Movatterモバイル変換


[0]ホーム

URL:


Title:Create Elegant Data Visualisations Using the Grammar of Graphics
Version:4.0.1
Description:A system for 'declaratively' creating graphics, based on "The Grammar of Graphics". You provide the data, tell 'ggplot2' how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.
License:MIT + file LICENSE
URL:https://ggplot2.tidyverse.org,https://github.com/tidyverse/ggplot2
BugReports:https://github.com/tidyverse/ggplot2/issues
Depends:R (≥ 4.1)
Imports:cli, grDevices, grid, gtable (≥ 0.3.6), isoband, lifecycle (>1.0.1), rlang (≥ 1.1.0), S7, scales (≥ 1.4.0), stats, vctrs(≥ 0.6.0), withr (≥ 2.5.0)
Suggests:broom, covr, dplyr, ggplot2movies, hexbin, Hmisc, hms, knitr,mapproj, maps, MASS, mgcv, multcomp, munsell, nlme, profvis,quantreg, quarto, ragg (≥ 1.2.6), RColorBrewer, roxygen2,rpart, sf (≥ 0.7-3), svglite (≥ 2.1.2), testthat (≥ 3.1.5),tibble, vdiffr (≥ 1.0.6), xml2
Enhances:sp
VignetteBuilder:quarto
Config/Needs/website:ggtext, tidyr, forcats, tidyverse/tidytemplate
Config/testthat/edition:3
Config/usethis/last-upkeep:2025-04-23
Encoding:UTF-8
LazyData:true
RoxygenNote:7.3.3
Collate:'ggproto.R' 'ggplot-global.R' 'aaa-.R''aes-colour-fill-alpha.R' 'aes-evaluation.R''aes-group-order.R' 'aes-linetype-size-shape.R''aes-position.R' 'all-classes.R' 'compat-plyr.R' 'utilities.R''aes.R' 'annotation-borders.R' 'utilities-checks.R''legend-draw.R' 'geom-.R' 'annotation-custom.R''annotation-logticks.R' 'scale-type.R' 'layer.R''make-constructor.R' 'geom-polygon.R' 'geom-map.R''annotation-map.R' 'geom-raster.R' 'annotation-raster.R''annotation.R' 'autolayer.R' 'autoplot.R' 'axis-secondary.R''backports.R' 'bench.R' 'bin.R' 'coord-.R' 'coord-cartesian-.R''coord-fixed.R' 'coord-flip.R' 'coord-map.R' 'coord-munch.R''coord-polar.R' 'coord-quickmap.R' 'coord-radial.R''coord-sf.R' 'coord-transform.R' 'data.R' 'docs_layer.R''facet-.R' 'facet-grid-.R' 'facet-null.R' 'facet-wrap.R''fortify-map.R' 'fortify-models.R' 'fortify-spatial.R''fortify.R' 'stat-.R' 'geom-abline.R' 'geom-rect.R''geom-bar.R' 'geom-tile.R' 'geom-bin2d.R' 'geom-blank.R''geom-boxplot.R' 'geom-col.R' 'geom-path.R' 'geom-contour.R''geom-point.R' 'geom-count.R' 'geom-crossbar.R''geom-segment.R' 'geom-curve.R' 'geom-defaults.R''geom-ribbon.R' 'geom-density.R' 'geom-density2d.R''geom-dotplot.R' 'geom-errorbar.R' 'geom-freqpoly.R''geom-function.R' 'geom-hex.R' 'geom-histogram.R''geom-hline.R' 'geom-jitter.R' 'geom-label.R''geom-linerange.R' 'geom-pointrange.R' 'geom-quantile.R''geom-rug.R' 'geom-sf.R' 'geom-smooth.R' 'geom-spoke.R''geom-text.R' 'geom-violin.R' 'geom-vline.R''ggplot2-package.R' 'grob-absolute.R' 'grob-dotstack.R''grob-null.R' 'grouping.R' 'properties.R' 'margins.R''theme-elements.R' 'guide-.R' 'guide-axis.R''guide-axis-logticks.R' 'guide-axis-stack.R''guide-axis-theta.R' 'guide-legend.R' 'guide-bins.R''guide-colorbar.R' 'guide-colorsteps.R' 'guide-custom.R''guide-none.R' 'guide-old.R' 'guides-.R' 'guides-grid.R''hexbin.R' 'import-standalone-obj-type.R''import-standalone-types-check.R' 'labeller.R' 'labels.R''layer-sf.R' 'layout.R' 'limits.R' 'performance.R''plot-build.R' 'plot-construction.R' 'plot-last.R' 'plot.R''position-.R' 'position-collide.R' 'position-dodge.R''position-dodge2.R' 'position-identity.R' 'position-jitter.R''position-jitterdodge.R' 'position-nudge.R' 'position-stack.R''quick-plot.R' 'reshape-add-margins.R' 'save.R' 'scale-.R''scale-alpha.R' 'scale-binned.R' 'scale-brewer.R''scale-colour.R' 'scale-continuous.R' 'scale-date.R''scale-discrete-.R' 'scale-expansion.R' 'scale-gradient.R''scale-grey.R' 'scale-hue.R' 'scale-identity.R''scale-linetype.R' 'scale-linewidth.R' 'scale-manual.R''scale-shape.R' 'scale-size.R' 'scale-steps.R' 'scale-view.R''scale-viridis.R' 'scales-.R' 'stat-align.R' 'stat-bin.R''stat-summary-2d.R' 'stat-bin2d.R' 'stat-bindot.R''stat-binhex.R' 'stat-boxplot.R' 'stat-connect.R''stat-contour.R' 'stat-count.R' 'stat-density-2d.R''stat-density.R' 'stat-ecdf.R' 'stat-ellipse.R''stat-function.R' 'stat-identity.R' 'stat-manual.R''stat-qq-line.R' 'stat-qq.R' 'stat-quantilemethods.R''stat-sf-coordinates.R' 'stat-sf.R' 'stat-smooth-methods.R''stat-smooth.R' 'stat-sum.R' 'stat-summary-bin.R''stat-summary-hex.R' 'stat-summary.R' 'stat-unique.R''stat-ydensity.R' 'summarise-plot.R' 'summary.R' 'theme.R''theme-defaults.R' 'theme-current.R' 'theme-sub.R''utilities-break.R' 'utilities-grid.R' 'utilities-help.R''utilities-patterns.R' 'utilities-resolution.R''utilities-tidy-eval.R' 'zxx.R' 'zzz.R'
NeedsCompilation:no
Packaged:2025-11-13 07:39:29 UTC; thomas
Author:Hadley WickhamORCID iD [aut], Winston ChangORCID iD [aut], Lionel Henry [aut], Thomas Lin PedersenORCID iD [aut, cre], Kohske Takahashi [aut], Claus WilkeORCID iD [aut], Kara WooORCID iD [aut], Hiroaki YutaniORCID iD [aut], Dewey DunningtonORCID iD [aut], Teun van den BrandORCID iD [aut], Posit, PBCROR ID [cph, fnd]
Maintainer:Thomas Lin Pedersen <thomas.pedersen@posit.co>
Repository:CRAN
Date/Publication:2025-11-14 09:20:02 UTC

ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics

Description

logo

A system for 'declaratively' creating graphics, based on "The Grammar of Graphics". You provide the data, tell 'ggplot2' how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.

Author(s)

Maintainer: Thomas Lin Pedersenthomas.pedersen@posit.co (ORCID)

Authors:

Other contributors:

See Also

Useful links:


Coords

Description

All⁠coord_*()⁠ functions (likecoord_transform()) return a⁠Coord*⁠ object(likeCoordTransform). These objects contain methods that support thecoordinate systems in ggplot2.

Details

Each of the⁠Coord*⁠ objects is aggproto() object, descended from thetop-levelCoord, and each implements various methods and fields.The object and its parameters are chaperoned by theLayout class.

To create a new type of Coord object, it is recommendedto extend not the baseCoord class, but one of its children likeCoordCartesian.

When overriding thetransform() method, it may be necessary to adapt theimplementation ofrender_bg() and possibly axis placement too.

An important data structure that coordinate systems create is thepanel_params structure. When overriding that structure, many methods mayneed to be adapted as well.

Fields

default

Scaler boolean indicating whether this is the defaultcoordinate system. Non-default coordinate systems raise a message whena new system replaces it.

clip

A scalar string grid setting controlling whether layers shouldbe clipped to the extent of the plot panel extent. Can be"on" toperform clipping,"off" to not clip, or"inherit" to take on thesetting of the parent viewport.

reverse

A scalar string giving which directions to reverse. ForCartesian systems, can be⁠"none⁠,"x","y" or"xy" for both.Non-Cartesian may define their own settings.

setup_params

Description

A function method for modifying or checking the parameters based on thedata. The default method parses theexpand parameter.

Usage

Coord$setup_params(data)

Arguments

data

A list of data frames. The first item is the global data,which is followed by layer data in subsequent items.

Value

A list of parameters

setup_data

Description

A function method for modifying or checking the data prior to addingdefaults. The default method returns data unaltered.

Usage

Coord$setup_data(data, params)

Arguments

data

A list of data frames. The first item is the global data,which is followed by layer data in subsequent items.

params

A list of parameters coming from thesetup_params()method.

Value

A list of data frames of the same length as thedata argument

setup_layout

Description

A function method that acts as a hook for the coordinate system to haveinput on the layout computed by facets.

Usage

Coord$setup_layout(layout, params)

Arguments

layout

A data frame computed byFacet$compute_layout().Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

params

A list of parameters coming from thesetup_params()method.

Value

A data frame from the modifiedlayout argument. The default creates anewCOORD column to identify unique combinations of x and y scales forefficiency purposes. It should never remove columns.

modify_scales

Description

A function method for modifying scales in place. This is optional andcurrently used by CoordFlip and CoordPolar to ensure axis positions areconforming to the coordinate system.

Usage

Coord$modify_scales(scales_x, scales_y)

Arguments

scales_x,scales_y

A list of trained scales for thex andyaesthetics respectively.

Value

Nothing, this is called for the side effect of modifying scales.

setup_panel_params

Description

This function method is used to setup panel parameters per panel.For efficiency reasons, this method is called once per combination ofx andy scales. It is used to instantiate ViewScale class objects andranges for position aesthetics and optionally append additionalparameters needed for thetransform() method and rendering axes.

Usage

Coord$setup_panel_params(scale_x, scale_y, params)

Arguments

scale_x,scale_y

A list of trained scales for thex andyaesthetics respectively.

params

A list of parameters coming from thesetup_params()method.

Value

A named list of view scales, ranges and other optional parameters.

setup_panel_guides

Description

This function method is used to initiate position guides for each panel.For efficiency reasons, this method is called once per combination ofxandy scales. For the primary and secondary positions, it should resolveguides coming from theplot$guides field andScale$guide fields andset appropriateGuide$params$position parameters.

Usage

Coord$setup_panel_guides(panel_params, guides, params)

Arguments

panel_params

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method.

guides

A⁠<Guides>⁠ ggproto class.

params

A list of parameters coming from thesetup_params()method.

Value

Thepanel_params object but with a Guides class object appended withthe name 'guides'.

setup_panel_guides

Description

This function method is used to train and transform position guides for eachpanel. For efficiency reasons, this method is called once per combinationofx andy scales.

Usage

Coord$train_panel_guides(panel_params, layers, params)

Arguments

panel_params

A list of ViewScale class objects, a Guides classobject and additional parameters from thesetup_panel_params() method.

layers

A list of layers fromplot$layers.

params

A list of parameters coming from thesetup_params()method.

Value

Thepanel_params object, but with trained and transformedguidesparameter.

transform

Description

This function method is used to apply transformations and rescale positionaesthetics. This method is used in several places:

  • The Geom drawing code, used throughcoord_munch() in many Geoms.

  • The Guide transform method

  • Panel grid transformation inrender_bg()

Usage

Coord$transform(data, panel_params)

Arguments

data

A data frame with columns for numeric position aesthetics.

panel_params

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method.

Value

Thedata argument with rescaled and transformed position aesthetics.

distance

Description

This function method is used to calculate distances between subsequentdata points.coord_munch() uses this method determine how many pointsshould be used to interpolate.

Usage

Coord$distance(x, y, panel_params)

Arguments

x,y

x and y coordinates of a set of points in data space.

panel_params

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method.

Value

Thedata argument with rescaled and transformed position aesthetics.

backtransform_range

Description

This function method is used to convert ranges from transformed coordinatesback into data coordinates. The data coordinates may possibly be scale-transformed. It is used incoord_munch() to ensure limits are in datacoordinates.

The back-transformation may be needed for coords such ascoord_transform(),where the range in the transformed coordinates differs from the range inthe untransformed coordinates.

Usage

Coord$backtransform_range(panel_params)

Arguments

panel_params

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method.

Value

A list containing numeric ranges forx andy in data coordinates.

range

Description

This function method is a small helper method to extract ranges from thepanel_params object. It exists becausepanel_params can be opaque attimes.

Usage

Coord$range(panel_params)

Arguments

panel_params

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method.

Value

A list containing numeric ranges forx andy.

draw_panel

Description

This function method is used to orchestrate decorating panel drawings withforeground and background drawings. It is called once per panel, invokestherender_fg() andrender_bg() methods and enforces theclip field.

Usage

Coord$draw_panel(panel, params, theme)

Arguments

panel

A grob containing drawn layers and facet foreground andbackground.

params

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method.

theme

Acomplete theme

Value

A grob with panel content.

render_fg

Description

This function method is used to draw the panel foreground. For allintents and purposes is just thepanel.border theme element, but you canrepurpose this method.

Usage

Coord$render_fg(panel_params, theme)

Arguments

panel_params

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method.

theme

Acomplete theme

Value

A grob with panel foreground.

render_bg

Description

This function method is used to draw the panel background. Typicallythis is a combination of thepanel.background andpanel.grid themeelements.

Usage

Coord$render_bg(panel_params, theme)

Arguments

panel_params

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method.

theme

Acomplete theme

Value

A grob with panel background.

labels

Description

This function method is used to format axis titles. It is used in somecoordinate systems to (conditionally) swap x and y labels.

Usage

Coord$labels(labels, panel_params)

Arguments

labels

A named list containing anx list and ay list. Thex andy lists haveprimary andsecondary labels.

panel_params

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method.

Value

A list with the same structure and names as thelabels argument.

aspect

Description

This function method that gives the aspect ratio for panels. It allows forCoordFixed to compute an aspect ratio based on data ranges.

Usage

Coord$render_bg(panel_params, theme)

Arguments

ranges

A list of ViewScale class objects and additionalparameters from thesetup_panel_params() method. If there aremultiple panels, the parameters for the first panel is used.

Value

A scalar numeric

render_axis_h,render_axis_v

Description

These function methods are used to render axes to place at the outside edgeof panels. Interior axes should not be rendered here. Therender_axis_h()methods produces the horizontal axes for the top and bottom position.Therender_axis_v() method renders the vertical axes for the left andright position.

Usage

Coord$render_axis_h(panel_params, themeCoord$render_axis_v(panel_params, theme)

Arguments

panel_params

A list of ViewScale class objects, a Guides classobject and additional parameters from thesetup_panel_params() method.

theme

Acomplete theme

Value

Forrender_axis_h() a named list where"top" and"bottom" are grobswith an axis. Forrender_axis_v() a named list where"left" and"right" are grobs with an axis. These grobs should bezeroGrob()when no axes should be rendered.

is_linear

Description

This function method is used to signal whether a coordinate system islinear. Incoord_munch() and several Geom drawing methods, it is used todetermine whether points should be interpolated.

Usage

Coord$is_linear()

Value

A scalar boolean.

is_free

Description

This function method is used to signal whether a coordinate system supportsfree scaling of axes in faceted plots. This should generally returnFALSEfor coordinate systems that enforce a fixed aspect ratio.

Usage

Coord$is_free()

Value

A scalar boolean.

Conventions

The object name that a new class is assigned to is typically the same as theclass name. Coord class names are in UpperCamelCase and start with the⁠Coord*⁠ prefix, likeCoordNew.

A constructor function is usually paired with a Coord class. The constructorcopies the coord class and populates parameters. The constructor function nameshould take the Coord class name and be formatted with snake_case,so thatCoordNew becomescoord_new().

See Also

Thenew coords section of the online ggplot2 book.

Other Layout components:Facet,Layout

Examples

# Extending the classCoordJitter <- ggproto(  "CoordJitter", CoordCartesian,  # Fields  amount = 0,  # Methods  is_linear = function() FALSE,  transform = function(self, data, panel_params) {    data   <- ggproto_parent(CoordCartesian, self)$transform(data, panel_params)    data$x <- jitter(data$x, amount = self$amount)    data$y <- jitter(data$y, amount = self$amount)    data  })# Building a constructorcoord_jitter <- function(amount = 0.005, xlim = NULL, ylim = NULL, expand = TRUE,                         clip = "on", reverse = "none") {  ggproto(    NULL, CoordJitter,    amount = amount,    limits = list(x = xlim, y = ylim),    reverse = reverse, expand = expand, clip = clip  )}# Use new coord in plotset.seed(42)ggplot(mpg, aes(drv, displ)) +  geom_boxplot() +  coord_jitter()

Visualise sf objects

Description

This set of geom, stat, and coord are used to visualise simple feature (sf)objects. For simple plots, you will only needgeom_sf() as itusesstat_sf() and addscoord_sf() for you.geom_sf() isan unusual geom because it will draw different geometric objects dependingon what simple features are present in the data: you can get points, lines,or polygons.For text and labels, you can usegeom_sf_text() andgeom_sf_label().

Usage

coord_sf(  xlim = NULL,  ylim = NULL,  expand = TRUE,  crs = NULL,  default_crs = NULL,  datum = sf::st_crs(4326),  label_graticule = waiver(),  label_axes = waiver(),  lims_method = "cross",  ndiscr = 100,  default = FALSE,  clip = "on",  reverse = "none")geom_sf(  mapping = aes(),  data = NULL,  stat = "sf",  position = "identity",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE,  ...)geom_sf_label(  mapping = aes(),  data = NULL,  stat = "sf_coordinates",  position = "nudge",  ...,  parse = FALSE,  label.padding = unit(0.25, "lines"),  label.r = unit(0.15, "lines"),  label.size = deprecated(),  border.colour = NULL,  border.color = NULL,  text.colour = NULL,  text.color = NULL,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE,  fun.geometry = NULL)geom_sf_text(  mapping = aes(),  data = NULL,  stat = "sf_coordinates",  position = "nudge",  ...,  parse = FALSE,  check_overlap = FALSE,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE,  fun.geometry = NULL)stat_sf(  mapping = NULL,  data = NULL,  geom = "rect",  position = "identity",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE,  ...)

Arguments

xlim,ylim

Limits for the x and y axes. These limits are specifiedin the units of the default CRS. By default, this means projected coordinates(default_crs = NULL). How limit specifications translate into the exactregion shown on the plot can be confusing when non-linear or rotated coordinatesystems are used as the default crs. First, different methods can be preferableunder different conditions. See parameterlims_method for details. Second,specifying limits along only one direction can affect the automatically generatedlimits along the other direction. Therefore, it is best to always specify limitsfor both x and y. Third, specifying limits via position scales orxlim()/ylim()is strongly discouraged, as it can result in data points being dropped from the plot eventhough they would be visible in the final plot region.

expand

IfTRUE, the default, adds a small expansion factor tothe limits to ensure that data and axes don't overlap. IfFALSE,limits are taken exactly from the data orxlim/ylim.Giving a logical vector will separately control the expansion for the fourdirections (top, left, bottom and right). Theexpand argument will berecycled to length 4 if necessary. Alternatively, can be a named logicalvector to control a single direction, e.g.expand = c(bottom = FALSE).

crs

The coordinate reference system (CRS) into which all data shouldbe projected before plotting. If not specified, will use the CRS definedin the first sf layer of the plot.

default_crs

The default CRS to be used for non-sf layers (whichdon't carry any CRS information) and scale limits. The default value ofNULL means that the setting forcrs is used. This implies that allnon-sf layers and scale limits are assumed to be specified in projectedcoordinates. A useful alternative setting isdefault_crs = sf::st_crs(4326),which means x and y positions are interpreted as longitude and latitude,respectively, in the World Geodetic System 1984 (WGS84).

datum

CRS that provides datum to use when generating graticules.

label_graticule

Character vector indicating which graticule lines should be labeledwhere. Meridians run north-south, and the letters"N" and"S" indicate thatthey should be labeled on their north or south end points, respectively.Parallels run east-west, and the letters"E" and"W" indicate that theyshould be labeled on their east or west end points, respectively. Thus,label_graticule = "SW" would label meridians at their south end and parallels attheir west end, whereaslabel_graticule = "EW" would label parallels at bothends and meridians not at all. Because meridians and parallels can in generalintersect with any side of the plot panel, for any choice oflabel_graticule labelsare not guaranteed to reside on only one particular side of the plot panel. Also,label_graticule can cause labeling artifacts, in particular if a graticule linecoincides with the edge of the plot panel. In such circumstances,label_axes willgenerally yield better results and should be used instead.

This parameter can be used alone or in combination withlabel_axes.

label_axes

Character vector or named list of character valuesspecifying which graticule lines (meridians or parallels) should be labeled onwhich side of the plot. Meridians are indicated by"E" (for East) andparallels by"N" (for North). Default is"--EN", which specifies(clockwise from the top) no labels on the top, none on the right, meridianson the bottom, and parallels on the left. Alternatively, this setting could have beenspecified withlist(bottom = "E", left = "N").

This parameter can be used alone or in combination withlabel_graticule.

lims_method

Method specifying how scale limits are converted intolimits on the plot region. Has no effect whendefault_crs = NULL.For a very non-linear CRS (e.g., a perspective centeredaround the North pole), the available methods yield widely differing results, andyou may want to try various options. Methods currently implemented include"cross"(the default),"box","orthogonal", and"geometry_bbox". For method"cross",limits along one direction (e.g., longitude) are applied at the midpoint of theother direction (e.g., latitude). This method avoids excessively large limits forrotated coordinate systems but means that sometimes limits need to be expanded alittle further if extreme data points are to be included in the final plot region.By contrast, for method"box", a box is generated out of the limits along both directions,and then limits in projected coordinates are chosen such that the entire box isvisible. This method can yield plot regions that are too large. Finally, method"orthogonal" applies limits separately along each axis, and method"geometry_bbox" ignores all limit information except the bounding boxes of anyobjects in thegeometry aesthetic.

ndiscr

Number of segments to use for discretising graticule lines;try increasing this number when graticules look incorrect.

default

Is this the default coordinate system? IfFALSE (the default),then replacing this coordinate system with another one creates a message alertingthe user that the coordinate system is being replaced. IfTRUE, that warningis suppressed.

clip

Should drawing be clipped to the extent of the plot panel? Asetting of"on" (the default) means yes, and a setting of"off"means no. In most cases, the default of"on" should not be changed,as settingclip = "off" can cause unexpected results. It allowsdrawing of data points anywhere on the plot, including in the plot margins. Iflimits are set viaxlim andylim and some data points fall outside thoselimits, then those data points may show up in places such as the axes, thelegend, the plot title, or the plot margins.

reverse

A string giving which directions to reverse."none"(default) keeps directions as is."x" and"y" can be used to reversetheir respective directions."xy" can be used to reverse bothdirections.

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.

You can also set this to one of "polygon", "line", and "point" tooverride the default legend.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

parse

IfTRUE, the labels will be parsed into expressions anddisplayed as described in?plotmath.

label.padding

Amount of padding around label. Defaults to 0.25 lines.

label.r

Radius of rounded corners. Defaults to 0.15 lines.

label.size

[Deprecated] Replaced by thelinewidth aesthetic. Size of label border, in mm.

border.colour,border.color

Colour of label border. WhenNULL(default), thecolour aesthetic determines the colour of the label border.border.color is an alias forborder.colour.

text.colour,text.color

Colour of the text. WhenNULL (default), thecolour aesthetic determines the colour of the text.text.color is analias fortext.colour.

fun.geometry

A function that takes asfc object and returns asfc_POINT with thesame length as the input. IfNULL,function(x) sf::st_point_on_surface(sf::st_zm(x))will be used. Note that the function may warn about the incorrectness ofthe result if the data is not projected, but you can ignore this exceptwhen you really care about the exact locations.

check_overlap

IfTRUE, text that overlaps previous text in thesame layer will not be plotted.check_overlap happens at draw time and inthe order of the data. Therefore data should be arranged by the labelcolumn before callinggeom_text(). Note that this argument is notsupported bygeom_label().

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

Geometry aesthetic

geom_sf() uses a unique aesthetic:geometry, giving ancolumn of classsfc containing simple features data. Thereare three ways to supply thegeometry aesthetic:

Unlike other aesthetics,geometry will never be inherited fromthe plot.

CRS

coord_sf() ensures that all layers use a common CRS. You caneither specify it using thecrs param, orcoord_sf() willtake it from the first layer that defines a CRS.

Combining sf layers and regular geoms

Most regular geoms, such asgeom_point(),geom_path(),geom_text(),geom_polygon() etc. will work fine withcoord_sf(). Howeverwhen using these geoms, two problems arise. First, what CRS should be usedfor the x and y coordinates used by these non-sf geoms? The CRS applied tonon-sf geoms is set by thedefault_crs parameter, and it defaults toNULL, which means positions for non-sf geoms are interpreted as projectedcoordinates in the coordinate system set by thecrs parameter. This settingallows you complete control over where exactly items are placed on the plotcanvas, but it may require some understanding of how projections work and howto generate data in projected coordinates. As an alternative, you can setdefault_crs = sf::st_crs(4326), the World Geodetic System 1984 (WGS84).This means that x and y positions are interpreted as longitude and latitude,respectively. You can also specify any other valid CRS as the default CRS fornon-sf geoms.

The second problem that arises for non-sf geoms is how straight linesshould be interpreted in projected space whendefault_crs is not set toNULL.The approachcoord_sf() takes is to break straight lines into small pieces(i.e., segmentize them) and then transform the pieces into projected coordinates.For the default setting where x and y are interpreted as longitude and latitude,this approach means that horizontal lines follow the parallels and vertical linesfollow the meridians. If you need a different approach to handling straight lines,then you should manually segmentize and project coordinates and generate the plotin projected coordinates.

See Also

Thesimple feature maps section of the online ggplot2 book.

stat_sf_coordinates()

Examples

if (requireNamespace("sf", quietly = TRUE)) {nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)ggplot(nc) +  geom_sf(aes(fill = AREA))# If not supplied, coord_sf() will take the CRS from the first layer# and automatically transform all other layers to use that CRS. This# ensures that all data will correctly line upnc_3857 <- sf::st_transform(nc, 3857)ggplot() +  geom_sf(data = nc) +  geom_sf(data = nc_3857, colour = "red", fill = NA)# Unfortunately if you plot other types of feature you'll need to use# show.legend to tell ggplot2 what type of legend to usenc_3857$mid <- sf::st_centroid(nc_3857$geometry)ggplot(nc_3857) +  geom_sf(colour = "white") +  geom_sf(aes(geometry = mid, size = AREA), show.legend = "point")# You can also use layers with x and y aesthetics. To have these interpreted# as longitude/latitude you need to set the default CRS in coord_sf()ggplot(nc_3857) +  geom_sf() +  annotate("point", x = -80, y = 35, colour = "red", size = 4) +  coord_sf(default_crs = sf::st_crs(4326))# To add labels, use geom_sf_label().ggplot(nc_3857[1:3, ]) +   geom_sf(aes(fill = AREA)) +   geom_sf_label(aes(label = NAME))}# Thanks to the power of sf, a geom_sf nicely handles varying projections# setting the aspect ratio correctly.if (requireNamespace('maps', quietly = TRUE)) {library(maps)world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE))ggplot() + geom_sf(data = world1)world2 <- sf::st_transform(  world1,  "+proj=laea +y_0=0 +lon_0=155 +lat_0=-90 +ellps=WGS84 +no_defs")ggplot() + geom_sf(data = world2)}

Facets

Description

All⁠facet_*()⁠ functions returns aFacet object or an object of aFacet subclass. This object describes how to assign data to differentpanels, how to apply positional scales and how to lay out the panels, oncerendered.

Details

Extending facets can range from the simple modifications of current facets,to very laborious rewrites with a lot ofgtable()manipulation.For some examples of both, please see the extension vignette.The object and its parameters are chaperoned by theLayout class.

Facet subclasses, like other extendible ggproto classes, have a rangeof methods that can be modified. Some of these are required for all newsubclasses, while other only need to be modified if need arises.

The required methods are:

In addition to the methods above, it can be useful to override the defaultbehaviour of one or more of the following methods:

All extension methods receive the content of the params field as the paramsargument, so the constructor function will generally put all relevantinformation into this field.

Fields

shink

A scalar boolean which whenTRUE, will shrink scales tofit output statistics rather than raw data. IfFALSE, will only includeraw data before statistical summary. By exception this is not part of theparams field.

params

A named list of parameters populated by the constructorfunction.

setup_params

Description

A function method for modifying or checking the parameters based on thedata. The default method includes a.possible_columns variable givingcolumn names.

Usage

Facet$setup_params(data, params)

Arguments

data

A list of data frames. The first item is the global data,which is followed by layer data in subsequent items.

params

A list of current parameters.

Value

A list of parameters

setup_data

Description

A function method for modifying or checking the data prior to addingdefaults. The default method returns data unaltered.

Usage

Facet$setup_data(data, params)

Arguments

data

A list of data frames. The first item is the global data,which is followed by layer data in subsequent items.

params

A list of parameters coming from thesetup_params()method.

Value

A list of data frames of the same length as thedata argument

compute_layout

Description

A function method for creating the correspondence between facetingvariable levels, panels and position scales. It places panels like cellsin a matrix.

Usage

Facet$compute_layout(data, params)

Arguments

data

A list of data frames. The first item is the global data,which is followed by layer data in subsequent items.

params

A list of parameters coming from thesetup_params()method.

Value

A data frame with 1 row per panel, containing at least integer columnsROW,COL,PANEL,SCALE_X andSCALE_Y. Can contain additionalinformation in terms of columns, typically faceting variables.

map_data

Description

A function method for to create thePANEL variable in layer data. ThePANEL variable is a special variable that tracks the relationship betweenrows in the layer data and the panels described in thelayout input.

In addition, #' this function may copy or discard rows as needed, forexample when adding margins in FacetGrid.

Usage

Facet$map_data(data, layout, params)

Arguments

data

A list of data frames containing layer data.

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

params

A list of parameters coming from thesetup_params()method.

Value

A list of data frames containing layer data including aPANEL variable.

init_scales

Description

A function method for initialising position scales. Given a prototype scaleforx andy, creates layout specific scales to accommodatethe relationships between panels and scales. By default, the prototypescales are cloned for eachSCALE_X andSCALE_Y level. The function iscalled separately; once forx and once fory.

Usage

Facet$init_scales(layout, x_scale, y_scale, params)

Arguments

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

x_scale,y_scale

A position scale for thex andyaesthetics respectively.

params

A list of parameters coming from thesetup_params()method.

Value

A named list withx andy elements containing a list of panel scalesfor eachSCALE_X and/orSCALE_Y level respectively.

train_scales

Description

A function method for training position scales. The default trains eachscale on the data related to its panels.

Usage

Facet$train_scales(x_scales, y_scales, layout, data, params)

Arguments

x_scales,y_scales

A list of panel scales for eachSCALE_XandSCALE_Y level respectively.

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

data

A list of data frames containing layer data.

params

A list of parameters coming from thesetup_params()method.

Value

Nothing, this method is called for its side-effect of training the scales.

setup_panel_params

Description

A function method as a hook to give facets input over panel parameters. Bydefault, returns panel parameters unaltered.

Usage

Facet$setup_panel_params(panel_params, coord, ...)

Arguments

panel_params

A named list of view scales, ranges and otheroptional parameters fromCoord$setup_panel_params().

coord

A⁠<Coord>⁠ ggproto object.

...

Currently not in use. For future expansion.

Value

A list of panel parameters.

finish_data

Description

A function method as a hook for making last-minute modifications to layerdata before it is rendered by Geoms. The default is to not modify the data.

Usage

Facet$finish_data(data, layout, x_scales, y_scales, params)

Arguments

data

A data frame containing layer data of a single layer.

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

x_scales,y_scales

A list of panel scales for eachSCALE_XandSCALE_Y level respectively.

params

A list of parameters coming from thesetup_params()method.

Value

A data frame containing layer data.

draw_panel_content

Description

A function method to assemble the panel contents. It delegates thedraw_back() anddraw_front() methods, as well asCoord$draw_panel().

Usage

Facet$draw_panel_content(  panels,  layout,  x_scales,  y_scales,  ranges,  coord,  theme,  params,  ...)

Arguments

panels

A list parallel to layers. Each element is another listwith grobs for each panel, generated byLayer$draw_geom().

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

x_scales,y_scales

A list of panel scales for eachSCALE_XandSCALE_Y level respectively.

ranges

A list of panel parameters from thesetup_panel_params() augmented with position guides.

coord

A⁠<Coord>⁠ ggproto object.

data

A list of data frames containing layer data.

theme

Acomplete theme object.

params

A list of parameters coming from thesetup_params()method.

...

Currently not in use.

Value

A list of grobs, one for each level of thePANEL layout variable. Grobcan bezeroGrob() to draw nothing.

draw_back,draw_front

Description

A function method draw facet background (back) and foreground (front) forpanels. The front and back will sandwich the grobs created by layers. Thedefault methods draw nothing.

Usage

Facet$draw_back(data, layout, x_scales, y_scales, theme, params)Facet$draw_front(data, layout, x_scales, y_scales, theme, params)

Arguments

data

A list of data frames containing layer data.

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

x_scales,y_scales

A list of panel scales for eachSCALE_XandSCALE_Y level respectively.

theme

Acomplete theme object.

params

A list of parameters coming from thesetup_params()method.

Value

A list of grobs, one for each level of thePANEL layout variable. Grobcan bezeroGrob() to draw nothing.

draw_panels

Description

A function method that orchestrates the majority of facet drawing. It isresponsible for assembling a gtable with panel content decorated with axesand strips. The resulting gtable is the basis for the plot in its entirety.It delegates these tasks to theinit_gtable(),attach_axes() andattach_strips() methods.

Usage

Facet$draw_panels(  panels,  layout,  x_scales,  y_scales,  ranges,  coord,  data,  theme,  params)

Arguments

panels

A list of grobs, one per panel.

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

x_scales,y_scales

A list of panel scales for eachSCALE_XandSCALE_Y level respectively.

ranges

A list of panel parameters from thesetup_panel_params() augmented with position guides.

coord

A⁠<Coord>⁠ ggproto object.

data

A list of data frames containing layer data.

theme

Acomplete theme object.

params

A list of parameters coming from thesetup_params()method.

Value

Agtable object.

init_gtable

Description

A function method that initiates a gtable object containing panels setat the appropriateROW andCOL cells from the layout. The panels areseparated by the⁠panel.spacing.{x/y}⁠ spacing.

Usage

Facet$init_gtable(panels, layout, theme, ranges, params, aspect_ratio)

Arguments

panels

A list of grobs, one per panel.

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

theme

Acomplete theme object.

ranges

A list of panel parameters from thesetup_panel_params() augmented with position guides.

aspect_ratio

A scalar numeric for the panel aspect ratio orNULL for no aspect ratio.

Value

Agtable object containing panel grobs prefixed with"panel".

attach_axes

Description

A function method that renders position guides (axes) and attaches theseto the gtable with panels. The default method returns the gtable unaltered.

Usage

Facet$attach_axes(table, layout, ranges, coord, theme, params)

Arguments

table

Agtable object populated with panels from theinit_gtable() method.

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

ranges

A list of panel parameters from thesetup_panel_params() augmented with position guides.

coord

A⁠<Coord>⁠ ggproto object.

theme

Acomplete theme object.

params

A list of parameters coming from thesetup_params()method.

Value

Agtable object.

attach_strips

Description

A function method that renders strips and attaches these to the gtablewith panels and axes. Theformat_strip_labels() method is used to formatthe strip text. The default method returns the gtable unaltered.

Usage

Facet$attach_strips(table, layout, ranges, coord, theme, params)

Arguments

table

Agtable object from theattach_axes()method.

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

params

A list of parameters coming from thesetup_params()method.

theme

Acomplete theme object.

Value

Agtable object.

format_strip_labels

Description

A function method that formats the text for strips. It is used in theattach_strips methods, but also theget_strip_labels() function.The default method returnsNULL.

Usage

Facet$format_strip_labels(layout, params)

Arguments

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

params

A list of parameters coming from thesetup_params()method.

Value

A list containing a data frame with strip labels.

set_panel_size

Description

A function method that enforces thepanel.widths andpanel.heightstheme settings.

Usage

Facet$set_panel_size(table, theme)

Arguments

table

Agtable object populated by thedraw_panels() method.

theme

Acomplete theme object.

Value

Thetable object, optionally with differentwidths andheightsproperties.

attach_axes

Description

A function method that renders axis titles and adds them to the gtable.The default is to add one title at each side depending on the positionand presence of axes.

Usage

Facet$draw_labels(  panels,  layout,  x_scales,  y_scales,  ranges,  coord,  data,  theme,  labels,  params)

Arguments

panels

Agtable object initiated by thedraw_panels() method.

layout

A data frame computed by thecompute_layout() method.Typically contains the faceting variables,ROW,COL,PANEL,SCALE_X andSCALE_Y variables.

x_scales,y_scales

A list of panel scales for eachSCALE_XandSCALE_Y level respectively.

ranges

A list of panel parameters from thesetup_panel_params() augmented with position guides.

coord

A⁠<Coord>⁠ ggproto object.

data

A list of data frames containing layer data.

theme

Acomplete theme object.

labels

A named list containing anx list andy list. Thex andy lists haveprimary andsecondary labels.

params

A list of parameters coming from thesetup_params()method.

Value

Agtable object.

vars

Description

A function method that returns the names of faceting variables. Thedefault method returns an character vector with 0 length.

Usage

Facet$vars()

Value

A character vector

Conventions

The object name that a new class is assigned to is typically the same as theclass name. Facet class names are in UpperCamelCase and start with the⁠Facet*⁠ prefix, likeFacetNew.

A constructor function is usually paired with a Facet class. The constructorcopies the facet class and populates theparams field. The constructorfunction name should take the Facet class name and be formatted withsnake_case, so thatFacetNew becomesfacet_new().

See Also

The thenew facets section of the online ggplot2 book.

Runvignette("extending-ggplot2"), in particular the "Creating anew faceting" section.

Other Layout components:Coord,Layout

Examples

# Please see extension vignetteNULL

Geoms

Description

All⁠geom_*()⁠ functions (likegeom_point()) return a layer thatcontains a⁠Geom*⁠ object (likeGeomPoint). The⁠Geom*⁠object is responsible for rendering the data in the plot.

Details

Each of the⁠Geom*⁠ objects is aggproto() object, descendedfrom the top-levelGeom, and each implements various methods andfields. The object and its parameters are chaperoned by theLayer class.

Compared toStat andPosition,Geom is a littledifferent because the execution of the setup and compute functions issplit up.setup_data runs before position adjustments, anddraw_layer() is not run until render time, much later.

When creating a new Geom class, you may want to consider override one ormore of the following:

Fields

required_aes

A character vector naming aesthetics that are necessaryto render the geom.

non_missing_aes

A character vector naming aesthetics that will causeremoval if they have missing values.

optional_aes

A character vector naming aesthetics that will beaccepted bylayer(), but are not required or described in thedefault_aes field.

default_aes

Amapping of default values for aesthetics.Aesthetics can be set toNULL to be included as optional aesthetic.

rename_size

A scalar boolean: whether to renamesize aesthetics tolinewidth.

extra_params

A character vector of parameter names in addition tothose imputed from thedraw_panel() ordraw_groups() methods. Thisfield can be set to include parameters forsetup_data() orhandle_na()methods. By default, this only contains"na.rm".

draw_key

A function generating a single legend glyph for the geom.Typically one of the functions prefixed bydraw_key_.

setup_params

Description

A function method for modifying or checking the parameters based on thedata. The default method returns the parameters unaltered.

Usage

Geom$setup_params(data, params)

Arguments

data

A data frame with the layer's data.

params

A list of current parameters.

Value

A list of parameters

setup_data

Description

A function method for modifying or checking the data prior to addingdefaults. The default method returns data unaltered.

Usage

Geom$setup_data(data, params)

Arguments

data

A data frame with the layer's data.

params

A list of parameters coming from thesetup_params()method.

Value

A data frame with layer data

use_defaults

Description

A function method for completing the layer data by filling in defaultaesthetics that are not present. It is not recommended to use as anextension point.

It takes on these tasks:

  • Evaluation of default aesthetics from thedefault_aes field.

  • Handling theafter_scale()/stage(after_scale) stage of delayedevaluation.

  • Fill in fixed, unmapped aesthetics passed as parameters.

Usage

Geom$use_defaults(data, params, modifiers, default_aes, theme, ...)

Arguments

data

A data frame of the layer's data, coming from thesetup_data() method. Can beNULL, in which case resolved defaultsshould be returned.

params

A list of fixed aesthetic parameters

modifiers

Amapping with delayed evaluations.

default_aes

Amapping with default aesthetics.

theme

Acompleted theme.

Value

A data frame with completed layer data.

handle_na

Description

A function method to handle missing values. The default method willremove rows that have missing values for the aesthetics listed in therequired_aes andnon_missing_aes fields. It is not recommended touse this method as an extension point.

Usage

Geom$handle_na(data, params)

Arguments

data

A data frame with the layer's data coming from theupdate_defaults() method.

params

A list of parameters coming from thesetup_params()method

Value

A data frame with layer data

draw_layer

Description

A function method orchestrating the drawing of the entire layer. Thedefault method splits the data and passes on drawing tasks to thepanel-leveldraw_panel() method. It is not recommended to use this methodas an extension point.

Usage

Geom$draw_layer(data, params, layout, coord)

Arguments

data

A data frame with the layer's data.

params

A list of parameters

layout

A completed⁠<Layout>⁠ ggproto object.

coord

A⁠<Coord>⁠ ggproto object.

Value

A list of grobs, one per panel

draw_panel,draw_group

Description

A function method orchestrating the drawing of the layer for a singlepanel or group. The defaultdraw_panel() method splits the data into groups,passes on the drawing tasks to the group-leveldraw_group() method andfinally assembles these into a single grob. The defaultdraw_group methodis not implemented.

Usage

Geom$draw_panel(data, panel_params, coord, ...)Geom$draw_group(data, panel_params, coord, ...)

Arguments

data

A data frame with the layer's data.

panel_params

A list of per-panel parameters constructed byCoord$setup_panel_params(). This should be considered an opaque datastructure that is just passed along when calling coord methods.

coord

A⁠<Coord>⁠ ggproto object. To correctly scale theposition data, one should always callcoord$transform(data, panel_params). When working with non-linearcoordinate systems, data should be converted to fit a primitive geom(e.g. point, path or polygon) and passed on to the corresponding drawmethod formunching.

...

Reserved for extensions. By default, this is passed on tothedraw_group() method.

Value

A single grob orzeroGrob() when there is nothing to draw. Fordraw_panel() this can be agTree holding individual grobsfrom thedraw_group() method.

parameters

Description

A function method for listing out all acceptable parameters for this geom.

Usage

Geom$parameters(extra)

Arguments

extra

A boolean: whether to include theextra_params field.

Value

A character vector of parameter names.

aesthetics

Description

A function method for listing out all acceptable aesthetics for this geom.

Usage

Geom$aesthetics()

Value

A character vector of aesthetic names.

Conventions

The object name that a new class is assigned to is typically the same asthe class name. Geom class names are in UpperCamelCase and start with the⁠Geom*⁠ prefix, likeGeomNew.

A constructor function is usually paired with a Geom class. The constructorwraps a call tolayer(), where e.g.layer(geom = GeomNew). The constructorfunction name is formatted by taking the Geom class name and formatting itwith snake_case, so thatGeomNew becomesgeom_new().

See Also

Thenew geoms section of the online ggplot2 book.

Runvignette("extending-ggplot2"), in particular the "Creating anew geom" section.

Other Layer components:Layer-class,Position,Stat

Examples

# Extending the classGeomSimplePoint <- ggproto(  "GeomSimplePoint", Geom,  # Fields  required_aes = c("x", "y"),  draw_key     = draw_key_point,  # Methods  draw_panel = function(data, panel_params, coord) {    data <- coord$transform(data, panel_params)    grid::pointsGrob(data$x, data$y)  })# Building a constructorgeom_simple_point <- function(mapping = NULL, data = NULL, stat = "identity",                              position = "identity", ..., na.rm = FALSE,                              show.legend = NA, inherit.aes = TRUE) {  layer(    mapping = mapping, data = data,    geom = GeomSimplePoint, stat = stat, position = position,    show.legend = show.legend, inherit.aes = inherit.aes,    params = list(na.rm = na.rm, ...)  )}# Use new geom in plotggplot(mpg, aes(displ, hwy)) +  geom_simple_point()

Guides

Description

The⁠guide_*⁠ functions (likeguide_legend()) return⁠Guide*⁠ objects(likeGuideLegend). The⁠Guide*⁠ object is responsible for rendering theguide for at least one aesthetic.

Details

Each of the⁠Guide*⁠ objects is aggproto() object, descended from thetop-levelGuide, and each implements various methods and fields.

Building a guide has three stages:

  1. The guide extracts the relevant information from scales.

  2. The guide interacts with other parts of the plot, like coords or layers tosupplement information.

  3. The guide is rendered.

When creating a new Guide class, you may want to consider overriding one ormore of the following:

Fields

params

A list of initial parameters that the guide needs tofunction. The baseGuide$params contains mandatory parameters,but extensions can add new parameters. It has the following roles:

  • It provides the default values for parameters.

  • names(params) determines what are valid arguments fornew_guide().

  • During build stages, a mutable copy ofparams holds informationabout the guide.

available_aes

A character vector of aesthetic names for which theguide is appropriate. Can use keyword"any" to indicate all non-positionaesthetics.

elements

A named list of strings stating which theme elements thisguide uses. By default, strings will be translated inGuide$setup_elements() usingcalc_element(). Strings are expected tooccur innames(get_element_tree()), like"legend.text" for example.Position guides typically append the⁠{aes}.{position}⁠ suffix in thesetup_elements() method when the position is known.

hashables

A list of calls or names constructed byrlang::exprs()indicating objects in theparams field. These will be evaluated in thecontext of theparams field and the resulting list will be hashed. Thehash uniquely identify guides that can merge. Guides that have differenthashes will not merge. For extensions, you should include objects thatclearly mark two guides from one another that cannot be merged.

train

Description

A function method for orchestrating the training of a guide, which extractsnecessary information from a Scale object. As orchestrator, this method isnot intended for extension.

Usage

Guide$train(params, scale, aesthetic, ...)

Arguments

params

A list of parameters initiated by theparams field.

scale

A⁠<Scale>⁠ ggproto object. In the case of positionguides, can be a⁠<ViewScale>⁠ ggproto object.

aesthetic

A scalar string specifying the aesthetic.If missing (default), it will use the first aesthetic specified in thescale.

...

Additional parameters passed on to theextract_params()method.

Value

A modified list of parameters

extract_key

Description

A function method for extracting break information from the scale calledthe 'key'. It retrieves breaks, maps these breaks and derives labels. Theseform the basis for tick marks and labels in some guides. It is appropriateto override in extensions.

Usage

Guide$extract_key(scale, aesthetic, ...)

Arguments

scale

A⁠<Scale>⁠ ggproto object. In the case of positionguides, can be a⁠<ViewScale>⁠ ggproto object.

aesthetic

A scalar string specifying the aesthetic.

...

Optional arguments from theparams field.

Value

A 'key' data frame containing annotated scale breaks, including at least acolumn for the aesthetic,.label and.value. If there are no breaks,returnsNULL.

extract_decor

Description

A function method for extracting 'decor' from the scale. The 'decor' actsas a wildcard for anything the guide may need to render that is not basedon the key. For this reason, it has guide specific meaning that indicatesdifferent things for different guides. Inguide_colourbar() it is thecolour gradient, but inguide_axis() it is the axis line information.It is appropriate to override in extensions.

Usage

Guide$extract_decor(scale, aesthetic, ...)

Arguments

scale

A⁠<Scale>⁠ ggproto object. In the case of positionguides, can be a⁠<ViewScale>⁠ ggproto object.

aesthetic

A scalar string specifying the aesthetic.

...

Optional arguments from theparams field.

Value

Undefined.NULL by default.

extract_params

Description

A function method for extracting any other information from the scale thatthe guide may need. A typical example is to derive the title from the scale,or apply any edits to thekey ordecor variables.

Usage

Geom$extract_params(scale, params, ...)

Arguments

scale

A⁠<Scale>⁠ ggproto object. In the case of positionguides, can be a⁠<ViewScale>⁠ ggproto object.

params

A list of parameters initiated by theparams field,which at this point includes thekey anddecor from previousextractors.

...

Additional arguments passed from thetrain() method. Fornon-position guides, often includestitle as derived from theplot$labels field.

Value

A modified list of parameters

transform

Description

A function method to apply coord transformation and munching to the'key' and 'decor' parameters. This method only applies to position guideslikeguide_axis() and is not called for non-position guides. It isrecommended to override this method if you have a position guide thatdoes not inherit fromGuideAxis or has custom key' or 'decor' structuresthatGuideAxis$transform() does not handle well.

Usage

Guide$transform(params, coord, ...)

Arguments

params

A list of parameters initiated by theparams field.

coord

A⁠<Coord>⁠ ggproto object.

...

Optional arguments, typicallypanel_params for mostposition guides.

Value

A list of parameters. The default throws an error.

merge

Description

A function method for combining information from two guides. When twoguides have the same computedhash parameter derived from thehashablesfield, this function will be called to merge them. If more than two guidesneed to be merged, they are merged successively in aReduce()-likefashion.

Merging guides is the mechanism by whichguide_legend() can take oneguide trained on theshape scale, another trained on thecolour scaleand display them together in the same guide, for example.

Overriding this method is recommended if the extension descends directlyfromGuide and not its children. Otherwise, it should be overridden ifpresented with no superior options.

Usage

Guide$merge(params, new_guide, new_params)

Arguments

params

A list of parameters derived from theparams field ofthis guide.

new_guide

A⁠<Guide>⁠ ggproto object representing the other guide class

new_params

A list of parameters derived from theparams fieldof the other guide

Value

A named list containingguide andparams, whereguide is a⁠<Guide>⁠ggproto object andparams is a list with parameters. By default, returnsthe new guide and its parameters.

process_layers,get_layer_key

Description

These function methods extract information from layers that the guide mayneed. Theprocess_layers() method is tasked with selecting layers thatare represented by the guide and are to be included. The selected layersshould be passed on to theget_layer_key() method.

Typical use of these methods is forguide_legend() to extract theGeom$draw_key function to render glyphs in addition to any default orfixed aesthetics. While these methods are called in position guides,thelayers anddata arguments are empty as these are unavailable atthat point.

You can overrideget_layer_key(), butprocess_layers() shouldprobably only be overridden if the extension does not inherit fromGuideLegend.

Usage

Guide$process_layers(params, layers, data, theme)Guide$get_layer_key(params, layers, data, theme)

Arguments

params

A list of parameters initiated by theparams field.

layers

A list of layers fromplot$layers.

data

A list of layer data frames.

theme

Acompleted theme object.

Value

A list of parameters

draw

Description

A function method is the main orchestrator for drawing the guide. It setsup the final pieces in context of the position, direction and themeand. Subsequenty, it renders the individual components like titles, ticks,labels and decor. Finally, it arranges these components into a guide.

This method should only be overridden if the extension has non standardcomponents that do not fit into 'decor' or when this method can be greatlysimplified for humble guides. All subsidiaries are fine to override.

Usage

Geom$setup_params(theme, position, direction, params)

Arguments

theme

Acomplete theme object.

position

A scalar string indicating the position wherethe guide should be drawn. Typically"top","right","bottom"or"left", unless it is a position guide for an exotic coord. Can beNULL, in which caseparams$position should be used.

direction

A scalar string indicating the legend direction.Can beNULL, in which caseparams$direction should be used.

params

A list of parameters initiated by theparams field.

Value

A grob with the guide.

draw_early_exit

Description

A function method that determines what should be drawn when the guide 'key'is empty. The default method returnszeroGrob(). You can overridethis method if an empty key should draw anything. Used inguide_axis()to render theaxis.line part even if no ticks or labels should be drawn.

Usage

Guide$draw_early_exit(params, elements)

Arguments

params

A list of parameters initiated by theparams field.

elements

A list of elements or resolved theme settings fromtheoverride_elements() method.

Value

A grob.

setup_params

Description

A function method for finalising parameters. Typically used to make checkson theparams object or to make any position or direction basedadjustments.

Usage

Guide$setup_params(params)

Arguments

params

A list of parameters initiated by theparams field.

Value

A list of parameters

setup_elements,override_elements

Description

A function method for resolving required theme elements. Thesetup_elements() method joins local guide theme with global theme andcalculates the necessary theme elements. Theoverride_elements() methodis a hook to edit elements after they've been calculated.

You can override thesetup_elements() method if you need more complicatedtheme handling before calculating elements or want to intervene in inheritance.For example,guide_legend() has special handling of text margins andguide_axis() suffixes⁠{aes}.{position}⁠ to get the theme elements forthe correct position.

For other purposes, you can override theoverride_elements() method.

Usage

Guide$setup_elements(params, elements, theme)Guide$override_elements(params, elements, theme)

Arguments

params

A list of parameters initiated by theparams field.

elements

A named list of strings initiated by theelements field.

theme

Acomplete theme

Value

A list of elements or resolved theme settings.

build_title

Description

A function method for rendering the title. Note that titles for positionguides are rendered by the Facet class and not this method.

You can override this method if you need to render more than one title(or none) or adjust margin settings.

Usage

Guide$build_title(label, elements, params)

Arguments

label

A single string or expression with the title text.

elements

A list of elements or resolved theme settings fromtheoverride_elements() method. The default method expectselements$title to inherit from the⁠<element_text>⁠ class.

params

A list of parameters initiated by theparams field.

Value

A grob representing the title.

build_ticks

Description

A function method for rendering tick marks.

You can override this function if you don't need ticks or have completelydifferent logic on how these should be drawn.

Usage

Guide$build_ticks(key, elements, params, position, length)

Arguments

key

A data frame with the key information derived from theextract_key() method.

elements

A list of elements or resolved theme settings fromtheoverride_elements() method. The default method expectselements$ticks to inherit from the⁠<element_line>⁠ class andelements$ticks_length to be a scalar⁠<unit>⁠ object.

params

A list of parameters initiated by theparams field.

position

A scalar string indicating the position. Due tohistoric error this works in the opposite way to intuition: if you wantticks for an axis at the bottom of a plot, you should use"top" here.

length

A scalar⁠<unit>⁠ object giving the tick length.

Value

A grob representing tick marks.

build_labels

Description

A function method for rendering labels. The default method returns anempty grob. It is recommended to override this method when your extensiondirectly descends from Guide.

Usage

Guide$build_labels(key, elements, params)

Arguments

key

A data frame with the key information derived from theextract_key() method.

elements

A list of elements or resolved theme settings fromtheoverride_elements() method. Most non-default methods expectselements$text to inherit from the⁠<element_text>⁠.

params

A list of parameters initiated by theparams field.

Value

A grob representing labels.

build_decor

Description

A function method for rendering decor. As the 'wildcard' component, thiscan draw whatever component the guide needs that isn't already captured bythe key. The default method returns an empty grob. It is recommended tooverride this method.

For some examples:guide_legend() renders the keys with the glyphs,guide_colourbar() renders the colour gradient rectangle andguide_axis() renders the axis line.

Usage

Guide$build_decor(decor, grobs, elements, params)

Arguments

decor

A data frame (or other structure) with information derivedfrom theextract_decor() method.

grobs

A list with grobs generated by the other⁠build_*⁠methods.

elements

A list of elements or resolved theme settings fromtheoverride_elements() method. Most non-default methods expectselements$text to inherit from the⁠<element_text>⁠.

params

A list of parameters initiated by theparams field.

Value

A grob.

measure_grobs

Description

A function method for measuring grobs. In preparation for arranging grobs,they often need to be measured to determine their widths and heights.It is convention that every measurement is converted to centimetres.You can override this method if your extension directly descends fromGuide, or the parent class measurement is defective.

Usage

Guide$measure_grobs(grobs, params, elements)

Arguments

grobs

A list with grobs generated by the⁠build_*⁠ methods.

params

A list of parameters initiated by theparams field.

elements

A list of elements or resolved theme settings fromtheoverride_elements() method.

Value

A named list or⁠<unit>⁠ vector giving sizes of components, coordinatedwitharrange_layout() andassemble_drawing() methods. The defaultmethod returnsNULL.

arrange_layout

Description

A function method for determining the location or order of grobs in agtable. Typically determines rows and columns where decor and labels areplaced. Titles are added seperately.You can override this method if yourextension directly descends from Guide.

Usage

Guide$arrange_layout(key, sizes, params, elements)

Arguments

key

A data frame with the key information derived from theextract_key() method.

sizes

A list of⁠<unit>⁠ vector from themeasure_grobs() method.

params

A list of parameters initiated by theparams field.

elements

A list of elements or resolved theme settings fromtheoverride_elements() method.

Value

Any structure holding placement information coordinated with theassemble_drawing() method.

assemble_drawing

Description

A function method that takes measurements, placement information and grobsand assembles these together in a gtable structure. You can override thismethod if your extension directly descends from Guide, or the parent classassembly does not work for your guide.

Usage

Guide$assemble_drawing(grobs, layout, sizes, params, elements)

Arguments

grobs

A list with grobs generated by the⁠build_*⁠ methods.

layout

A data structure from thearrange_layout() method.

sizes

A list of⁠<unit>⁠ vector from themeasure_grobs() method.

params

A list of parameters initiated by theparams field.

elements

A list of elements or resolved theme settings fromtheoverride_elements() method.

Value

A finished gtable containing the guide.

arrange_layout

Description

A function method for placing the title. It is a subsidiary method usedin theassemble_drawing() method for non-position guides. Titles aretypically added beforelegend.margin is applied. It is notrecommended to override this method.

Usage

Guide$add_title(gtable, title, position, just)

Arguments

gtable

An unfinished gtable under construction in theassemble_drawing() method.

title

The grob resulting from thebuild_title() method.

position

A scaler string, either"top","right","bottom"or"left" corresponding to thelegend.title.position.

just

A named list havinghjust andvjust components withscalar numeric values between 0 and 1.

Value

Thegtable argument with added title.

Conventions

The object name that a new class is assigned to is typically the same as theclass name. Guide class names are in UpperCamelCase and start with the⁠Guide*⁠ prefix, likeGuideNew.

A constructor function is usually paired with a Guide class. The constructorwraps a call tonew_guide(), where e.g.new_guide(super = GuideNew). Theconstructor name is formatted by taking the Guide class name and formattingit with snake_case, so thatGuideNew becomesguide_new().

See Also

Runvignette("extending-ggplot2"), in particular the "Creatingnew guides" section.

Examples

# Extending the classGuideDescribe <- ggproto(  "GuideDescribe", Guide,  # Fields  elements  = list(text = "legend.text", margin = "legend.margin"),  hashables = rlang::exprs(key$.label),  # Methods  build_title = function(...) zeroGrob(), # Turn off title  build_labels = function(key, elements, params) {    labels <- key$.label    n <- length(labels)    labels <- paste0(paste0(labels[-n], collapse = ", "), ", and ", labels[n])    labels <- paste0("A guide showing ", labels, " categories")    element_grob(elements$text, label = labels, margin_x = TRUE, margin_y = TRUE)  },  measure_grobs = function(grobs, params, elements) {    # Measuring in centimetres is the convention    width  <- grid::convertWidth(grid::grobWidth(grobs$labels), "cm", valueOnly = TRUE)    height <- grid::convertHeight(grid::grobHeight(grobs$labels), "cm", valueOnly = TRUE)    list(width = unit(width, "cm"), height = unit(height, "cm"))  },  assemble_drawing = function(self, grobs, layout, sizes, params, elements) {    gt <- gtable::as.gtable(grobs$labels, width = sizes$width, height = sizes$height)    gt <- gtable::gtable_add_padding(gt, elements$margin)    gt  })# Building a constructorguide_describe <- function(position = NULL) {  new_guide(position = position, super = GuideDescribe)}# Use new guide plotggplot(mpg, aes(displ, hwy, colour = class)) +  geom_point() +  guides(colour = guide_describe("bottom"))

Layers

Description

The Layer class is a chaperone class not available for extension. The classfulfils the following tasks. The class houses the Geom, Stat and Positiontrinity and tracks their stateful parameters. Furthermore, its methods areresponsible for managing the layer data and exposing it to other componentsof the plot at the right time.

Details

The Layer class is an internal class that is not exported because the classis not intended for extension. Thelayer() function instantiates theLayerInstance class, which inherits from Layer, but has relevant fieldspopulated.

The class is mostly used inggplot_build(), with the notable exceptionof thedraw_geom() method, which is used inggplot_gtable() instead.

Fields

constructor

Acall object with the user-facingconstructor function, for use in error messaging. This field is populatedbylayer().

geom,stat,position

These fields house the Geom, Stat and Positiontrifecta in ggproto form and is populated bylayer().

stat_params,computed_stat_params

These fields hold parametersassigned to the Stat. Thestat_params field is directly derived fromuser input and is populated bylayer(). Thecomputed_stat_paramscarries state and is constructed by theStat$setup_params() method.

geom_params,computed_geom_params

These fields hold parametersassigned to the Geom. Thegeom_params field is directly derived fromuser input and is populated bylayer(). Thecomputed_geom_paramscarries state and is constructed by theGeom$setup_params() method.

mapping,computed_mapping

These fields holdmappings.Themapping field holds thelayer(mapping) argument. Thecomputed_mapping field carries state and is constructed in thesetup_layer() method.

data

The fortifiedlayer(data) argument.

aes_params

Holds the fixed, unmapped aesthetics passed tolayer(params) as determined byGeom$aesthetics().

inherit.aes

A scalar boolean used in thesetup_layer() method toindicate whether thecomputed_mapping should include the global mapping(TRUE) or only the layer mapping (FALSE). This is populated by thelayer(inherit.aes) parameter.

layer_data

Description

A function method for initially resolving layer data. If layer data ismissing or is a function, it will derive layer data from the global plotdata.

Usage

Layer$layer_data(plot_data)

Arguments

plot_data

Thedata field of the ggplot object.

Value

A data frame with layer data orNULL

setup_layer

Description

A function method is a hook to allow a final access to layer data ininput form. In addition, it allows a layer access to global plotinformation. The latter is used to enforce theinherit.aes parameter bysupplementing the layer mapping with the global mapping when requested.

Usage

Layer$setup_data(data, plot)

Arguments

data

A data frame with the layer's data.

plot

A ggplot object

Value

A data frame with layer data. As a side effect, thecomputed_mappingfield is populated.

compute_aesthetics

Description

A function method that evaluates aesthetics and warns about any problems.It also infers agroup aesthetic if not provided. This method is alsothe step where layer data becomes standardised to base data frames withoutrow names or additional attributes.

Usage

Layer$compute_aesthetics(data, plot)

Arguments

data

A data frame with the layer's data.

plot

A ggplot object

Value

A data frame with layer data

compute_aesthetics

Description

A function method that orchestrates computing statistics. It executesmethods from the Stat class to form new computed variables.

Usage

Layer$compute_statistic(data, layout)

Arguments

data

A data frame with the layer's data.

layout

A⁠<Layout>⁠ ggproto object.

Value

A data frame with layer data. As a side effect thecomputed_stat_paramsfield is populated.

map_statistic

Description

A function method that finishes the result of computed statistics. It hasseveral tasks:

  • It evaluates theafter_stat() stage of the mapping from both thecomputed_mapping but also theStat$default_aes fields.

  • It ensures relevant scales are instantiated for computed aesthetics.

  • It takes care that scale transformation is applied to computed aesthetics.

Usage

Layer$map_statistic(data, plot)

Arguments

data

A data frame with the layer's data.

plot

A ggplot object.

Value

A data frame with layer data

compute_geom_1

Description

A function method that prepares data for drawing. It checks that allrequired aesthetics are present and sets up parameters and data using theGeom class.

Usage

Layer$compute_geom_1(data)

Arguments

data

A data frame with the layer's data.

Value

A data frame with layer data. As a side effect thecomputed_geom_paramsfield is populated.

compute_position

Description

A function method that orchestrates the position adjustment. It executesmethods from the Position class.

Usage

Layer$compute_position(data, layout)

Arguments

data

A data frame with the layer's data.

layout

A⁠<Layout>⁠ ggproto object.

Value

A data frame with layer data.

compute_geom_2

Description

A function method that add defaults and fixed parameters. It wraps theGeom$use_defaults() method.

Usage

Layer$compute_geom_2(data, params, theme, ...)

Arguments

data

A data frame with the layer's data.

params

A list with fixed aesthetic parameters, typically theaes_params field.

theme

Atheme object

...

Passed on toGeom$use_defaults(), not in use.

Value

A data frame with layer data.

finish_statistics

Description

A function method that wrapsStat$finish_layer().

Usage

Layer$finish_statistics(data)

Arguments

data

A data frame with the layer's data.

Value

A data frame with layer data.

draw_geom

Description

A function method that produces graphics for every panel. It uses Geomclass methods to handle missing data and produce grobs. In contrast toother methods, this is called during theggplot_gtable() stage, not theggplot_build() stage.

Usage

Layer$draw_geom(data, layout)

Arguments

data

A data frame with the layer's data.

layout

A⁠<Layout>⁠ ggproto object.

Value

A list of grobs, one per panel.

print

Description

A function method that prints information about the layer.

Usage

Layer$print()

Value

Nothing (NULL), invisibly

Layer data diagram

As the Layer class is a chaparone for the data, it makes sense to give asmall overview of how layer data flows through a plot. In the diagram belowwe following thelayer(data) argument over the course of plot buildingthrough Layer class methods. When an outside class acts on the data withoutthe Layer class, this is indicated with the left arrow⁠<-⁠. Subcomponentsof a method that touch data are indicated with the right arrow⁠->⁠.

# Inside `ggplot_build()` |layer(data) | | | # Inherit plot data |Layer$layer_data() | | | # Finalise mapping |Layer$setup_layer() | | | # Append PANEL variable for facets | |<- Layout$setup() |    | |    +-> Facet$setup_data() |    | |    +-> Coord$setup_data() | | | # Evaluate mappings to new data and infer group |Layer$compute_aesthetics() | | | # Scale-transform all aesthetics | |<- ScalesList$transform_df() |    | |    +-> Scale$transform_df() | | | # Map x/y aesthetics with initial scale | |<- Layout$map_position() |    | |    +-> Scale$map() | | | # Compute stat part of layer |Layer$compute_statistic() | | | +-> Stat$setup_data() | | | +-> Stat$compute_layer() | | | # Add `after_stat()` stage | # Scale transform computed variables |Layer$map_statistic() | | | # Setup geom part of layer |Layer$compute_geom_1() | | | +-> Geom$setup_data() | | | # Apply position adjustments |Layer$compute_position() | | | +-> Position$use_defaults() | | | +-> Position$setup_data() | | | +-> Position$compute_layer() | | | # Map x/y aesthetics with final scales | |<- Layout$map_position() |    | |    +-> Scale$map() | | # Map non-position aesthetics | |<- ScalesList$map_df() |    | |    +-> Scale$map() | | | # Fill in defaults and fixed aesthetics |Layer$compute_geom_2() | | | +-> Geom$use_defaults() | | | # Apply final Stat hook |Layer$finish_statistics() | | | +-> Stat$finish_layer() | | | # Apply final Facet hook | |<- Layout$finish_data() |    | |    +-> Facet$finish_data() | V# `ggplot_build()` is finished# Hand off to `ggplot_gtable()` | | | # Draw the geom part |Layer$draw_geom() | +-> Geom$handle_na() | +-> Geom$draw_layer()

See Also

Other Layer components:Geom,Position,Stat

Other chaperone classes:Layout

Examples

# None: Layer is not intended to be extended

Layout

Description

The Layout class is a chaperone class discouraged for extension. The classfulfils the following tasks. The class houses the Coord and Facet classesand tracks their stateful parameters. In addition, it manages the positionscales for each panel. It is responsible for keeping track of panelspecifications and matching pieces of the data to scales and parameters inpanel-wise manners.

Details

The Layout class is only exported for extensions that re-implement aggplot_build() method for their specific class of plots. It is discouragedto subclass the Layout class and for all purposes be considered an internalstructure. It has no user-facing constructor to put an small barrier in theway.

The class is used throughoutggplot_build(), with the notable exception oftherender() method, which is used inggplot_gtable() instead.

Fields

coord,coord_params

A<Coord> ggproto object and a listof the coordinate system's parameters. Parameters get populated by theCoord$setup_params() method.

facet,facet_params

A<Facet> ggproto object and a listof the faceting specification's parameters. Parameters get populated bytheFacet$setup_params() method.

layout

A data frame with a row for each panel. The data framecontains integer columnsPANEL,SCALE_X,SCALE_Y,ROW andCOLrepresenting a panel ID, scale indices and placement locations. In addition,the layout may contain faceting variables or other additional information.This field gets populated by theFacet$compute_layout() method.

panel_scales_x,panel_scales_y

A list ofx andy position scalesparallel to the layout field'sSCALE_X andSCALE_Y levels respectively.This fields gets populated by theFacet$init_scales() method.

panel_params

A named list of parameters per panel populated by theCoord$setup_panel_params() method. Contains⁠<ViewScale>⁠ entries forthex andy variables in addition to ranges and other information thecoordinate system might need to transform or render guides and grids.

setup

Description

A function method for setting up the relevant information for the layoutof the plot. It populates thefacet_params,coord_params andlayoutfields and appends aPANEL variable to the layer data.

Usage

Layout$setup(data, plot_data, plot_env)

Arguments

data

A list of data frames with layer data.

plot_data

The data frame in thedata field of the ggplotobject.

plot_env

The environment in theplot_env field of theggplot object.

Value

A list of data frames from thedata argument with aPANEL variablecorresponding to rows in thelayout field.Also called for the side effects of populating fields.

train_position

Description

A function method for training position scales and optionally initiatingthem. Implementation is via theFacet$train_scales() andFacet$init_scales() methods.

Usage

Layout$train_position(data, x_scale, y_scale)

Arguments

data

A list of data frames with layer data.

x_scale,y_scale

A single prototype position scale for thexandy aesthetics respectively.

Value

Nothing, this method is called for the side effect of training scales andoptionally populating thepanel_scales_x andpanel_scales_y fields.

map_position

Description

A function method for mapping position aesthetics. For discrete scales thisconverts discrete levels to a numeric representation, usually integers. Forcontinuous scales, this applies out-of-bounds handling.

Usage

Layout$map_position(data)

Arguments

data

A list of data frames with layer data.

Value

A list of data frames per thedata argument with mapped positionaesthetics.

reset_scales

Description

A function method for resetting scale ranges. After computing stats andposition adjustments, scales need to be reset and re-trained to have anaccurate measure of the data limits. This goes through thepanel_scales_x andpanel_scales_y fields and invokes theScale$reset() method.

Usage

Layout$reset_scales()

Value

Nothing, it is called for the side-effect of resetting scale ranges.

setup_panel_params

Description

A function method for executingCoord$setup_panel_params() once per panelwith the appropriate scales. For efficiency reasons, the setup is invokedonce per unique combination ofx andy scale.

Usage

Layout$setup_panel_params()

Value

Nothing, it is called for the side effect of populating thepanel_paramsfield.

setup_panel_guides

Description

A function method for setting up and training the position guides (axes)once per panel with the appropriate scales. For efficiency reasons,the guides are setup once per unique combination ofx andy scale.It calls theCoord$setup_panel_guides() andCoord$train_panel_guides()methods.

Usage

Layout$setup_panel_guides(guides, layers)

Arguments

guides

A⁠<Guides>⁠ ggproto object from theguides field ofthe ggplot object.

layers

A list of layers from thelayers field of the ggplotobject.

Value

Nothing, it is called for the side effect of augmenting each entry of thepanel_params field with position guides.

setup_panel_guides

Description

A function method for setting up theFacet$finish_data() hook.

Usage

Layout$finish_data(data)

Arguments

data

A list of data frames with layer data.

Value

A list of data frames with layer data.

render

Description

A function method for drawing and assembling the core plot. Mostly itdelegates tasks to the specific Facet methods for drawing components.

Usage

Layout$render(panels, data, theme, labels)

Arguments

panels

A list parallel to layers. Each element is another listwith grobs for each panel, generated byLayer$draw_geom().

data

A list of data frames with layer data.

theme

Acomplete theme.

labels

A list of labels from thelabels field of the ggplotobject.

Value

A gtable containing a plot with panels, axes, axis titles and strips.

resolve_label

Description

A function method for prying the axis titles from guides, scales or plotlabels.

Usage

Layout$resolve_label(scale, labels)

Arguments

scale

A single scale from thepanel_scales_x orpanel_scales_y fields.

labels

A list of labels from thelabels field of the ggplotobject.

Value

A named list containing a two titles named"primary" and"secondary".

render_labels

Description

A function method for drawing axis title grobs. The position guidesthemselves do not typically render the axis title grobs as they areorchestrated by the layout to draw one title even for multiple axes.

Usage

Layout$render_labels(labels, theme)

Arguments

labels

A named list containing anx list and ay list. Thex andy lists haveprimary andsecondary labels. It originatesfrom theCoord$labels() method.

theme

Acomplete theme.

Value

A list with the same structure and names as thelabels argument, but withgrobs instead of text.

get_scales

Description

A function method for retrieving panel specific scales. It is called intheStat$compute_layer() andPosition$compute_layer() methods. TheGeom uses thepanel_params field instead of the raw scales.

Usage

Layout$get_scales(i)

Arguments

i

A scalar integer panel index giving the panel for which toretrieve scales

Value

A named list of scales giving thex andy scale for the panel.

See Also

Other Layout components:Coord,Facet

Other chaperone classes:Layer-class

Examples

# Some dummy layout componentsfacet <- facet_null()coord <- coord_cartesian()# Use in custom `ggplot_build()` methodslayout <- ggproto(NULL, Layout, facet = facet, coord = coord)

Positions

Description

All⁠position_*()⁠ functions (likeposition_dodge()) return a⁠Position*⁠ object (likePositionDodge). The⁠Position*⁠object is responsible for adjusting the position of overlapping geoms.

Details

The way that the⁠position_*⁠ functions work is slightly different fromthe⁠geom_*⁠ and⁠stat_*⁠ functions, because a⁠position_*⁠function actually "instantiates" the⁠Position*⁠ object by creating adescendant, and returns that. The object is chaperoned by theLayer class.

To create a new type of Position object, you typically will want to overrideone or more of the following:

Fields

required_aes

A character vector naming aesthetics that are necessaryto compute the position adjustment.

default_aes

Amapping of default values for aesthetics.

use_defaults

Description

A function method for completing the layer data by filling in defaultposition aesthetics that are not present. These can come from two sources:either from the layer parameters as static, unmapped aesthetics or fromthedefault_aes field.

Usage

Position$use_defaults(data, params)

Arguments

data

A data frame of the layer's data

params

A list of fixed aesthetic parameters

Value

A data frame with completed layer data

setup_params

Description

A function method for modifying or checking the parameters based on thedata. The default method returns an empty list.

Usage

Position$setup_params(data)

Arguments

data

A data frame with the layer's data.

Value

A list of parameters

setup_data

Description

A function method for modifying or checking the data. The default methodchecks for the presence of required aesthetics.

Usage

Position$setup_data(data, params)

Arguments

data

A data frame with the layer's data.

params

A list of parameters coming from thesetup_params()method

Value

A data frame with layer data

compute_layer

Description

A function method orchestrating the position adjust of the entire layer.The default method splits the data and passes on adjustment tasks to thepanel-levelcompute_panel(). In addition, it finds the correct scalesin the layout object to pass to the panel computation.

Usage

Position$compute_layer(data, params, layout)

Arguments

data

A data frame with the layer's data.

params

A list of parameters coming from thesetup_params()method

layout

A⁠<Layout>⁠ ggproto object.

Value

A data frame with layer data

compute_panel

Description

A function method executing the position adjustment at the panel level.The default method is not implemented.

Usage

Position$compute_panel(data, params, scales)

Arguments

data

A data frame with the layer's data.

params

A list of parameters coming from thesetup_params()method

scales

A list of pre-trainedx andy scales. Note that theposition scales are not finalised at this point and reflect the initialdata range before computing stats.

Value

A data frame with layer data

aesthetics

Description

A function method for listing out custom position aesthetics for thisposition adjustment.

Usage

Position$aesthetics()

Value

A character vector of aesthetic names.

Convention

The object name that a new class is assigned to is typically the same as theclass name. Position class name are in UpperCamelCase and start with the⁠Position*⁠ prefix, likePositionNew.

A constructor functions is usually paired with a Position class. Theconstructor copies the position class and populates parameters. Theconstructor function name is formatted by taking the Position class name andformatting it with snake_case, so thatPositionNew becomesposition_new().

See Also

Thenew positions section of the online ggplot2 book.

Other Layer components:Geom,Layer-class,Stat

Examples

# Extending the classPositionRank <- ggproto(  "PositionRank", Position,  # Fields  required_aes = c("x", "y"),  # Methods  setup_params = function(self, data) list(width = self$width),  compute_panel = function(data, params, scales) {    width <- params$width    if (is.null(width)) {      width <- resolution(data$x, zero = FALSE, TRUE) * 0.4    }    rank   <- stats::ave(data$y, data$group, FUN = rank)    rank   <- scales::rescale(rank, to = c(-width, width) / 2)    data$x <- data$x + rank    data  })# Building a constructorposition_rank <- function(width = NULL) {  ggproto(NULL, PositionRank, width = width)}# Use new position in plotggplot(mpg, aes(drv, displ)) +  geom_point(position = position_rank(width = 0.5))

Scales

Description

All⁠scale_*()⁠ functions (likescale_fill_continuous()) return a⁠Scale*⁠object. The main purpose of these objects is to translate data values toaesthetic values and populating breaks and labels.

Details

All⁠scale_*⁠ functions likescale_x_continuous() return a⁠Scale*⁠ objectlikeScaleContinuous. Each of the⁠Scale*⁠ objects is aggproto() objectdescended from the top-levelScale.

Scales generally need to track three types of spaces:

  1. Data space. These are values as they are evaluated from the plotor layer mapping, prior to any transformation.

  2. Transformed space. This is the space after original data has beentransformed. Effectively, scales internally operate in transformed spacein that ranges and breaks get passed around in this space. Discrete scalesdon't do transformations, so for these scales, transformed space is thesame as untransformed space.

  3. Aesthetic space. Graphic values that are mapped from the transformedspace. This is dependent on thepalette field for most scales and on therescaler field for continuous position scales.

The user is expected to give any vector-basedminor_breaks,breaks orlimits in data space. Whenbreaks,limits orlabels is a function,its input is expected to be in data space.

Before you attempt to create a new⁠Scale*⁠ class of your own, it isrecommended to think through whether your aims cannot be implemented withone of the existing classes. Making a wrapper for thecontinuous_scale(),discrete_scale() andbinned_scale() should cover many cases, and shouldbe considered prior to commiting to build a⁠Scale*⁠ extension.

For example, if you aim to develop a scale for a new data type, it shouldgenerally be possible to create a newtransformationinstead. One reason to implement your own⁠Scale*⁠ class is to accommodatea data type does not lend itself for continuous or discrete range training.

In such case, you can override the following:

Fields

call

Acall object with the user-facing constructorfunction, for use in error messaging. This field is populated by scaleconstructors.

range

ARange class object, likescales::ContinuousRange orscales::DiscreteRange. These are 'trained'to keep track of the data range (continuous) or data levels (discrete).Continuous ranges are tracked in transformed space.

aesthetics,palette,name,breaks,labels,limits,name,guide,position,na.value,expand

Fields populated by the scale constructor that can take on the same valuesas described in e.g.?continuous_scale.Note thatlimits is expected in transformed space.

transform_df,transform

Description

A function method for orchestrating the transformation of aesthetics in adata frame. Data transformation occurs before stats are computed.Thetransform_df() method ensures thetransform() method is appliedto the correct columns.

Usage

Scale$transform_df(df)Scale$transform(x)

Arguments

df

A data frame with the layer's data.

x

A vector of the relevant aesthetic.

Value

Fortransform() a vector of transformed values.Fortransform_df(), a named list with transformed values for eachtransformed aesthetic.

train_df,train

Description

A function method for orchestrating scale training for keeping track ofthe data range or levels. Thetrain_df() method ensures thetrain()method is applied to the correct columns.

Usage

Scale$train_df(df)Scale$train(x)

Arguments

df

A data frame with the layer's data.

x

A vector of the relevant aesthetic.

Value

Nothing, these are called for their side effect of updating therangefield.

map_df,map

Description

A function method for orchestrating the mapping of data values toaesthetics. Themap_df() method ensures themap() method is appliedto the correct columns. When the scale uses apalette() function, it isapplied in themap() method.

Usage

Scale$map_df(df, i)Scale$map(x, limits)

Arguments

df

A data frame with the layer's data.

i

An integer vector giving an index to map a subset of data.The default,NULL, will map all rows.

x

A vector of the relevant aesthetic.

limits

A vector of the relevant aesthetic, usually viatheget_limits() method.

Value

Formap() a vector of mapped values in aesthetics space.Formap_df(), a named list with mapped values for eachaesthetic.

recale

Description

A function method for applying the recale function in therescaler field.It is used during the continuousmap() andCoord$transform() methodsto ensure values are in the 0-1 range.

Usage

Scale$rescale(x, limits, range)

Arguments

x

A vector of values to rescale. Can contain out-of-boundsor missing values depending on themap() method.

limits

A length two vector giving the limits of the relevantaesthetic, usually via theget_limits() method.

range

A length two vector giving the range that should coincidewith the 0-1 points. For most purpuses, this should be the same as thelimits argument.

Value

A vector of values between 0 and 1 for in-bounds values ofx.

get_limits

Description

A function method for resolving user input and getting the scale limits.

Usage

Scale$get_limits()

Value

The scale limits, without any expansion applied, in transformed space.

dimension

Description

A function method for getting a continuous representation of the limits ofposition scales. For continuous scales, the dimension is the same conceptas the limits. For discrete scales the dimension is the continuous rangeoccupied by the mapped breaks, which by default take integer positions.

Usage

Scale$dimension(expand, limits)

Arguments

expand

A length 4 vector giving scaleexpansion.This is optional and defaults to no expansion.

limits

A vector of the relevant aesthetic, usually viatheget_limits() method.

Value

A numeric vector of length 2

get_breaks,get_breaks_minor

Description

A function method for resolving user input and getting the scale breaksor minor breaks. Note that these may return out-of-bounds values for thepurpose of coordinating with theget_labels() method.

Usage

Scale$get_breaks(limits)Scale$get_breaks_minor(n, b, limits)

Arguments

limits

A vector of the relevant aesthetic, usually viatheget_limits() method.

n

An integer setting the desired number of minor breaks permajor break. Note that the resulting minor breaks may coincide withmajor breaks.

b

A vector of mapped major breaks from theget_breaks()method.

Value

A vector of breaks in transformed space.

get_labels

Description

A function method for resolving user input and getting the scale labels fora set of breaks.

Usage

Scale$get_labels(breaks)

Arguments

breaks

A vector of unmapped major breaks from theget_breaks()method, in transformed space.

Value

A vector of labels of the same length asbreaks.

get_transformation

Description

A helper method to access the scale's transformation object.

Usage

Scale$get_transformation()

Value

Atransform object.

break_info

Description

A function method for getting all break related information for positionscales. It is in use by coords that do not use the modern Guide systemand secondary axes.

Usage

Scale$break_info(range)

Arguments

range

A vector of the relevant aesthetic.

Value

A named list with the following structure:

  • range a length 2 vector giving continuous range

  • labels a character or expression vector of the same length as major breaks.

  • major a numeric vector with mapped numeric values for major breaks.

  • major_source a numeric vector with (transformed) data values for major breaks.

  • minor a numeric vector with mapped numeric values for minor breaks.

  • minor_source a numeric vector with (transformed) data values for minor breaks.

break_position

Description

A function method for getting mapped break positions. It is in use as adefault value inget_breaks_minor(), but is otherwise vestigial.

Usage

Scale$break_info(range)

Arguments

range

A vector of the relevant aesthetic.

Value

A vector with mapped break positions

make_title,make_sec_title

Description

A function method for picking the title to use. This is usually called intheGuide$extract_params() orLayout$resolve_label() methods.The hierarchy of titles goes from guide (highest priority), to scale, tolabs (lowest priority).When the guide or scale title are functions, they're applied to the nextin line. Themake_sec_title() method by default re-uses the primarymake_title() method and only applies to position aesthetics.

Usage

Scale$make_title(guide_title, scale_title, label_title)Scale$make_sec_title(...)

Arguments

guide_title

Thetitle parameter coming from a guide.

scale_title

Thename field of the Scale.

label_title

The relevant entry in theplot$labels field.

...

By default, arguments forwarded to themake_title()method

Value

A scalar character or expression title

axis_order

Description

A function method for setting the order of axes titles used to coordinatewithFacet$draw_labels().

Usage

Scale$axis_order()

Value

Eitherc("primary", "secondary") orc("secondary", "primary").

clone

Description

A function method for making an untrained copy of the scale. Due toreference semantics of ggproto objects, in contrast to copy-on-modifysemantics, scales need to be cloned at the start of plot building.The cloned scale can be trained independently of the original.

Usage

Scale$clone()

Value

A Scale object.

reset

Description

A function method for to reset therange field, effectively 'untraining'the scale. This is used in theLayout$reset_scales() method, so thatscales can be re-trained on data with final position aesthetics.For discrete scales, only the continuous range (range_c) is reset.

Usage

Scale$clone()

Value

None, called for the side-effect of resetting the range.

is_empty

Description

A function method for determining whether a scale is empty, i.e. when noinformation with which to calculate limits.

Usage

Scale$is_empty()

Value

A scalar boolean value.

is_empty

Description

A function method for determining whether a scale is discrete.

Usage

Scale$is_discrete()

Value

A scalar boolean value.

Conventions

The object name that a new class is assigned to is typically the same as theclass name. Scale class names are in UpperCamelCase and start with the⁠Scale*⁠ prefix, likeScaleNew.

In scales, there is a difference between user-facing and developer-facingconstructors. Developer facing constructors have the shape⁠{foundation}_scale()⁠, likediscrete_scale() corresponding toScaleDiscrete. User-facing constructors have the⁠scale_{aesthetic}_{type}⁠as name. If you implement a new⁠Scale*⁠ class, you like want both thesetypes of constructor.

Examples

# TODO: find easy to digest exampleNULL

Stats

Description

All⁠stat_*()⁠ functions (likestat_bin()) return a layer thatcontains a⁠Stat*⁠ object (likeStatBin). The⁠Stat*⁠object is responsible for rendering the data in the plot.

Details

Each of the⁠Stat*⁠ objects is aggproto() object, descendedfrom the top-levelStat, and each implements various methods andfields. The object and its parameters are chaperoned by theLayer class.

To create a new type of Stat object, you typically will want tooverride one or more of the following:

Fields

required_aes

A character vector naming aesthetics that are necessaryto compute the stat.

non_missing_aes

A character vector naming aesthetics that will causeremoval if they have missing values.

optional_aes

A character vector naming aesthetics that will beaccepted bylayer(), but are not required or dscribed in thedefault_aesfield.

default_aes

Amapping of default values for aesthetics.Aesthetics can be set toNULL to be included as optional aesthetic.

dropped_aes

A character vector naming aesthetics that can be droppedfrom the data without warning. Typically used for aesthetics that are'consumed' during computation like"weight".

extra_params

A character vector of parameter names in addition tothose imputed from thecompute_panel() orcompute_groups() methods.This field can be set to include parameters forsetup_data() methods.By default, this only contains"na.rm".

retransform

A scalar boolean: should the values produced by thestatistic also be transformed in the second pass when recently addedstatistics are trained to the scales

setup_params

Description

A function method for modifying or checking the parameters based on thedata. The default method returns the parameters unaltered.

Usage

Stat$setup_params(data, params)

Arguments

data

A data frame with the layer's data.

params

A list of current parameters

Value

A list of parameters

setup_data

Description

A function method for modifying or checking the data. The default methodreturns data unaltered.

Usage

Stat$setup_data(data, params)

Arguments

data

A data frame with the layer's data.

params

A list of parameters coming from thesetup_params()method

Value

A data frame with layer data

compute_layer

Description

A function method for orchestrating the computation of the statistic. Thedefault method splits the data and passes on computation tasks to thepanel-levelcompute_panel() method. In addition, the default methodhandles missing values by removing rows that have missing values for theaesthetics listed in therequired_aes andnon_missing_aes fields. It isnot recommended to use this method as an extension point.

Usage

Stat$compute_layer(data, params, layout)

Arguments

data

A data frame with the layer's data.

params

A list of parameters

layout

A pre-trained⁠<Layout>⁠ ggproto object.

Value

A data frame with computed data

compute_panel,compute_group

Description

A function method orchestrating the computation of statistics for a singlepanel or group. The defaultcompute_panel() method splits the data intogroups, and passes on computation tasks to thecompute_group() method.In addition,compute_panel() is tasked with preserving aesthetics thatare constant within a group and preserving these if the computation losesthem. The defaultcompute_group() is not implemented.

Usage

Stat$compute_panel(data, scales, ...)Stat$compute_group(data, scales, ...)

Arguments

data

A data frame with the layer's data.

scales

A list of pre-trainedx andy scales. Note that theposition scales are not finalised at this point and reflect the initialdata range before computing stats.

...

Reserved for extensions. By default, this passes parametersto thecompute_group() method.

Value

A data frame with layer data

finish_layer

Description

A function method acting as a hook to modify data after scales have beenapplied, but before geoms have to render. The default is to pass the dataunaltered. This can be used as an extension point when actual aestheticvalues rather than values mapped to the aesthetic are needed.

Usage

Stat$finish_layer(data, params)

Arguments

data

A data frame with layer data

params

A list of parameters

Value

A data frame with layer data

parameters

Description

A function method for listing out all acceptable parameters for this stat.

Usage

Stat$parameters(extra)

Arguments

extra

A boolean: whether to include theextra_params field.

Value

A character vector of parameter names.

aesthetics

Description

A function method for listing out all acceptable aesthetics for this stat.

Usage

Stat$aesthetics()

Value

A character vector of aesthetic names.

Conventions

The object name that a new class is assigned to is typically the same as theclass name. Stat class names are in UpperCamelCase and start with the⁠Stat*⁠prefix, likeStatNew.

A constructor function is usually paired wih a Stat class. The constructorwraps a call tolayer(), where e.g.layer(stat = StatNew). Theconstructor function name is formatted by taking the Stat class name andformatting it with snake_case, so thatStatNew becomesstat_new().

See Also

Thenew stats section of the online ggplot2 book..

Runvignette("extending-ggplot2"), in particular the "Creating anew stat" section.

Other Layer components:Geom,Layer-class,Position

Examples

# Extending the classStatKmeans <- ggproto(  "StatKmeans", Stat,  # Fields  required_aes = c("x", "y"),  # You can relate computed variables to aesthetics using `after_stat()`  # in defaults  default_aes = aes(colour = after_stat(cluster)),  # Methods  compute_panel = function(data, scales, k = 2L) {    km <- kmeans(cbind(scale(data$x), scale(data$y)), centers = k)    data$cluster <- factor(km$cluster)    data  })# Building a constructorstat_kmeans <- function(mapping = NULL, data = NULL, geom = "point",                        position = "identity", ..., k = 2L, na.rm = FALSE,                        show.legend = NA, inherit.aes = TRUE) {  layer(    mapping = mapping, data = data,    geom = geom, stat = StatKmeans, position = position,    show.legend = show.legend, inherit.aes = inherit.aes,    params = list(na.rm = na.rm, k = k, ...)  )}# Use new stat in plotggplot(mpg, aes(displ, hwy)) +  stat_kmeans(k = 3)

Absolute grob

Description

This grob has fixed dimensions and position.

Usage

absoluteGrob(  grob,  width = NULL,  height = NULL,  xmin = NULL,  ymin = NULL,  vp = NULL)

Details

It's still experimental


Add components to a plot

Description

+ is the key to constructing sophisticated ggplot2 graphics. Itallows you to start simple, then get more and more complex, checking yourwork at each step.

Usage

add_gg(e1, e2)e1 %+% e2

Arguments

e1

An object of classggplot() or atheme().

e2

A plot component, as described below.

What can you add?

You can add any of the following types of objects:

To replace the current default data frame, you must use⁠%+%⁠,due to S3 method precedence issues.

You can also supply a list, in which case each element of the list willbe added in turn.

See Also

theme()

Examples

base <- ggplot(mpg, aes(displ, hwy)) + geom_point()base + geom_smooth()# To override the data, you must use %+%base %+% subset(mpg, fl == "p")# Alternatively, you can add multiple components with a list.# This can be useful to return from a function.base + list(subset(mpg, fl == "p"), geom_smooth())

Modify properties of an element in a theme object

Description

Modify properties of an element in a theme object

Usage

add_theme(t1, t2, t2name, call = caller_env())

Arguments

t1

A theme object

t2

A theme object that is to be added tot1

t2name

A name of the t2 object. This is used for printinginformative error messages.


Construct aesthetic mappings

Description

Aesthetic mappings describe how variables in the data are mapped to visualproperties (aesthetics) of geoms. Aesthetic mappings can be set inggplot() and in individual layers.

Usage

aes(x, y, ...)

Arguments

x,y,...

<data-masking> List of name-valuepairs in the formaesthetic = variable describing which variables in thelayer data should be mapped to which aesthetics used by the pairedgeom/stat. The expressionvariable is evaluated within the layer data, sothere is no need to refer to the original dataset (i.e., useggplot(df, aes(variable)) instead ofggplot(df, aes(df$variable))).The names for x and y aesthetics are typically omitted because they are socommon; all other aesthetics must be named.

Details

This function also standardises aesthetic names by convertingcolor tocolour(also in substrings, e.g.,point_color topoint_colour) and translating old styleR names to ggplot names (e.g.,pch toshape andcex tosize).

Value

An S7 object representing a list with classmapping. Components ofthe list are either quosures or constants.

Quasiquotation

aes() is aquoting function. This means thatits inputs are quoted to be evaluated in the context of thedata. This makes it easy to work with variables from the data framebecause you can name those directly. The flip side is that you haveto usequasiquotation to program withaes(). See a tidy evaluation tutorial such as thedplyr programming vignetteto learn more about these techniques.

Note

UsingI() to create objects of class 'AsIs' causes scales to ignore thevariable and assumes the wrapped variable is direct input for the gridpackage. Please be aware that variables are sometimes combined, like insome stats or position adjustments, that may yield unexpected results with'AsIs' variables.

See Also

vars() for another quoting function designed forfaceting specifications.

Runvignette("ggplot2-specs") to see an overview of other aestheticsthat can be modified.

Delayed evaluation for working with computed variables.

Other aesthetics documentation:aes_colour_fill_alpha,aes_group_order,aes_linetype_size_shape,aes_position

Examples

aes(x = mpg, y = wt)aes(mpg, wt)# You can also map aesthetics to functions of variablesaes(x = mpg ^ 2, y = wt / cyl)# Or to constantsaes(x = 1, colour = "smooth")# Aesthetic names are automatically standardisedaes(col = x)aes(fg = x)aes(color = x)aes(colour = x)# aes() is passed to either ggplot() or specific layer. Aesthetics supplied# to ggplot() are used as defaults for every layer.ggplot(mpg, aes(displ, hwy)) + geom_point()ggplot(mpg) + geom_point(aes(displ, hwy))# Tidy evaluation ----------------------------------------------------# aes() automatically quotes all its arguments, so you need to use tidy# evaluation to create wrappers around ggplot2 pipelines. The# simplest case occurs when your wrapper takes dots:scatter_by <- function(data, ...) {  ggplot(data) + geom_point(aes(...))}scatter_by(mtcars, disp, drat)# If your wrapper has a more specific interface with named arguments,# you need the "embrace operator":scatter_by <- function(data, x, y) {  ggplot(data) + geom_point(aes({{ x }}, {{ y }}))}scatter_by(mtcars, disp, drat)# Note that users of your wrapper can use their own functions in the# quoted expressions and all will resolve as it should!cut3 <- function(x) cut_number(x, 3)scatter_by(mtcars, cut3(disp), drat)

Define aesthetic mappings programmatically

Description

[Deprecated]

Aesthetic mappings describe how variables in the data are mapped to visualproperties (aesthetics) of geoms.aes() uses non-standardevaluation to capture the variable names.aes_() andaes_string()require you to explicitly quote the inputs either with"" foraes_string(), or withquote or~ foraes_().(aes_q() is an alias toaes_()). This makesaes_() andaes_string() easy to program with.

aes_string() andaes_() are particularly useful when writingfunctions that create plots because you can use strings or quotednames/calls to define the aesthetic mappings, rather than having to usesubstitute() to generate a call toaes().

I recommend usingaes_(), because creating the equivalents ofaes(colour = "my colour") oraes(x = `X$1`)withaes_string() is quite clunky.

Usage

aes_(x, y, ...)aes_string(x, y, ...)aes_q(x, y, ...)

Arguments

x,y,...

List of name value pairs. Elements must be eitherquoted calls, strings, one-sided formulas or constants.

Life cycle

All these functions are deprecated. Please use tidy evaluation idiomsinstead. Regardingaes_string(), you can replace it with.data pronoun.For example, the following code can achieve the same mapping asaes_string(x_var, y_var).

x_var <- "foo"y_var <- "bar"aes(.data[[x_var]], .data[[y_var]])

For more details, please seevignette("ggplot2-in-packages").

See Also

aes()


Given a character vector, create a set of identity mappings

Description

Given a character vector, create a set of identity mappings

Usage

aes_all(vars)

Arguments

vars

vector of variable names

Examples

aes_all(names(mtcars))aes_all(c("x", "y", "col", "pch"))

Automatic aesthetic mapping

Description

[Deprecated]

Usage

aes_auto(data = NULL, ...)

Arguments

data

data.frame or names of variables

...

aesthetics that need to be explicitly mapped.


Colour related aesthetics: colour, fill, and alpha

Description

These aesthetics parameters change the colour (colour andfill) and theopacity (alpha) of geom elements on a plot. Almost every geom has eithercolour or fill (or both), as well as can have their alpha modified.Modifying colour on a plot is a useful way to enhance the presentation of data,often especially when a plot graphs more than two variables.

Colour and fill

Thecolour aesthetic is used to draw lines and strokes, such as ingeom_point() andgeom_line(), but also the line contours ofgeom_rect() andgeom_polygon(). Thefill aesthetic is used tocolour the inside areas of geoms, such asgeom_rect() andgeom_polygon(), but also the insides of shapes 21-25 ofgeom_point().

Colours and fills can be specified in the following ways:

Alpha

Alpha refers to the opacity of a geom. Values ofalpha range from 0 to 1,with lower values corresponding to more transparent colors.

Alpha can additionally be modified through thecolour orfill aestheticif either aesthetic provides color values using an rgb specification("#RRGGBBAA"), whereAA refers to transparency values.

See Also

Other aesthetics documentation:aes(),aes_group_order,aes_linetype_size_shape,aes_position

Examples

# Bar chart examplep <- ggplot(mtcars, aes(factor(cyl)))# Default plottingp + geom_bar()# To change the interior colouring use fill aestheticp + geom_bar(fill = "red")# Compare with the colour aesthetic which changes just the bar outlinep + geom_bar(colour = "red")# Combining both, you can see the changes more clearlyp + geom_bar(fill = "white", colour = "red")# Both colour and fill can take an rgb specification.p + geom_bar(fill = "#00abff")# Use NA for a completely transparent colour.p + geom_bar(fill = NA, colour = "#00abff")# Colouring scales differ depending on whether a discrete or# continuous variable is being mapped. For example, when mapping# fill to a factor variable, a discrete colour scale is used.ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar()# When mapping fill to continuous variable a continuous colour# scale is used.ggplot(faithfuld, aes(waiting, eruptions)) +  geom_raster(aes(fill = density))# Some geoms only use the colour aesthetic but not the fill# aesthetic (e.g. geom_point() or geom_line()).p <- ggplot(economics, aes(x = date, y = unemploy))p + geom_line()p + geom_line(colour = "green")p + geom_point()p + geom_point(colour = "red")# For large datasets with overplotting the alpha# aesthetic will make the points more transparent.set.seed(1)df <- data.frame(x = rnorm(5000), y = rnorm(5000))p  <- ggplot(df, aes(x,y))p + geom_point()p + geom_point(alpha = 0.5)p + geom_point(alpha = 1/10)# Alpha can also be used to add shading.p <- ggplot(economics, aes(x = date, y = unemploy)) + geom_line()pyrng <- range(economics$unemploy)p <- p +  geom_rect(    aes(NULL, NULL, xmin = start, xmax = end, fill = party),    ymin = yrng[1], ymax = yrng[2], data = presidential  )pp + scale_fill_manual(values = alpha(c("blue", "red"), .3))

Control aesthetic evaluation

Description

Mostaesthetics are mapped from variables found in the data.Sometimes, however, you want to delay the mapping until later in therendering process. ggplot2 has three stages of the data that you can mapaesthetics from, and three functions to control at which stage aestheticsshould be evaluated.

after_stat() replaces the old approaches of using eitherstat(), e.g.stat(density), or surrounding the variable names with.., e.g...density...

Usage

# These functions can be used inside the `aes()` function# used as the `mapping` argument in layers, for example:# geom_density(mapping = aes(y = after_stat(scaled)))after_stat(x)after_scale(x)from_theme(x)stage(start = NULL, after_stat = NULL, after_scale = NULL)

Arguments

x

<data-masking> An aesthetic expressionusing variables calculated by the stat (after_stat()) or layer aesthetics(after_scale()).

start

<data-masking> An aestheticexpression using variables from the layer data.

after_stat

<data-masking> An aestheticexpression using variables calculated by the stat.

after_scale

<data-masking> An aestheticexpression using layer aesthetics.

Staging

Below follows an overview of the three stages of evaluation and how aestheticevaluation can be controlled.

Stage 1: direct input at the start

The default is to map at the beginning, using the layer data provided bythe user. If you want to map directly from the layer data you should not doanything special. This is the only stage where the original layer data canbe accessed.

# 'x' and 'y' are mapped directlyggplot(mtcars) + geom_point(aes(x = mpg, y = disp))

Stage 2: after stat transformation

The second stage is after the data has been transformed by the layerstat. The most common example of mapping from stat transformed data is theheight of bars ingeom_histogram(): the height does not come from avariable in the underlying data, but is instead mapped to thecountcomputed bystat_bin(). In order to map from stat transformed data youshould use theafter_stat() function to flag that evaluation of theaesthetic mapping should be postponed until after stat transformation.Evaluation after stat transformation will have access to the variablescalculated by the stat, not the original mapped values. The 'computedvariables' section in each stat lists which variables are available toaccess.

# The 'y' values for the histogram are computed by the statggplot(faithful, aes(x = waiting)) +  geom_histogram()# Choosing a different computed variable to display, matching up the# histogram with the density plotggplot(faithful, aes(x = waiting)) +  geom_histogram(aes(y = after_stat(density))) +  geom_density()

Stage 3: after scale transformation

The third and last stage is after the data has been transformed andmapped by the plot scales. An example of mapping from scaled data couldbe to use a desaturated version of the stroke colour for fill. You shoulduseafter_scale() to flag evaluation of mapping for after data has beenscaled. Evaluation after scaling will only have access to the finalaesthetics of the layer (including non-mapped, default aesthetics).

# The exact colour is known after scale transformationggplot(mpg, aes(cty, colour = factor(cyl))) +  geom_density()# We re-use colour properties for the fill without a separate fill scaleggplot(mpg, aes(cty, colour = factor(cyl))) +  geom_density(aes(fill = after_scale(alpha(colour, 0.3))))

Complex staging

Sometimes, you may want to map the same aesthetic multiple times, e.g. mapx to a data column at the start for the layer stat, but remap it later toa variable from the stat transformation for the layer geom. Thestage()function allows you to control multiple mappings for the same aestheticacross all three stages of evaluation.

# Use stage to modify the scaled fillggplot(mpg, aes(class, hwy)) +  geom_boxplot(aes(fill = stage(class, after_scale = alpha(fill, 0.4))))# Using data for computing summary, but placing label elsewhere.# Also, we're making our own computed variables to use for the label.ggplot(mpg, aes(class, displ)) +  geom_violin() +  stat_summary(    aes(      y = stage(displ, after_stat = 8),      label = after_stat(paste(mean, "±", sd))    ),    geom = "text",    fun.data = ~ round(data.frame(mean = mean(.x), sd = sd(.x)), 2)  )

Conceptually,aes(x) is equivalent toaes(stage(start = x)), andaes(after_stat(count)) is equivalent toaes(stage(after_stat = count)),and so on.stage() is most useful when at least two of its arguments arespecified.

Theme access

Thefrom_theme() function can be used to acces theelement_geom()fields of thetheme(geom) argument. Usingaes(colour = from_theme(ink))andaes(colour = from_theme(accent)) allows swapping between foreground andaccent colours.

Examples

# Default histogram displayggplot(mpg, aes(displ)) +  geom_histogram(aes(y = after_stat(count)))# Scale tallest bin to 1ggplot(mpg, aes(displ)) +  geom_histogram(aes(y = after_stat(count / max(count))))# Use a transparent version of colour for fillggplot(mpg, aes(class, hwy)) +  geom_boxplot(aes(colour = class, fill = after_scale(alpha(colour, 0.4))))# Use stage to modify the scaled fillggplot(mpg, aes(class, hwy)) +  geom_boxplot(aes(fill = stage(class, after_scale = alpha(fill, 0.4))))# Making a proportional stacked density plotggplot(mpg, aes(cty)) +  geom_density(    aes(      colour = factor(cyl),      fill = after_scale(alpha(colour, 0.3)),      y = after_stat(count / sum(n[!duplicated(group)]))    ),    position = "stack", bw = 1  ) +  geom_density(bw = 1)# Imitating a ridgeline plotggplot(mpg, aes(cty, colour = factor(cyl))) +  geom_ribbon(    stat = "density", outline.type = "upper",    aes(      fill = after_scale(alpha(colour, 0.3)),      ymin = after_stat(group),      ymax = after_stat(group + ndensity)    )  )# Labelling a bar plotggplot(mpg, aes(class)) +  geom_bar() +  geom_text(    aes(      y = after_stat(count + 2),      label = after_stat(count)    ),    stat = "count"  )# Labelling the upper hinge of a boxplot,# inspired by June Choeggplot(mpg, aes(displ, class)) +  geom_boxplot(outlier.shape = NA) +  geom_text(    aes(      label = after_stat(xmax),      x = stage(displ, after_stat = xmax)    ),    stat = "boxplot", hjust = -0.5  )

Aesthetics: grouping

Description

Thegroup aesthetic is by default set to the interaction of all discrete variablesin the plot. This choice often partitions the data correctly, but when it does not,or when no discrete variable is used in the plot, you will need to explicitly define thegrouping structure by mappinggroup to a variable that has a different valuefor each group.

Details

For most applications the grouping is set implicitly by mapping one or morediscrete variables tox,y,colour,fill,alpha,shape,size,and/orlinetype. This is demonstrated in the examples below.

There are three common cases where the default does not display the data correctly.

  1. geom_line() where there are multiple individuals and the plot tries toconnect every observation, even across individuals, with a line.

  2. geom_line() where a discrete x-position implies groups, whereas observationsspan the discrete x-positions.

  3. When the grouping needs to be different over different layers, for examplewhen computing a statistic on all observations when another layer showsindividuals.

The examples below use a longitudinal dataset,Oxboys, from the nlme package to demonstratethese cases.Oxboys records the heights (height) and centered ages (age) of 26 boys (Subject),measured on nine occasions (Occasion).

See Also

Other aesthetics documentation:aes(),aes_colour_fill_alpha,aes_linetype_size_shape,aes_position

Examples

p <- ggplot(mtcars, aes(wt, mpg))# A basic scatter plotp + geom_point(size = 4)# Using the colour aestheticp + geom_point(aes(colour = factor(cyl)), size = 4)# Using the shape aestheticp + geom_point(aes(shape = factor(cyl)), size = 4)# Using fillp <- ggplot(mtcars, aes(factor(cyl)))p + geom_bar()p + geom_bar(aes(fill = factor(cyl)))p + geom_bar(aes(fill = factor(vs)))# Using linetypesggplot(economics_long, aes(date, value01)) +  geom_line(aes(linetype = variable))# Multiple groups with one aestheticp <- ggplot(nlme::Oxboys, aes(age, height))# The default is not sufficient here. A single line tries to connect all# the observations.p + geom_line()# To fix this, use the group aesthetic to map a different line for each# subject.p + geom_line(aes(group = Subject))# Different groups on different layersp <- p + geom_line(aes(group = Subject))# Using the group aesthetic with both geom_line() and geom_smooth()# groups the data the same way for both layersp + geom_smooth(aes(group = Subject), method = "lm", se = FALSE)# Changing the group aesthetic for the smoother layer# fits a single line of best fit across all boysp + geom_smooth(aes(group = 1), size = 2, method = "lm", se = FALSE)# Overriding the default grouping# Sometimes the plot has a discrete scale but you want to draw lines# that connect across groups. This is the strategy used in interaction# plots, profile plots, and parallel coordinate plots, among others.# For example, we draw boxplots of height at each measurement occasion.p <- ggplot(nlme::Oxboys, aes(Occasion, height)) + geom_boxplot()p# There is no need to specify the group aesthetic here; the default grouping# works because occasion is a discrete variable. To overlay individual# trajectories, we again need to override the default grouping for that layer# with aes(group = Subject)p + geom_line(aes(group = Subject), colour = "blue")

Differentiation related aesthetics: linetype, size, shape

Description

Thelinetype,linewidth,size, andshape aesthetics modify theappearance of lines and/or points. They also apply to the outlines ofpolygons (linetype andlinewidth) or to text (size).

Linetype

Thelinetype aesthetic can be specified with either an integer (0-6), aname (0 = blank, 1 = solid, 2 = dashed, 3 = dotted, 4 = dotdash, 5 = longdash,6 = twodash), a mapping to a discrete variable, or a string of an even number(up to eight) of hexadecimal digits which give the lengths in consecutivepositions in the string. See examples for a hex string demonstration.

Linewidth and stroke

Thelinewidth aesthetic sets the widths of lines, and can be specifiedwith a numeric value (for historical reasons, these units are about 0.75millimetres). Alternatively, they can also be set via mapping to a continuousvariable. Thestroke aesthetic serves the same role for points, but isdistinct for discriminating points from lines in geoms such asgeom_pointrange().

Size

Thesize aesthetic control the size of points and text, and can bespecified with a numerical value (in millimetres) or via a mapping to acontinuous variable.

Shape

Theshape aesthetic controls the symbols of points, and can be specifiedwith an integer (between 0 and 25), a single character (which uses thatcharacter as the plotting symbol), a. to draw the smallest rectangle thatis visible (i.e., about one pixel), anNA to draw nothing, or a mapping toa discrete variable. Symbols and filled shapes are described in the examplesbelow.

See Also

Other aesthetics documentation:aes(),aes_colour_fill_alpha,aes_group_order,aes_position

Examples

df <- data.frame(x = 1:10 , y = 1:10)p <- ggplot(df, aes(x, y))p + geom_line(linetype = 2)p + geom_line(linetype = "dotdash")# An example with hex strings; the string "33" specifies three units on followed# by three off and "3313" specifies three units on followed by three off followed# by one on and finally three off.p + geom_line(linetype = "3313")# Mapping line type from a grouping variableggplot(economics_long, aes(date, value01)) +  geom_line(aes(linetype = variable))# Linewidth examplesggplot(economics, aes(date, unemploy)) +  geom_line(linewidth = 2, lineend = "round")ggplot(economics, aes(date, unemploy)) +  geom_line(aes(linewidth = uempmed), lineend = "round")# Size examplesp <- ggplot(mtcars, aes(wt, mpg))p + geom_point(size = 4)p + geom_point(aes(size = qsec))p + geom_point(size = 2.5) +  geom_hline(yintercept = 25, size = 3.5)# Shape examplesp + geom_point()p + geom_point(shape = 5)p + geom_point(shape = "k", size = 3)p + geom_point(shape = ".")p + geom_point(shape = NA)p + geom_point(aes(shape = factor(cyl)))# A look at all 25 symbolsdf2 <- data.frame(x = 1:5 , y = 1:25, z = 1:25)p <- ggplot(df2, aes(x, y))p + geom_point(aes(shape = z), size = 4) +  scale_shape_identity()# While all symbols have a foreground colour, symbols 19-25 also take a# background colour (fill)p + geom_point(aes(shape = z), size = 4, colour = "Red") +  scale_shape_identity()p + geom_point(aes(shape = z), size = 4, colour = "Red", fill = "Black") +  scale_shape_identity()

Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend

Description

The following aesthetics can be used to specify the position of elements:x,y,xmin,xmax,ymin,ymax,xend,yend.

Details

x andy define the locations of points or of positions along a lineor path.

x,y andxend,yend define the starting and ending points ofsegment and curve geometries.

xmin,xmax,ymin andymax can be used to specify the position ofannotations and to represent rectangular areas.

In addition, there are position aesthetics that are contextual to thegeometry that they're used in. These arexintercept,yintercept,xmin_final,ymin_final,xmax_final,ymax_final,xlower,lower,xmiddle,middle,xupper,upper,x0 andy0. Many of these are usedand automatically computed ingeom_boxplot().

Relation towidth andheight

The position aesthetics mentioned above likex andy are all locationbased. Thewidth andheight aesthetics are closely related lengthbased aesthetics, but are not position aesthetics. Consequently,x andyaesthetics respond to scale transformations, whereas the length basedwidth andheight aesthetics are not transformed by scales. For example,if we have the pair⁠x = 10, width = 2⁠, that gets translated to thelocations⁠xmin = 9, xmax = 11⁠ when using the default identity scales.However, the same pair becomes⁠xmin = 1, xmax = 100⁠ when using log10 scales,aswidth = 2 in log10-space spans a 100-fold change.

See Also

Other aesthetics documentation:aes(),aes_colour_fill_alpha,aes_group_order,aes_linetype_size_shape

Examples

# Generate data: means and standard errors of means for prices# for each type of cutdmod <- lm(price ~ cut, data = diamonds)cut <- unique(diamonds$cut)cuts_df <- data.frame(  cut,  predict(dmod, data.frame(cut), se = TRUE)[c("fit", "se.fit")])ggplot(cuts_df) +  aes(   x = cut,   y = fit,   ymin = fit - se.fit,   ymax = fit + se.fit,   colour = cut  ) +  geom_pointrange()# Using annotatep <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()pp + annotate(  "rect", xmin = 2, xmax = 3.5, ymin = 2, ymax = 25,  fill = "dark grey", alpha = .5)# Geom_segment examplesp + geom_segment(  aes(x = 2, y = 15, xend = 2, yend = 25),  arrow = arrow(length = unit(0.5, "cm")))p + geom_segment(  aes(x = 2, y = 15, xend = 3, yend = 15),  arrow = arrow(length = unit(0.5, "cm")))p + geom_segment(  aes(x = 5, y = 30, xend = 3.5, yend = 25),  arrow = arrow(length = unit(0.5, "cm")))# You can also use geom_segment() to recreate plot(type = "h")# from base R:set.seed(1)counts <- as.data.frame(table(x = rpois(100, 5)))counts$x <- as.numeric(as.character(counts$x))with(counts, plot(x, Freq, type = "h", lwd = 10))ggplot(counts, aes(x = x, y = Freq)) +  geom_segment(aes(yend = 0, xend = x), size = 10)

Create an annotation layer

Description

This function adds geoms to a plot, but unlike a typical geom function,the properties of the geoms are not mapped from variables of a data frame,but are instead passed in as vectors. This is useful for adding small annotations(such as text labels) or if you have your data in vectors, and for somereason don't want to put them in a data frame.

Usage

annotate(  geom,  x = NULL,  y = NULL,  xmin = NULL,  xmax = NULL,  ymin = NULL,  ymax = NULL,  xend = NULL,  yend = NULL,  ...,  na.rm = FALSE)

Arguments

geom

name of geom to use for annotation

x,y,xmin,ymin,xmax,ymax,xend,yend

positioning aesthetics -you must specify at least one of these.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

Details

Note that all position aesthetics are scaled (i.e. they will expand thelimits of the plot so they are visible), but all other aesthetics areset. This means that layers created with this function will neveraffect the legend.

Unsupported geoms

Due to their special nature, reference line geomsgeom_abline(),geom_hline(), andgeom_vline() can't be used withannotate().You can use these geoms directly for annotations.

See Also

Thecustom annotations section of the online ggplot2 book.

Examples

p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()p + annotate("text", x = 4, y = 25, label = "Some text")p + annotate("text", x = 2:5, y = 25, label = "Some text")p + annotate("rect", xmin = 3, xmax = 4.2, ymin = 12, ymax = 21,  alpha = .2)p + annotate("segment", x = 2.5, xend = 4, y = 15, yend = 25,  colour = "blue")p + annotate("pointrange", x = 3.5, y = 20, ymin = 12, ymax = 28,  colour = "red", size = 2.5, linewidth = 1.5)p + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2"))p + annotate("text", x = 4, y = 25, label = "italic(R) ^ 2 == 0.75",  parse = TRUE)p + annotate("text", x = 4, y = 25,  label = "paste(italic(R) ^ 2, \" = .75\")", parse = TRUE)

Create a layer of map borders

Description

This is a quick and dirty way to get map data (from themaps package)onto your plot. This is a good place to start if you need some crudereference lines, but you'll typically want something more sophisticatedfor communication graphics.

Usage

annotation_borders(  database = "world",  regions = ".",  fill = NA,  colour = "grey50",  xlim = NULL,  ylim = NULL,  ...)borders(...) # Deprecated

Arguments

database

map data, seemaps::map() for details

regions

map region

fill

fill colour

colour

border colour

xlim,ylim

latitudinal and longitudinal ranges for extracting mappolygons, seemaps::map() for details.

...

Arguments passed on togeom_polygon

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

rule

Either"evenodd" or"winding". If polygons with holes arebeing drawn (using thesubgroup aesthetic) this argument defines how thehole coordinates are interpreted. See the examples ingrid::pathGrob() foran explanation.

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

Examples

if (require("maps")) {data(us.cities)capitals <- subset(us.cities, capital == 2)ggplot(capitals, aes(long, lat)) +  annotation_borders("state") +  geom_point(aes(size = pop)) +  scale_size_area() +  coord_quickmap()}if (require("maps")) {# Same map, with some world contextggplot(capitals, aes(long, lat)) +  annotation_borders("world", xlim = c(-130, -60), ylim = c(20, 50)) +  geom_point(aes(size = pop)) +  scale_size_area() +  coord_quickmap()}

Annotation: Custom grob

Description

This is a special geom intended for use as static annotationsthat are the same in every panel. These annotations will notaffect scales (i.e. the x and y axes will not grow to cover the rangeof the grob, and the grob will not be modified by any ggplot settingsor mappings).

Usage

annotation_custom(grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)

Arguments

grob

grob to display

xmin,xmax

x location (in data coordinates) giving horizontallocation of raster

ymin,ymax

y location (in data coordinates) giving verticallocation of raster

Details

Most useful for adding tables, inset plots, and other grid-based decorations.

Note

annotation_custom() expects the grob to fill the entire viewportdefined by xmin, xmax, ymin, ymax. Grobs with a different (absolute) sizewill be center-justified in that region.Inf values can be used to fill the full plot panel (see examples).

Examples

# Dummy plotdf <- data.frame(x = 1:10, y = 1:10)base <- ggplot(df, aes(x, y)) +  geom_blank() +  theme_bw()# Full panel annotationbase + annotation_custom(  grob = grid::roundrectGrob(),  xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)# Inset plotdf2 <- data.frame(x = 1 , y = 1)g <- ggplotGrob(ggplot(df2, aes(x, y)) +  geom_point() +  theme(plot.background = element_rect(colour = "black")))base +  annotation_custom(grob = g, xmin = 1, xmax = 10, ymin = 8, ymax = 10)

Annotation: log tick marks

Description

[Superseded]

This function is superseded by usingguide_axis_logticks().

This annotation adds log tick marks with diminishing spacing.These tick marks probably make sense only for base 10.

Usage

annotation_logticks(  base = 10,  sides = "bl",  outside = FALSE,  scaled = TRUE,  short = unit(0.1, "cm"),  mid = unit(0.2, "cm"),  long = unit(0.3, "cm"),  colour = "black",  linewidth = 0.5,  linetype = 1,  alpha = 1,  color = NULL,  ...,  size = deprecated())

Arguments

base

the base of the log (default 10)

sides

a string that controls which sides of the plot the log ticks appear on.It can be set to a string containing any of"trbl", for top, right,bottom, and left.

outside

logical that controls whether to move the log ticks outsideof the plot area. Default is off (FALSE). You will also need to usecoord_cartesian(clip = "off"). See examples.

scaled

is the data already log-scaled? This should beTRUE(default) when the data is already transformed withlog10() or whenusingscale_y_log10(). It should beFALSE when usingcoord_transform(y = "log10").

short

agrid::unit() object specifying the length of theshort tick marks

mid

agrid::unit() object specifying the length of themiddle tick marks. In base 10, these are the "5" ticks.

long

agrid::unit() object specifying the length of thelong tick marks. In base 10, these are the "1" (or "10") ticks.

colour

Colour of the tick marks.

linewidth

Thickness of tick marks, in mm.

linetype

Linetype of tick marks (solid,dashed, etc.)

alpha

The transparency of the tick marks.

color

An alias forcolour.

...

Other parameters passed on to the layer

size

[Deprecated]

See Also

scale_y_continuous(),scale_y_log10() for log scaletransformations.

coord_transform() for log coordinate transformations.

Examples

# Make a log-log plot (without log ticks)a <- ggplot(msleep, aes(bodywt, brainwt)) + geom_point(na.rm = TRUE) + scale_x_log10(   breaks = scales::trans_breaks("log10", \(x) 10^x),   labels = scales::trans_format("log10", scales::math_format(10^.x)) ) + scale_y_log10(   breaks = scales::trans_breaks("log10", \(x) 10^x),   labels = scales::trans_format("log10", scales::math_format(10^.x)) ) + theme_bw()a + annotation_logticks()                # Default: log ticks on bottom and lefta + annotation_logticks(sides = "lr")    # Log ticks for y, on left and righta + annotation_logticks(sides = "trbl")  # All four sidesa + annotation_logticks(sides = "lr", outside = TRUE) + coord_cartesian(clip = "off")  # Ticks outside plot# Hide the minor grid lines because they don't align with the ticksa + annotation_logticks(sides = "trbl") + theme(panel.grid.minor = element_blank())# Another way to get the same results as 'a' above: log-transform the data before# plotting it. Also hide the minor grid lines.b <- ggplot(msleep, aes(log10(bodywt), log10(brainwt))) + geom_point(na.rm = TRUE) + scale_x_continuous(name = "body", labels = scales::label_math(10^.x)) + scale_y_continuous(name = "brain", labels = scales::label_math(10^.x)) + theme_bw() + theme(panel.grid.minor = element_blank())b + annotation_logticks()# Using a coordinate transform requires scaled = FALSEt <- ggplot(msleep, aes(bodywt, brainwt)) +  geom_point() +  coord_transform(x = "log10", y = "log10") +  theme_bw()t + annotation_logticks(scaled = FALSE)# Change the length of the ticksa + annotation_logticks(  short = unit(.5,"mm"),  mid = unit(3,"mm"),  long = unit(4,"mm"))

Annotation: a map

Description

Display a fixed map on a plot. This function predates thegeom_sf()framework and does not work with sf geometry columns as input. However,it can be used in conjunction withgeom_sf() layers and/orcoord_sf() (see examples).

Usage

annotation_map(map, ...)

Arguments

map

Data frame representing a map. Seegeom_map() fordetails.

...

Other arguments used to modify visual parameters, such ascolour orfill.

Examples

## Not run: if (requireNamespace("maps", quietly = TRUE)) {# location of cities in North Carolinadf <- data.frame(  name = c("Charlotte", "Raleigh", "Greensboro"),  lat = c(35.227, 35.772, 36.073),  long = c(-80.843, -78.639, -79.792))p <- ggplot(df, aes(x = long, y = lat)) +  annotation_map(    map_data("state"),    fill = "antiquewhite", colour = "darkgrey"  ) +  geom_point(color = "blue") +  geom_text(    aes(label = name),    hjust = 1.105, vjust = 1.05, color = "blue"  )# use without coord_sf() is possible but not recommendedp + xlim(-84, -76) + ylim(34, 37.2)if (requireNamespace("sf", quietly = TRUE)) {# use with coord_sf() for appropriate projectionp +  coord_sf(    crs = sf::st_crs(3347),    default_crs = sf::st_crs(4326),  # data is provided as long-lat    xlim = c(-84, -76),    ylim = c(34, 37.2)  )# you can mix annotation_map() and geom_sf()nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)p +  geom_sf(    data = nc, inherit.aes = FALSE,    fill = NA, color = "black", linewidth = 0.1  ) +  coord_sf(crs = sf::st_crs(3347), default_crs = sf::st_crs(4326))}}## End(Not run)

Annotation: high-performance rectangular tiling

Description

This is a special version ofgeom_raster() optimised for staticannotations that are the same in every panel. These annotations will notaffect scales (i.e. the x and y axes will not grow to cover the rangeof the raster, and the raster must already have its own colours). Thisis useful for adding bitmap images.

Usage

annotation_raster(raster, xmin, xmax, ymin, ymax, interpolate = FALSE)

Arguments

raster

raster object to display, may be anarray or anativeRaster

xmin,xmax

x location (in data coordinates) giving horizontallocation of raster

ymin,ymax

y location (in data coordinates) giving verticallocation of raster

interpolate

IfTRUE interpolate linearly, ifFALSE(the default) don't interpolate.

Examples

# Generate datarainbow <- matrix(hcl(seq(0, 360, length.out = 50 * 50), 80, 70), nrow = 50)ggplot(mtcars, aes(mpg, wt)) +  geom_point() +  annotation_raster(rainbow, 15, 20, 3, 4)# To fill up whole plotggplot(mtcars, aes(mpg, wt)) +  annotation_raster(rainbow, -Inf, Inf, -Inf, Inf) +  geom_point()rainbow2 <- matrix(hcl(seq(0, 360, length.out = 10), 80, 70), nrow = 1)ggplot(mtcars, aes(mpg, wt)) +  annotation_raster(rainbow2, -Inf, Inf, -Inf, Inf) +  geom_point()rainbow2 <- matrix(hcl(seq(0, 360, length.out = 10), 80, 70), nrow = 1)ggplot(mtcars, aes(mpg, wt)) +  annotation_raster(rainbow2, -Inf, Inf, -Inf, Inf, interpolate = TRUE) +  geom_point()

Convert a ggproto object to a list

Description

This will not include the object'ssuper member.

Usage

## S3 method for class 'ggproto'as.list(x, inherit = TRUE, ...)

Arguments

x

A ggproto object to convert to a list.

inherit

IfTRUE (the default), flatten all inherited items intothe returned list. IfFALSE, do not include any inherited items.

...

Arguments passed on tobase::as.list.environment

all.names

a logical indicating whether to copy all values or(default) only those whose names do not begin with a dot.

sorted

a logical indicating whether thenames ofthe resulting list should be sorted (increasingly). Note that thisis somewhat costly, but may be useful for comparison of environments.


Coerce to labeller function

Description

This transforms objects to labeller functions. Used internally bylabeller().

Usage

as_labeller(x, default = label_value, multi_line = TRUE)

Arguments

x

Object to coerce to a labeller function. If a namedcharacter vector, it is used as a lookup table before beingpassed on todefault. If a non-labeller function, it isassumed it takes and returns character vectors and is applied tothe labels. If a labeller, it is simply applied to the labels.

default

Default labeller to process the labels produced bylookup tables or modified by non-labeller functions.

multi_line

Whether to display the labels of multiple factorson separate lines. This is passed to the labeller function.

See Also

labeller(),labellers

Examples

p <- ggplot(mtcars, aes(disp, drat)) + geom_point()p + facet_wrap(~am)# Rename labels on the fly with a lookup character vectorto_string <- as_labeller(c(`0` = "Zero", `1` = "One"))p + facet_wrap(~am, labeller = to_string)# Quickly transform a function operating on character vectors to a# labeller function:appender <- function(string, suffix = "-foo") paste0(string, suffix)p + facet_wrap(~am, labeller = as_labeller(appender))# If you have more than one faceting variable, be sure to dispatch# your labeller to the right variable with labeller()p + facet_grid(cyl ~ am, labeller = labeller(am = to_string))

Create a ggplot layer appropriate to a particular data type

Description

autolayer() uses ggplot2 to draw a particular layer for an object of aparticular class in a single command. This defines the S3 generic thatother classes and packages can extend.

Usage

autolayer(object, ...)

Arguments

object

an object, whose class will determine the behaviour of autolayer

...

other arguments passed to specific methods

Value

a ggplot layer

See Also

Other plotting automation topics:automatic_plotting,autoplot(),fortify()


Tailoring plots to particular data types

Description

There are three functions to make plotting particular data types easier:autoplot(),autolayer() andfortify(). These are S3 generics for whichother packages can write methods to display classes of data. The threefunctions are complementary and allow different levels of customisation.Below we'll explore implementing this series of methods to automate plottingof some class.

Let's suppose we are writing a packages that has a class called 'my_heatmap',that wraps a matrix and we'd like users to easily plot this heatmap.

my_heatmap <- function(...) {  m <- matrix(...)  class(m) <- c("my_heatmap", class(m))  m}my_data <- my_heatmap(volcano)

Automatic data shaping

One of the things we have to do is ensure that the data is shaped in the longformat so that it is compatible with ggplot2. This is the job of thefortify() function. Because 'my_heatmap' wraps a matrix, we can let thefortify method 'melt' the matrix to a long format. If your data is alreadybased on a long-format⁠<data.frame>⁠, you can skip implementing afortify() method.

fortify.my_heatmap <- function(model, ...) {  data.frame(    row = as.vector(row(model)),    col = as.vector(col(model)),    value = as.vector(model)  )}fortify(my_data)

When you have implemented thefortify() method, it should be easier toconstruct a plot with the data than with the matrix.

ggplot(my_data, aes(x = col, y = row, fill = value)) +  geom_raster()

Automatic layers

A next step in automating plotting of your data type is to write anautolayer() method. These are typically wrappers around geoms or statsthat automatically set aesthetics or other parameters. If you haven'timplemented afortify() method for your data type, you might have toreshape the data inautolayer().

If you require multiple layers to display your data type, you can use anautolayer() method that constructs a list of layers, which can be addedto a plot.

autolayer.my_heatmap <- function(object, ...) {  geom_raster(    mapping = aes(x = col, y = row, fill = value),    data = object,    ...,    inherit.aes = FALSE  )}ggplot() + autolayer(my_data)

As a quick tip: if you define a mapping inautolayer(), you might wantto setinherit.aes = FALSE to not have aesthetics set in other layersinterfere with your layer.

Automatic plots

The last step in automating plotting is to write anautoplot() methodfor your data type. The expectation is that these return a complete plot.In the example below, we're exploiting theautolayer() method that wehave already written to make a complete plot.

autoplot.my_heatmap <- function(object, ..., option = "magma") {  ggplot() +    autolayer(my_data) +    scale_fill_viridis_c(option = option) +    theme_void()}autoplot(my_data)

If you don't have a wish to implement a base R plotting method, youcan set the plot method for your class to the autoplot method.

plot.my_heatmap <- autoplot.my_heatmapplot(my_data)

See Also

Other plotting automation topics:autolayer(),autoplot(),fortify()


Create a complete ggplot appropriate to a particular data type

Description

autoplot() uses ggplot2 to draw a particular plot for an object of aparticular class in a single command. This defines the S3 generic thatother classes and packages can extend.

Usage

autoplot(object, ...)

Arguments

object

an object, whose class will determine the behaviour of autoplot

...

other arguments passed to specific methods

Value

a ggplot object

See Also

Other plotting automation topics:autolayer(),automatic_plotting,fortify()


Benchmark plot creation time.Broken down into construct, build, render and draw times.

Description

Benchmark plot creation time.Broken down into construct, build, render and draw times.

Usage

benchplot(x)

Arguments

x

code to create ggplot2 plot

Examples

benchplot(ggplot(mtcars, aes(mpg, wt)) + geom_point())benchplot(ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_grid(. ~ cyl))# With tidy eval:p <- expr(ggplot(mtcars, aes(mpg, wt)) + geom_point())benchplot(!!p)

Utilities for working with bidirectional layers

Description

These functions are what underpins the ability of certain geoms to workautomatically in both directions. See theExtending ggplot2 vignette forhow they are used when implementingGeom,Stat, andPosition classes.

Usage

has_flipped_aes(  data,  params = list(),  main_is_orthogonal = NA,  range_is_orthogonal = NA,  group_has_equal = FALSE,  ambiguous = FALSE,  main_is_continuous = FALSE,  main_is_optional = FALSE,  default = FALSE)flip_data(data, flip = NULL)flipped_names(flip = FALSE)

Arguments

data

The layer data

params

The parameters of theStat/Geom. Only theorientationparameter will be used.

main_is_orthogonal

If onlyx ory are present do they correspondto the main orientation or the reverse. E.g. IfTRUE andy is presentit is not flipped. IfNA this check will be ignored.

range_is_orthogonal

Ifxmin/xmax orymin/ymax is present dothey correspond to the main orientation or reverse. IfNA this check willbe ignored.

group_has_equal

Is it expected that grouped data has either a singlex ory value that will correspond to the orientation.

ambiguous

Is the layer ambiguous in its mapping by nature. If so, itwill only be flipped ifparams$orientation == "y"

main_is_continuous

If there is a discrete and continuous axis, doesthe continuous one correspond to the main orientation?

main_is_optional

Is the main axis aesthetic optional and, if notgiven, set to0

default

The logical value to return if no orientation can be discernedfrom the data.

flip

Logical. Is the layer flipped.

Details

has_flipped_aes() is used to sniff out the orientation of the layer fromthe data. It has a range of arguments that can be used to finetune thesniffing based on what the data should look like.flip_data() will switchthe column names of the data so that it looks like x-oriented data.flipped_names() provides a named list of aesthetic names that correspondsto the orientation of the layer.

Value

has_flipped_aes() returnsTRUE if it detects a layer in the otherorientation andFALSE otherwise.flip_data() will return the inputunchanged ifflip = FALSE and the data with flipped aesthetic names ifflip = TRUE.flipped_names() returns a named list of strings. Ifflip = FALSE the name of the element will correspond to the element, e.g.flipped_names(FALSE)$x == "x" and ifflip = TRUE it will correspond tothe flipped name, e.g.flipped_names(FALSE)$x == "y"

Controlling the sniffing

How the layer data should be interpreted depends on its specific features.has_flipped_aes() contains a range of flags for defining what certainfeatures in the data correspond to:


Binning scale constructor

Description

Binning scale constructor

Usage

binned_scale(  aesthetics,  scale_name = deprecated(),  palette,  name = waiver(),  breaks = waiver(),  labels = waiver(),  limits = NULL,  rescaler = rescale,  oob = squish,  expand = waiver(),  na.value = NA_real_,  n.breaks = NULL,  nice.breaks = TRUE,  right = TRUE,  transform = "identity",  trans = deprecated(),  show.limits = FALSE,  guide = "bins",  position = "left",  fallback.palette = NULL,  call = caller_call(),  super = ScaleBinned)

Arguments

aesthetics

The names of the aesthetics that this scale works with.

scale_name

[Deprecated] The name of the scalethat should be used for error messages associated with this scale.

palette

A palette function that when called with a numeric vector withvalues between 0 and 1 returns the corresponding output values(e.g.,scales::pal_area()).

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by thetransformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaksas output (e.g., a function returned byscales::extended_breaks()).Note that for position scales, limits are provided after scale expansion.Also accepts rlanglambda function notation.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

rescaler

A function used to scale the input values to therange [0, 1]. This is alwaysscales::rescale(), except fordiverging and n colour gradients (i.e.,scale_colour_gradient2(),scale_colour_gradientn()). Therescaler is ignored by positionscales, which always usescales::rescale(). Also accepts rlanglambda function notation.

oob

One of:

  • Function that handles limits outside of the scale limits(out of bounds). Also accepts rlanglambdafunction notation.

  • The default (scales::squish()) squishes out ofbounds values into range.

  • scales::censor for replacing out of bounds values withNA.

  • scales::squish_infinite() for squishing infinite values into range.

expand

For position scales, a vector of range expansion constants used to add somepadding around the data to ensure that they are placed some distanceaway from the axes. Use the convenience functionexpansion()to generate the values for theexpand argument. The defaults are toexpand the scale by 5% on each side for continuous variables, and by0.6 units on each side for discrete variables.

na.value

Missing values will be replaced with this value.

n.breaks

The number of break points to create if breaks are not givendirectly.

nice.breaks

Logical. Should breaks be attempted placed at nice valuesinstead of exactly evenly spaced between the limits. IfTRUE (default)the scale will ask the transformation object to create breaks, and thismay result in a different number of breaks than requested. Ignored ifbreaks are given explicitly.

right

Should the intervals be closed on the right (TRUE, default) orshould the intervals be closed on the left (FALSE)? 'Closed on the right'means that values at break positions are part of the lower bin (open on theleft), whereas they are part of the upper bin when intervals are closed onthe left (open on the right).

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

trans

[Deprecated] Deprecated in favour oftransform.

show.limits

should the limits of the scale appear as ticks

guide

A function used to create a guide or its name. Seeguides() for more information.

position

For position scales, The position of the axis.left orright for y axes,top orbottom for x axes.

fallback.palette

Function to use whenpalette = NULL and thepalette is not represented in the theme.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

See Also

Thenew scales section of the online ggplot2 book.


Calculate the element properties, by inheriting properties from its parents

Description

Calculate the element properties, by inheriting properties from its parents

Usage

calc_element(  element,  theme,  verbose = FALSE,  skip_blank = FALSE,  call = caller_env())

Arguments

element

The name of the theme element to calculate

theme

A theme object (liketheme_grey())

verbose

If TRUE, print out which elements this one inherits from

skip_blank

If TRUE, elements of typeelement_blank in theinheritance hierarchy will be ignored.

Examples

t <- theme_grey()calc_element('text', t)# Compare the "raw" element definition to the element with calculated inheritancet$axis.text.xcalc_element('axis.text.x', t, verbose = TRUE)# This reports that axis.text.x inherits from axis.text,# which inherits from text. You can view each of them with:t$axis.text.xt$axis.textt$text

Check graphics device capabilities

Description

This function makes an attempt to estimate whether the graphics device isable to render newer graphics features.

Usage

check_device(  feature,  action = "warn",  op = NULL,  maybe = FALSE,  call = caller_env())

Arguments

feature

A string naming a graphics device feature. One of:"clippingPaths","alpha_masks","lumi_masks","compositing","blending","transformations","gradients","patterns","paths"or"glyphs". See the 'Features' section below for an explanationof these terms.

action

A string for what action to take. One of:

  • "test" returnsTRUE orFALSE indicating support of the feature.

  • "warn" also returns a logical, but throws an informative warning whenFALSE.

  • "abort" throws an error when the device is estimated to not supportthe feature.

op

A string for a specific operation to test for whenfeature iseither"blending" or"compositing". IfNULL (default), support forall known blending or compositing operations is queried.

maybe

A logical of length 1 determining what the return value shouldbe in case the device capabilities cannot be assessed. When the currentdevice is the 'null device',maybe is returned.

call

The execution environment of a currently running function, e.g.caller_env(). The function will be mentioned inwarnings and error messages as the source of the warning or error. Seethecall argument ofabort() for more information.

Details

The procedure for testing is as follows:

Value

TRUE when the feature is thought to be supported andFALSEotherwise.

Features

"clippingPaths"

While most devices support rectangular clippingregions, this feature is about the support for clipping to arbitrary paths.It can be used to only display a part of a drawing.

"alpha_masks"

Like clipping regions and paths, alpha masks can alsobe used to only display a part of a drawing. In particular asemi-transparent mask can be used to display a drawing in the opaque partsof the mask and hide a drawing in transparent part of a mask.

⁠"lumi_masks⁠

Similar to alpha masks, but using the mask's luminance(greyscale value) to determine what is drawn. Light values are opaque anddark values are transparent.

"compositing"

Compositing allows one to control how to drawingsare drawn in relation to one another. By default, one drawing is drawn'over' the previous one, but other operators are possible, like 'clear','in' and 'out'.

"blending"

When placing one drawing atop of another, the blendmode determines how the colours of the drawings relate to one another.

"transformations"

Performing an affine transformation on a groupcan be used to translate, rotate, scale, shear and flip the drawing.

"gradients"

Gradients can be used to show a transition betweentwo or more colours as a fill in a drawing. The checks expects both linearand radial gradients to be supported.

"patterns"

Patterns can be used to display a repeated, tileddrawing as a fill in another drawing.

"paths"

Contrary to 'paths' as polyline or polygon drawings,"paths" refers to the ability to fill and stroke collections ofdrawings.

"glyphs"

Refers to the advanced typesetting feature forcontrolling the appearance of individual glyphs.

Limitations

Examples

# Typically you'd run `check_device()` inside a function that might produce# advanced graphics.# The check is designed for use in control flow statements in the test modeif (check_device("patterns", action = "test")) {  print("Yay")} else {  print("Nay")}# Automatically throw a warning when unavailableif (check_device("compositing", action = "warn")) {  print("Yay")} else {  print("Nay")}# Possibly throw an errortry(check_device("glyphs", action = "abort"))

Class definitions

Description

The S7 object oriented programming system requires class definitions.Here, we provide definitions of classes that are home to ggplot2.

S7 classes

A general advice the S7 package gives is to name class definition objectsthe same as the class name, which then becomes the constructor for the class.The classes listed below deviate from that advice for historical reasons,because some constructors likeggplot() are also S3 generics with methods.The have theclass_-prefix to indicate their role.

Theme elements

The theme elements follow the advice of the S7 package that the class namesare also the class definitions and constructors.

ggproto classes

The ggproto classes are S3 classes of the type environment that form thebackbone of most systems in ggplot2 and are in particular crucial to theextension system.

S3 classes

Some simple classes remain S3, primarily because they aren't meant to berecycled into new classes.


The ggplot class

Description

The ggplot class collects the needed information to render a plot.This class can be constructed using theggplot() function.

Usage

class_ggplot(  data = waiver(),  ...,  layers = list(),  scales = NULL,  guides = NULL,  mapping = aes(),  theme = NULL,  coordinates = coord_cartesian(default = TRUE),  facet = facet_null(),  layout = NULL,  labels = labs(),  meta = list(),  plot_env = parent.frame())

Arguments

data

A property containing any data coerced byfortify().

...

Reserved for future expansion.

layers

A list of layer instances created bylayer().

scales

A ScalesList ggproto object.

guides

A Guides ggproto object created byguides().

mapping

A mapping class object created byaes().

theme

A theme class object created bytheme().

coordinates

A Coord ggproto object created by⁠coord_*()⁠ family offunctions.

facet

A Facet ggproto object created by⁠facet_*()⁠ family offunctions.

layout

A Layout ggproto object.

labels

A labels object created bylabs().

meta

A list for additional metadata. This will be deprecated in thefuture.

plot_env

An environment.


The ggplot built class

Description

The ggplot built class is an intermediate class and represents a processedggplot object ready for rendering. It is constructed by callingggplot_build() on aggplot object and is not meant to beinstantiated directly. The class can be rendered to a gtable object bycalling theggplot_gtable() function on a ggplot built class object.

Usage

class_ggplot_built(..., data = NULL, layout = NULL, plot = NULL)

Arguments

...

Reserved for future expansion.

data

A list of plain data frames; one for each layer.

layout

A Layout ggproto object.

plot

A completed ggplot class object.


The labels class

Description

The labels class holds a list with label information to display as titlesof plot components. The preferred way to construct an object of the labelsclass is to use thelabs() function.

Usage

class_labels(labels = list(), ...)

Arguments

labels

A named list.

...

Reserved for future expansion.

Details

All members oflabels are expected to be named and names should be unique.


The mapping class

Description

The mapping class holds a list of quoted expressions(quosures) or constants. An object is typicallyconstructed using theaes() function.

Usage

class_mapping(x = list(), ..., env = globalenv())

Arguments

x

A list of quosures and constants.

...

Reserved for future expansion.

env

An environment for symbols that are not quosures or constants.


The theme class

Description

The theme class holds information on how non-data elements of the plotshould be rendered. The preferred way to construct an object of this classis through thetheme() function.

Usage

class_theme(elements = list(), ..., complete = FALSE, validate = TRUE)

Arguments

elements

A named list containing theme elements.

...

Reserved for future expansion.

complete

A boolean value stating whether a theme is complete.

validate

A boolean value stating whether a theme should still bevalidated.


Take input data and define a mapping between faceting variables and ROW,COL and PANEL keys

Description

Take input data and define a mapping between faceting variables and ROW,COL and PANEL keys

Usage

combine_vars(data, env = emptyenv(), vars = NULL, drop = TRUE)

Arguments

data

A list of data.frames, the first being the plot data and thesubsequent individual layer data

env

The environment the vars should be evaluated in

vars

A list of quoted symbols matching columns in data

drop

should missing combinations/levels be dropped

Value

A data.frame with columns for PANEL, ROW, COL, and faceting vars


Complete a theme

Description

This function takes a theme and completes it so that it can be useddownstream to render theme elements. Missing elements are filled in andevery item is validated to the specifications of the element tree.

Usage

complete_theme(theme = NULL, default = theme_get())

Arguments

theme

An incompletetheme object to complete, orNULLto complete the default theme.

default

A completetheme to fill in missing pieces.Defaults to the global theme settings.

Value

Atheme object.

Examples

my_theme <- theme(line = element_line(colour = "red"))complete_theme(my_theme)

Continuous scale constructor

Description

Continuous scale constructor

Usage

continuous_scale(  aesthetics,  scale_name = deprecated(),  palette,  name = waiver(),  breaks = waiver(),  minor_breaks = waiver(),  n.breaks = NULL,  labels = waiver(),  limits = NULL,  rescaler = rescale,  oob = censor,  expand = waiver(),  na.value = NA,  transform = "identity",  trans = deprecated(),  guide = "legend",  position = "left",  fallback.palette = NULL,  call = caller_call(),  super = ScaleContinuous)

Arguments

aesthetics

The names of the aesthetics that this scale works with.

scale_name

[Deprecated] The name of the scalethat should be used for error messages associated with this scale.

palette

A palette function that when called with a numeric vector withvalues between 0 and 1 returns the corresponding output values(e.g.,scales::pal_area()).

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by thetransformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaksas output (e.g., a function returned byscales::extended_breaks()).Note that for position scales, limits are provided after scale expansion.Also accepts rlanglambda function notation.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

n.breaks

An integer guiding the number of major breaks. The algorithmmay choose a slightly different number to ensure nice break labels. Willonly have an effect ifbreaks = waiver(). UseNULL to use the defaultnumber of breaks given by the transformation.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

rescaler

A function used to scale the input values to therange [0, 1]. This is alwaysscales::rescale(), except fordiverging and n colour gradients (i.e.,scale_colour_gradient2(),scale_colour_gradientn()). Therescaler is ignored by positionscales, which always usescales::rescale(). Also accepts rlanglambda function notation.

oob

One of:

expand

For position scales, a vector of range expansion constants used to add somepadding around the data to ensure that they are placed some distanceaway from the axes. Use the convenience functionexpansion()to generate the values for theexpand argument. The defaults are toexpand the scale by 5% on each side for continuous variables, and by0.6 units on each side for discrete variables.

na.value

Missing values will be replaced with this value.

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

trans

[Deprecated] Deprecated in favour oftransform.

guide

A function used to create a guide or its name. Seeguides() for more information.

position

For position scales, The position of the axis.left orright for y axes,top orbottom for x axes.

fallback.palette

Function to use whenpalette = NULL and thepalette is not represented in the theme.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

See Also

Thenew scales section of the online ggplot2 book.


Cartesian coordinates

Description

The Cartesian coordinate system is the most familiar, and common, type ofcoordinate system. Setting limits on the coordinate system will zoom theplot (like you're looking at it with a magnifying glass), and will notchange the underlying data like setting limits on a scale will.

Usage

coord_cartesian(  xlim = NULL,  ylim = NULL,  expand = TRUE,  default = FALSE,  clip = "on",  reverse = "none",  ratio = NULL)

Arguments

xlim,ylim

Limits for the x and y axes.

expand

IfTRUE, the default, adds a small expansion factor tothe limits to ensure that data and axes don't overlap. IfFALSE,limits are taken exactly from the data orxlim/ylim.Giving a logical vector will separately control the expansion for the fourdirections (top, left, bottom and right). Theexpand argument will berecycled to length 4 if necessary. Alternatively, can be a named logicalvector to control a single direction, e.g.expand = c(bottom = FALSE).

default

Is this the default coordinate system? IfFALSE (the default),then replacing this coordinate system with another one creates a message alertingthe user that the coordinate system is being replaced. IfTRUE, that warningis suppressed.

clip

Should drawing be clipped to the extent of the plot panel? Asetting of"on" (the default) means yes, and a setting of"off"means no. In most cases, the default of"on" should not be changed,as settingclip = "off" can cause unexpected results. It allowsdrawing of data points anywhere on the plot, including in the plot margins. Iflimits are set viaxlim andylim and some data points fall outside thoselimits, then those data points may show up in places such as the axes, thelegend, the plot title, or the plot margins.

reverse

A string giving which directions to reverse."none"(default) keeps directions as is."x" and"y" can be used to reversetheir respective directions."xy" can be used to reverse bothdirections.

ratio

aspect ratio, expressed asy / x. Can beNULL (default) tonot use an aspect ratio. Using1 ensures that one unit on the x-axisis the same length as one unit on the y-axis. Ratios higher than one makeunits on the y-axis longer than units on the x-axis, and vice versa.

Examples

# There are two ways of zooming the plot display: with scales or# with coordinate systems.  They work in two rather different ways.p <- ggplot(mtcars, aes(disp, wt)) +  geom_point() +  geom_smooth()p# Setting the limits on a scale converts all values outside the range to NA.p + scale_x_continuous(limits = c(325, 500))# Setting the limits on the coordinate system performs a visual zoom.# The data is unchanged, and we just view a small portion of the original# plot. Note how smooth continues past the points visible on this plot.p + coord_cartesian(xlim = c(325, 500))# By default, the same expansion factor is applied as when setting scale# limits. You can set the limits precisely by setting expand = FALSEp + coord_cartesian(xlim = c(325, 500), expand = FALSE)# Similarly, we can use expand = FALSE to turn off expansion with the# default limitsp + coord_cartesian(expand = FALSE)# Using a fixed ratio: 1 y-axis unit is 100 x-axis units# Plot window can be resized and aspect ratio will be maintainedp + coord_cartesian(ratio = 100)# You can see the same thing with this 2d histogramd <- ggplot(diamonds, aes(carat, price)) +  stat_bin_2d(bins = 25, colour = "white")d# When zooming the scale, the we get 25 new bins that are the same# size on the plot, but represent smaller regions of the data spaced + scale_x_continuous(limits = c(0, 1))# When zooming the coordinate system, we see a subset of original 50 bins,# displayed biggerd + coord_cartesian(xlim = c(0, 1))

Cartesian coordinates with fixed "aspect ratio"

Description

A fixed scale coordinate system forces a specified ratio between thephysical representation of data units on the axes. The ratio represents thenumber of units on the y-axis equivalent to one unit on the x-axis. Thedefault,ratio = 1, ensures that one unit on the x-axis is the samelength as one unit on the y-axis. Ratios higher than one make units on they axis longer than units on the x-axis, and vice versa. This is similar toMASS::eqscplot(), but it works for all types of graphics.

Usage

coord_fixed(ratio = 1, ...)

Arguments

ratio

aspect ratio, expressed asy / x. Can beNULL (default) tonot use an aspect ratio. Using1 ensures that one unit on the x-axisis the same length as one unit on the y-axis. Ratios higher than one makeunits on the y-axis longer than units on the x-axis, and vice versa.

...

Arguments passed on tocoord_cartesian

xlim,ylim

Limits for the x and y axes.

expand

IfTRUE, the default, adds a small expansion factor tothe limits to ensure that data and axes don't overlap. IfFALSE,limits are taken exactly from the data orxlim/ylim.Giving a logical vector will separately control the expansion for the fourdirections (top, left, bottom and right). Theexpand argument will berecycled to length 4 if necessary. Alternatively, can be a named logicalvector to control a single direction, e.g.expand = c(bottom = FALSE).

default

Is this the default coordinate system? IfFALSE (the default),then replacing this coordinate system with another one creates a message alertingthe user that the coordinate system is being replaced. IfTRUE, that warningis suppressed.

clip

Should drawing be clipped to the extent of the plot panel? Asetting of"on" (the default) means yes, and a setting of"off"means no. In most cases, the default of"on" should not be changed,as settingclip = "off" can cause unexpected results. It allowsdrawing of data points anywhere on the plot, including in the plot margins. Iflimits are set viaxlim andylim and some data points fall outside thoselimits, then those data points may show up in places such as the axes, thelegend, the plot title, or the plot margins.

reverse

A string giving which directions to reverse."none"(default) keeps directions as is."x" and"y" can be used to reversetheir respective directions."xy" can be used to reverse bothdirections.

Examples

# ensures that the ranges of axes are equal to the specified ratio by# adjusting the plot aspect ratiop <- ggplot(mtcars, aes(mpg, wt)) + geom_point()p + coord_fixed(ratio = 1)p + coord_fixed(ratio = 5)p + coord_fixed(ratio = 1/5)p + coord_fixed(xlim = c(15, 30))# Resize the plot to see that the specified aspect ratio is maintained

Cartesian coordinates with x and y flipped

Description

[Superseded]

This function is superseded because in many cases,coord_flip() can easilybe replaced by swapping the x and y aesthetics, or optionally setting theorientation argument in geom and stat layers.

coord_flip() is useful for geoms and statistics that do not supporttheorientation setting, and converting the display of y conditional on x,to x conditional on y.

Usage

coord_flip(xlim = NULL, ylim = NULL, expand = TRUE, clip = "on")

Arguments

xlim,ylim

Limits for the x and y axes.

expand

IfTRUE, the default, adds a small expansion factor tothe limits to ensure that data and axes don't overlap. IfFALSE,limits are taken exactly from the data orxlim/ylim.Giving a logical vector will separately control the expansion for the fourdirections (top, left, bottom and right). Theexpand argument will berecycled to length 4 if necessary. Alternatively, can be a named logicalvector to control a single direction, e.g.expand = c(bottom = FALSE).

clip

Should drawing be clipped to the extent of the plot panel? Asetting of"on" (the default) means yes, and a setting of"off"means no. In most cases, the default of"on" should not be changed,as settingclip = "off" can cause unexpected results. It allowsdrawing of data points anywhere on the plot, including in the plot margins. Iflimits are set viaxlim andylim and some data points fall outside thoselimits, then those data points may show up in places such as the axes, thelegend, the plot title, or the plot margins.

Details

Coordinate systems interact with many parts of the plotting system. You canexpect the following forcoord_flip():

Examples

# The preferred method of creating horizontal instead of vertical boxplotsggplot(diamonds, aes(price, cut)) +  geom_boxplot()# Using `coord_flip()` to make the same plotggplot(diamonds, aes(cut, price)) +  geom_boxplot() +  coord_flip()# With swapped aesthetics, the y-scale controls the left axisggplot(diamonds, aes(y = carat)) +  geom_histogram() +  scale_y_reverse()# In `coord_flip()`, the x-scale controls the left axisggplot(diamonds, aes(carat)) +  geom_histogram() +  coord_flip() +  scale_x_reverse()# In line and area plots, swapped aesthetics require an explicit orientationdf <- data.frame(a = 1:5, b = (1:5) ^ 2)ggplot(df, aes(b, a)) +  geom_area(orientation = "y")# The same plot with `coord_flip()`ggplot(df, aes(a, b)) +  geom_area() +  coord_flip()

Map projections

Description

[Superseded]

coord_map() projects a portion of the earth, which is approximatelyspherical, onto a flat 2D plane using any projection defined by themapproj package. Map projections do not, in general, preserve straightlines, so this requires considerable computation.coord_quickmap() is aquick approximation that does preserve straight lines. It works best forsmaller areas closer to the equator.

Bothcoord_map() andcoord_quickmap()are superseded bycoord_sf(), and should no longer be used in newcode. All regular (non-sf) geoms can be used withcoord_sf() bysetting the default coordinate system via thedefault_crs argument.See also the examples forannotation_map() andgeom_map().

Usage

coord_map(  projection = "mercator",  ...,  parameters = NULL,  orientation = NULL,  xlim = NULL,  ylim = NULL,  clip = "on")coord_quickmap(xlim = NULL, ylim = NULL, expand = TRUE, clip = "on")

Arguments

projection

projection to use, seemapproj::mapproject() for list

...,parameters

Other arguments passed on tomapproj::mapproject(). Use... for named parameters tothe projection, andparameters for unnamed parameters.... is ignored if theparameters argument is present.

orientation

projection orientation, which defaults toc(90, 0, mean(range(x))). This is not optimal for manyprojections, so you will have to supply your own. Seemapproj::mapproject() for more information.

xlim,ylim

Manually specific x/y limits (in degrees oflongitude/latitude)

clip

Should drawing be clipped to the extent of the plot panel? Asetting of"on" (the default) means yes, and a setting of"off"means no. For details, please seecoord_cartesian().

expand

IfTRUE, the default, adds a small expansion factor tothe limits to ensure that data and axes don't overlap. IfFALSE,limits are taken exactly from the data orxlim/ylim.Giving a logical vector will separately control the expansion for the fourdirections (top, left, bottom and right). Theexpand argument will berecycled to length 4 if necessary. Alternatively, can be a named logicalvector to control a single direction, e.g.expand = c(bottom = FALSE).

Details

Map projections must account for the fact that the actual length(in km) of one degree of longitude varies between the equator and the pole.Near the equator, the ratio between the lengths of one degree of latitude andone degree of longitude is approximately 1. Near the pole, it tendstowards infinity because the length of one degree of longitude tends towards0. For regions that span only a few degrees and are not too close to thepoles, setting the aspect ratio of the plot to the appropriate lat/lon ratioapproximates the usual mercator projection. This is whatcoord_quickmap() does, and is much faster (particularly for complexplots likegeom_tile()) at the expense of correctness.

See Also

Thepolygon maps section of the online ggplot2 book.

Examples

if (require("maps")) {nz <- map_data("nz")# Prepare a map of NZnzmap <- ggplot(nz, aes(x = long, y = lat, group = group)) +  geom_polygon(fill = "white", colour = "black")# Plot it in cartesian coordinatesnzmap}if (require("maps")) {# With correct mercator projectionnzmap + coord_map()}if (require("maps")) {# With the aspect ratio approximationnzmap + coord_quickmap()}if (require("maps")) {# Other projectionsnzmap + coord_map("azequalarea", orientation = c(-36.92, 174.6, 0))}if (require("maps")) {states <- map_data("state")usamap <- ggplot(states, aes(long, lat, group = group)) +  geom_polygon(fill = "white", colour = "black")# Use cartesian coordinatesusamap}if (require("maps")) {# With mercator projectionusamap + coord_map()}if (require("maps")) {# See ?mapproject for coordinate systems and their parametersusamap + coord_map("gilbert")}if (require("maps")) {# For most projections, you'll need to set the orientation yourself# as the automatic selection done by mapproject is not available to# ggplotusamap + coord_map("orthographic")}if (require("maps")) {usamap + coord_map("conic", lat0 = 30)}if (require("maps")) {usamap + coord_map("bonne", lat0 = 50)}## Not run: if (require("maps")) {# World map, using geom_path instead of geom_polygonworld <- map_data("world")worldmap <- ggplot(world, aes(x = long, y = lat, group = group)) +  geom_path() +  scale_y_continuous(breaks = (-2:2) * 30) +  scale_x_continuous(breaks = (-4:4) * 45)# Orthographic projection with default orientation (looking down at North pole)worldmap + coord_map("ortho")}if (require("maps")) {# Looking up up at South Poleworldmap + coord_map("ortho", orientation = c(-90, 0, 0))}if (require("maps")) {# Centered on New York (currently has issues with closing polygons)worldmap + coord_map("ortho", orientation = c(41, -74, 0))}## End(Not run)

Munch coordinates data

Description

This function "munches" lines, dividing each line into many small piecesso they can be transformed independently. Used inside geom functions.

Usage

coord_munch(coord, data, range, segment_length = 0.01, is_closed = FALSE)

Arguments

coord

Coordinate system definition.

data

Data set to transform - should have variablesx andy are chopped up into small pieces (as defined bygroup).All other variables are duplicated as needed.

range

Panel range specification.

segment_length

Target segment length

is_closed

Whether data should be considered as a closed polygon.


Polar coordinates

Description

The polar coordinate system is most commonly used for pie charts, whichare a stacked bar chart in polar coordinates.
[Superseded]:coord_polar() has been in favour ofcoord_radial().

Usage

coord_polar(theta = "x", start = 0, direction = 1, clip = "on")coord_radial(  theta = "x",  start = 0,  end = NULL,  thetalim = NULL,  rlim = NULL,  expand = TRUE,  direction = deprecated(),  clip = "off",  r.axis.inside = NULL,  rotate.angle = FALSE,  inner.radius = 0,  reverse = "none",  r_axis_inside = deprecated(),  rotate_angle = deprecated())

Arguments

theta

variable to map angle to (x ory)

start

Offset of starting point from 12 o'clock in radians. Offsetis applied clockwise or anticlockwise depending on value ofdirection.

direction

1, clockwise; -1, anticlockwise

clip

Should drawing be clipped to the extent of the plot panel? Asetting of"on" (the default) means yes, and a setting of"off"means no. For details, please seecoord_cartesian().

end

Position from 12 o'clock in radians where plot ends, to allowfor partial polar coordinates. The default,NULL, is set tostart + 2 * pi.

thetalim,rlim

Limits for the theta and r axes.

expand

IfTRUE, the default, adds a small expansion factor tothe limits to prevent overlap between data and axes. IfFALSE, limitsare taken directly from the scale.

r.axis.inside

One of the following:

  • NULL (default) places the axis next to the panel ifstart andend arguments form a full circle and inside the panel otherwise.

  • TRUE to place the radius axis inside the panel.

  • FALSE to place the radius axis next to the panel.

  • A numeric value, setting a theta axis value at whichthe axis should be placed inside the panel. Can be given as a length 2vector to control primary and secondary axis placement separately.

rotate.angle

IfTRUE, transforms theangle aesthetic in datain accordance with the computedtheta position. IfFALSE (default),no such transformation is performed. Can be useful to rotate text geoms inalignment with the coordinates.

inner.radius

Anumeric between 0 and 1 setting the size of ainner radius hole.

reverse

A string giving which directions to reverse."none"(default) keep directions as is."theta" reverses the angle and"r"reverses the radius."thetar" reverses both the angle and the radius.

r_axis_inside,rotate_angle

[Deprecated]

Note

Incoord_radial(), position guides can be defined by usingguides(r = ..., theta = ..., r.sec = ..., theta.sec = ...). Note thatthese guides requirer andtheta as available aesthetics. The classicguide_axis() can be used for ther positions andguide_axis_theta() canbe used for thetheta positions. Using thetheta.sec position is onlysensible wheninner.radius > 0.

See Also

Thepolar coordinates section of the online ggplot2 book.

Examples

# NOTE: Use these plots with caution - polar coordinates has# major perceptual problems.  The main point of these examples is# to demonstrate how these common plots can be described in the# grammar.  Use with EXTREME caution.# A pie chart = stacked bar chart + polar coordinatespie <- ggplot(mtcars, aes(x = factor(1), fill = factor(cyl))) + geom_bar(width = 1)pie + coord_radial(theta = "y", expand = FALSE)# A coxcomb plot = bar chart + polar coordinatescxc <- ggplot(mtcars, aes(x = factor(cyl))) +  geom_bar(width = 1, colour = "black")cxc + coord_radial(expand = FALSE)# A new type of plot?cxc + coord_radial(theta = "y", expand = FALSE)# The bullseye chartpie + coord_radial(expand = FALSE)# Hadley's favourite pie chartdf <- data.frame(  variable = c("does not resemble", "resembles"),  value = c(20, 80))ggplot(df, aes(x = "", y = value, fill = variable)) +  geom_col(width = 1) +  scale_fill_manual(values = c("red", "yellow")) +  coord_radial("y", start = pi / 3, expand =  FALSE) +  labs(title = "Pac man")# Windrose + doughnut plotif (require("ggplot2movies")) {movies$rrating <- cut_interval(movies$rating, length = 1)movies$budgetq <- cut_number(movies$budget, 4)doh <- ggplot(movies, aes(x = rrating, fill = budgetq))# Wind rosedoh + geom_bar(width = 1) + coord_radial(expand = FALSE)# Race track plotdoh + geom_bar(width = 0.9, position = "fill") +  coord_radial(theta = "y", expand = FALSE)}# A partial polar plotggplot(mtcars, aes(disp, mpg)) +  geom_point() +  coord_radial(start = -0.4 * pi, end = 0.4 * pi, inner.radius = 0.3)# Similar with coord_cartesian(), you can set limits.ggplot(mtcars, aes(disp, mpg)) +  geom_point() +  coord_radial(    start = -0.4 * pi,    end = 0.4 * pi, inner.radius = 0.3,    thetalim = c(200, 300),    rlim = c(15, 30),  )

Transformed Cartesian coordinate system

Description

coord_transform() is different to scale transformations in that it occurs afterstatistical transformation and will affect the visual appearance of geoms - there isno guarantee that straight lines will continue to be straight.

Usage

coord_transform(  x = "identity",  y = "identity",  xlim = NULL,  ylim = NULL,  limx = deprecated(),  limy = deprecated(),  clip = "on",  expand = TRUE,  reverse = "none")coord_trans(...)

Arguments

x,y

Transformers for x and y axes or their names.

xlim,ylim

Limits for the x and y axes.

limx,limy

[Deprecated] usexlim andylim instead.

clip

Should drawing be clipped to the extent of the plot panel? Asetting of"on" (the default) means yes, and a setting of"off"means no. In most cases, the default of"on" should not be changed,as settingclip = "off" can cause unexpected results. It allowsdrawing of data points anywhere on the plot, including in the plot margins. Iflimits are set viaxlim andylim and some data points fall outside thoselimits, then those data points may show up in places such as the axes, thelegend, the plot title, or the plot margins.

expand

IfTRUE, the default, adds a small expansion factor tothe limits to ensure that data and axes don't overlap. IfFALSE,limits are taken exactly from the data orxlim/ylim.Giving a logical vector will separately control the expansion for the fourdirections (top, left, bottom and right). Theexpand argument will berecycled to length 4 if necessary. Alternatively, can be a named logicalvector to control a single direction, e.g.expand = c(bottom = FALSE).

reverse

A string giving which directions to reverse."none"(default) keeps directions as is."x" and"y" can be used to reversetheir respective directions."xy" can be used to reverse bothdirections.

...

Arguments forwarded tocoord_transform().

Details

Transformations only work with continuous values: seescales::new_transform() for list of transformations, and instructionson how to create your own.

Thecoord_trans() function is deprecated in favour ofcoord_transform().

See Also

Thecoord transformations section of the online ggplot2 book.

Examples

# See ?geom_boxplot for other examples# Three ways of doing transformation in ggplot:#  * by transforming the dataggplot(diamonds, aes(log10(carat), log10(price))) +  geom_point()#  * by transforming the scalesggplot(diamonds, aes(carat, price)) +  geom_point() +  scale_x_log10() +  scale_y_log10()#  * by transforming the coordinate system:ggplot(diamonds, aes(carat, price)) +  geom_point() +  coord_transform(x = "log10", y = "log10")# The difference between transforming the scales and# transforming the coordinate system is that scale# transformation occurs BEFORE statistics, and coordinate# transformation afterwards.  Coordinate transformation also# changes the shape of geoms:d <- subset(diamonds, carat > 0.5)ggplot(d, aes(carat, price)) +  geom_point() +  geom_smooth(method = "lm") +  scale_x_log10() +  scale_y_log10()ggplot(d, aes(carat, price)) +  geom_point() +  geom_smooth(method = "lm") +  coord_transform(x = "log10", y = "log10")# Here I used a subset of diamonds so that the smoothed line didn't# drop below zero, which obviously causes problems on the log-transformed# scale# With a combination of scale and coordinate transformation, it's# possible to do back-transformations:ggplot(diamonds, aes(carat, price)) +  geom_point() +  geom_smooth(method = "lm") +  scale_x_log10() +  scale_y_log10() +  coord_transform(x = scales::transform_exp(10), y = scales::transform_exp(10))# cf.ggplot(diamonds, aes(carat, price)) +  geom_point() +  geom_smooth(method = "lm")# Also works with discrete scalesset.seed(1)df <- data.frame(a = abs(rnorm(26)),letters)plot <- ggplot(df,aes(a,letters)) + geom_point()plot + coord_transform(x = "log10")plot + coord_transform(x = "sqrt")

Discretise numeric data into categorical

Description

cut_interval() makesn groups with equal range,cut_number()makesn groups with (approximately) equal numbers of observations;cut_width() makes groups of widthwidth.

Usage

cut_interval(x, n = NULL, length = NULL, ...)cut_number(x, n = NULL, ...)cut_width(x, width, center = NULL, boundary = NULL, closed = "right", ...)

Arguments

x

numeric vector

n

number of intervals to create, OR

length

length of each interval

...

Arguments passed on tobase::cut.default

breaks

either a numeric vector of two or more unique cut points or asingle number (greater than or equal to 2) giving the number ofintervals into whichx is to be cut.

labels

labels for the levels of the resulting category. By default,labels are constructed using"(a,b]" interval notation. Iflabels = FALSE, simple integer codes are returned instead ofa factor.

right

logical, indicating if the intervals should be closed onthe right (and open on the left) or vice versa.

dig.lab

integer which is used when labels are not given. Itdetermines the number of digits used in formatting the break numbers.

ordered_result

logical: should the result be an ordered factor?

width

The bin width.

center,boundary

Specify either the position of edge or the center ofa bin. Since all bins are aligned, specifying the position of a single bin(which doesn't need to be in the range of the data) affects the location ofall bins. If not specified, uses the "tile layers algorithm", and setsthe boundary to half of the binwidth.

To center on integers,width = 1 andcenter = 0.boundary = 0.5.

closed

One of"right" or"left" indicating whether rightor left edges of bins are included in the bin.

Author(s)

Randall Prium contributed most of the implementation ofcut_width().

Examples

table(cut_interval(1:100, 10))table(cut_interval(1:100, 11))set.seed(1)table(cut_number(runif(1000), 10))table(cut_width(runif(1000), 0.1))table(cut_width(runif(1000), 0.1, boundary = 0))table(cut_width(runif(1000), 0.1, center = 0))table(cut_width(runif(1000), 0.1, labels = FALSE))

Date/time scale constructor

Description

Date/time scale constructor

Usage

datetime_scale(  aesthetics,  transform,  trans = deprecated(),  palette,  breaks = pretty_breaks(),  minor_breaks = waiver(),  labels = waiver(),  date_breaks = waiver(),  date_labels = waiver(),  date_minor_breaks = waiver(),  timezone = NULL,  guide = "legend",  call = caller_call(),  ...)

Arguments

aesthetics

The names of the aesthetics that this scale works with.

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

trans

For date/time scales, the name of a date/time transformation orthe object itself. Built-in transformations include "hms", "date" and "time".

palette

A palette function that when called with a numeric vector withvalues between 0 and 1 returns the corresponding output values(e.g.,scales::pal_area()).

breaks

One of:

  • NULL for no breaks

  • waiver() for the breaks specified bydate_breaks

  • ADate/POSIXct vector giving positions of breaks

  • A function that takes the limits as input and returns breaks as output

minor_breaks

One of:

  • NULL for no breaks

  • waiver() for the breaks specified bydate_minor_breaks

  • ADate/POSIXct vector giving positions of minor breaks

  • A function that takes the limits as input and returns minor breaks asoutput

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

date_breaks

A string giving the distance between breaks like "2weeks", or "10 years". If bothbreaks anddate_breaks arespecified,date_breaks wins. Valid specifications are 'sec', 'min','hour', 'day', 'week', 'month' or 'year', optionally followed by 's'.

date_labels

A string giving the formatting specification for thelabels. Codes are defined instrftime(). If bothlabelsanddate_labels are specified,date_labels wins.

date_minor_breaks

A string giving the distance between minor breakslike "2 weeks", or "10 years". If bothminor_breaks anddate_minor_breaks are specified,date_minor_breaks wins. Validspecifications are 'sec', 'min', 'hour', 'day', 'week', 'month' or 'year',optionally followed by 's'.

timezone

The timezone to use for display on the axes. The default(NULL) uses the timezone encoded in the data.

guide

A function used to create a guide or its name. Seeguides() for more information.

call

Thecall used to construct the scale for reporting messages.

...

Arguments passed on tocontinuous_scale

scale_name

[Deprecated] The name of the scalethat should be used for error messages associated with this scale.

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

n.breaks

An integer guiding the number of major breaks. The algorithmmay choose a slightly different number to ensure nice break labels. Willonly have an effect ifbreaks = waiver(). UseNULL to use the defaultnumber of breaks given by the transformation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

rescaler

A function used to scale the input values to therange [0, 1]. This is alwaysscales::rescale(), except fordiverging and n colour gradients (i.e.,scale_colour_gradient2(),scale_colour_gradientn()). Therescaler is ignored by positionscales, which always usescales::rescale(). Also accepts rlanglambda function notation.

oob

One of:

na.value

Missing values will be replaced with this value.

expand

For position scales, a vector of range expansion constants used to add somepadding around the data to ensure that they are placed some distanceaway from the axes. Use the convenience functionexpansion()to generate the values for theexpand argument. The defaults are toexpand the scale by 5% on each side for continuous variables, and by0.6 units on each side for discrete variables.

fallback.palette

Function to use whenpalette = NULL and thepalette is not represented in the theme.

position

For position scales, The position of the axis.left orright for y axes,top orbottom for x axes.

super

The super class to use for the constructed scale


Prices of over 50,000 round cut diamonds

Description

A dataset containing the prices and other attributes of almost 54,000diamonds. The variables are as follows:

Usage

diamonds

Format

A data frame with 53940 rows and 10 variables:

price

price in US dollars ($326–$18,823)

carat

weight of the diamond (0.2–5.01)

cut

quality of the cut (Fair, Good, Very Good, Premium, Ideal)

color

diamond colour, from D (best) to J (worst)

clarity

a measurement of how clear the diamond is (I1 (worst), SI2,SI1, VS2, VS1, VVS2, VVS1, IF (best))

x

length in mm (0–10.74)

y

width in mm (0–58.9)

z

depth in mm (0–31.8)

depth

total depth percentage = z / mean(x, y) = 2 * z / (x + y) (43–79)

table

width of top of diamond relative to widest point (43–95)


Discrete scale constructor

Description

Discrete scale constructor

Usage

discrete_scale(  aesthetics,  scale_name = deprecated(),  palette,  name = waiver(),  breaks = waiver(),  minor_breaks = waiver(),  labels = waiver(),  limits = NULL,  expand = waiver(),  na.translate = TRUE,  na.value = NA,  drop = TRUE,  guide = "legend",  position = "left",  fallback.palette = NULL,  call = caller_call(),  super = ScaleDiscrete)

Arguments

aesthetics

The names of the aesthetics that this scale works with.

scale_name

[Deprecated] The name of the scalethat should be used for error messages associated with this scale.

palette

A palette function that when called with a single integerargument (the number of levels in the scale) returns the values thatthey should take (e.g.,scales::pal_hue()).

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks (the scale limits)

  • A character vector of breaks

  • A function that takes the limits as input and returns breaksas output. Also accepts rlanglambda functionnotation.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale values

  • A character vector that defines possible values of the scale and theirorder

  • A function that accepts the existing (automatic) values and returnsnew ones. Also accepts rlanglambda functionnotation.

expand

For position scales, a vector of range expansion constants used to add somepadding around the data to ensure that they are placed some distanceaway from the axes. Use the convenience functionexpansion()to generate the values for theexpand argument. The defaults are toexpand the scale by 5% on each side for continuous variables, and by0.6 units on each side for discrete variables.

na.translate

Unlike continuous scales, discrete scales can easily showmissing values, and do so by default. If you want to remove missing valuesfrom a discrete scale, specifyna.translate = FALSE.

na.value

Ifna.translate = TRUE, what aesthetic value should themissing values be displayed as? Does not apply to position scaleswhereNA is always placed at the far right.

drop

Should unused factor levels be omitted from the scale?The default,TRUE, uses the levels that appear in the data;FALSE includes the levels in the factor. Please note that to displayevery level in a legend, the layer should useshow.legend = TRUE.

guide

A function used to create a guide or its name. Seeguides() for more information.

position

For position scales, The position of the axis.left orright for y axes,top orbottom for x axes.

fallback.palette

Function to use whenpalette = NULL and thepalette is not represented in the theme.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

See Also

Thenew scales section of the online ggplot2 book.


Key glyphs for legends

Description

Each geom has an associated function that draws the key when the geom needsto be displayed in a legend. These functions are called⁠draw_key_*()⁠, where* stands for the name of the respective key glyph. The key glyphs can becustomized for individual geoms by providing a geom with thekey_glyphargument (seelayer() or examples below.)

Usage

draw_key_point(data, params, size)draw_key_abline(data, params, size)draw_key_rect(data, params, size)draw_key_polygon(data, params, size)draw_key_blank(data, params, size)draw_key_boxplot(data, params, size)draw_key_crossbar(data, params, size)draw_key_path(data, params, size)draw_key_vpath(data, params, size)draw_key_dotplot(data, params, size)draw_key_linerange(data, params, size)draw_key_pointrange(data, params, size)draw_key_smooth(data, params, size)draw_key_text(data, params, size)draw_key_label(data, params, size)draw_key_vline(data, params, size)draw_key_timeseries(data, params, size)

Arguments

data

A single row data frame containing the scaled aesthetics todisplay in this key

params

A list of additional parameters supplied to the geom.

size

Width and height of key in mm.

Value

A grid grob.

Examples

p <- ggplot(economics, aes(date, psavert, color = "savings rate"))# key glyphs can be specified by their namep + geom_line(key_glyph = "timeseries")# key glyphs can be specified via their drawing functionp + geom_line(key_glyph = draw_key_rect)

US economic time series

Description

This dataset was produced from US economic time series data available fromhttps://fred.stlouisfed.org/.economics is in "wide"format,economics_long is in "long" format.

Usage

economicseconomics_long

Format

A data frame with 574 rows and 6 variables:

date

Month of data collection

pce

personal consumption expenditures, in billions of dollars,https://fred.stlouisfed.org/series/PCE

pop

total population, in thousands,https://fred.stlouisfed.org/series/POP

psavert

personal savings rate,https://fred.stlouisfed.org/series/PSAVERT/

uempmed

median duration of unemployment, in weeks,https://fred.stlouisfed.org/series/UEMPMED

unemploy

number of unemployed in thousands,https://fred.stlouisfed.org/series/UNEMPLOY

An object of classtbl_df (inherits fromtbl,data.frame) with 2870 rows and 4 columns.


Generate grid grob from theme element

Description

Theelement_grob() function is vestigial anddraw_element() shouldbe used instead.

Usage

element_grob(element, ...)

Arguments

element

Theme element, i.e.element_rect or similar.

...

Other arguments to control specific of rendering. This isusually at least position. See the source code for individual methods.


Render a specified theme element into a grob

Description

Given a theme object and element name, returns a grob for the element.Useselement_grob() to generate the grob.

Usage

element_render(theme, element, ..., name = NULL)

Arguments

theme

The theme object

element

The element name given as character vector

...

Other arguments provided toelement_grob()

name

Character vector added to the name of the grob


Expand the plot limits, using data

Description

[Superseded]: It is recommended to pass a function tothelimits argument in scales instead. For example:scale_x_continuous(limits = ~range(.x, 0)) to include zero.

Sometimes you may want to ensure limits include a single value, for allpanels or all plots. This function is a thin wrapper aroundgeom_blank() that makes it easy to add such values.

Usage

expand_limits(...)

Arguments

...

named list of aesthetics specifying the value (or values) thatshould be included in each scale.

Examples

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()p + expand_limits(x = 0)p + expand_limits(y = c(1, 9))p + expand_limits(x = 0, y = 0)ggplot(mtcars, aes(mpg, wt)) +  geom_point(aes(colour = cyl)) +  expand_limits(colour = seq(2, 10, by = 2))ggplot(mtcars, aes(mpg, wt)) +  geom_point(aes(colour = factor(cyl))) +  expand_limits(colour = factor(seq(2, 10, by = 2)))

Generate expansion vector for scales

Description

This is a convenience function for generating scale expansion vectorsfor theexpand argument ofscale_(x|y)_continuousandscale_(x|y)_discrete. The expansion vectors are used toadd some space between the data and the axes.

Usage

expansion(mult = 0, add = 0)expand_scale(mult = 0, add = 0)

Arguments

mult

vector of multiplicative range expansion factors.If length 1, both the lower and upper limits of the scaleare expanded outwards bymult. If length 2, the lower limitis expanded bymult[1] and the upper limit bymult[2].

add

vector of additive range expansion constants.If length 1, both the lower and upper limits of the scaleare expanded outwards byadd units. If length 2, thelower limit is expanded byadd[1] and the upperlimit byadd[2].

Examples

# No space below the bars but 10% above themggplot(mtcars) +  geom_bar(aes(x = factor(cyl))) +  scale_y_continuous(expand = expansion(mult = c(0, .1)))# Add 2 units of space on the left and right of the dataggplot(subset(diamonds, carat > 2), aes(cut, clarity)) +  geom_jitter() +  scale_x_discrete(expand = expansion(add = 2))# Reproduce the default range expansion used# when the 'expand' argument is not specifiedggplot(subset(diamonds, carat > 2), aes(cut, price)) +  geom_jitter() +  scale_x_discrete(expand = expansion(add = .6)) +  scale_y_continuous(expand = expansion(mult = .05))

Lay out panels in a grid

Description

facet_grid() forms a matrix of panels defined by row and columnfaceting variables. It is most useful when you have two discretevariables, and all combinations of the variables exist in the data.If you have only one variable with many levels, tryfacet_wrap().

Usage

facet_grid(  rows = NULL,  cols = NULL,  scales = "fixed",  space = "fixed",  shrink = TRUE,  labeller = "label_value",  as.table = TRUE,  switch = NULL,  drop = TRUE,  margins = FALSE,  axes = "margins",  axis.labels = "all",  facets = deprecated())

Arguments

rows,cols

A set of variables or expressions quoted byvars() and defining faceting groups on the rows or columnsdimension. The variables can be named (the names are passed tolabeller).

For compatibility with the classic interface,rows can also bea formula with the rows (of the tabular display) on the LHS andthe columns (of the tabular display) on the RHS; the dot in theformula is used to indicate there should be no faceting on thisdimension (either row or column).

scales

Are scales shared across all facets (the default,"fixed"), or do they vary across rows ("free_x"),columns ("free_y"), or both rows and columns ("free")?

space

If"fixed", the default, all panels have the same size.If"free_y" their height will be proportional to the length of they scale; if"free_x" their width will be proportional to thelength of the x scale; or if"free" both height and width willvary. This setting has no effect unless the appropriate scales also vary.

shrink

IfTRUE, will shrink scales to fit output ofstatistics, not raw data. IfFALSE, will be range of raw databefore statistical summary.

labeller

A function that takes one data frame of labels andreturns a list or data frame of character vectors. Each inputcolumn corresponds to one factor. Thus there will be more thanone withvars(cyl, am). Each outputcolumn gets displayed as one separate line in the striplabel. This function should inherit from the "labeller" S3 classfor compatibility withlabeller(). You can use different labelingfunctions for different kind of labels, for example uselabel_parsed() forformatting facet labels.label_value() is used by default,check it for more details and pointers to other options.

as.table

IfTRUE, the default, the facets are laid out likea table with highest values at the bottom-right. IfFALSE, thefacets are laid out like a plot with the highest value at the top-right.

switch

By default, the labels are displayed on the top andright of the plot. If"x", the top labels will bedisplayed to the bottom. If"y", the right-hand sidelabels will be displayed to the left. Can also be set to"both".

drop

IfTRUE, the default, all factor levels not used in thedata will automatically be dropped. IfFALSE, all factor levelswill be shown, regardless of whether or not they appear in the data.

margins

Either a logical value or a charactervector. Margins are additional facets which contain all the datafor each of the possible values of the faceting variables. IfFALSE, no additional facets are included (thedefault). IfTRUE, margins are included for all facetingvariables. If specified as a character vector, it is the names ofvariables for which margins are to be created.

axes

Determines which axes will be drawn. When"margins"(default), axes will be drawn at the exterior margins."all_x" and"all_y" will draw the respective axes at the interior panels too, whereas"all" will draw all axes at all panels.

axis.labels

Determines whether to draw labels for interior axes whentheaxes argument is not"margins". When"all" (default), allinterior axes get labels. When"margins", only the exterior axes getlabels and the interior axes get none. When"all_x" or"all_y", onlydraws the labels at the interior axes in the x- or y-directionrespectively.

facets

[Deprecated] Please userowsandcols instead.

Layer layout

Thelayer(layout) argument in context offacet_grid() can takethe following values:

See Also

Thefacet grid section of the online ggplot2 book.

Examples

p <- ggplot(mpg, aes(displ, cty)) + geom_point()# Use vars() to supply variables from the dataset:p + facet_grid(rows = vars(drv))p + facet_grid(cols = vars(cyl))p + facet_grid(vars(drv), vars(cyl))# To change plot order of facet grid,# change the order of variable levels with factor()# If you combine a facetted dataset with a dataset that lacks those# faceting variables, the data will be repeated across the missing# combinations:df <- data.frame(displ = mean(mpg$displ), cty = mean(mpg$cty))p +  facet_grid(cols = vars(cyl)) +  geom_point(data = df, colour = "red", size = 2)# When scales are constant, duplicated axes can be shown with# or without labelsggplot(mpg, aes(cty, hwy)) +  geom_point() +  facet_grid(year ~ drv, axes = "all", axis.labels = "all_x")# Free scales -------------------------------------------------------# You can also choose whether the scales should be constant# across all panels (the default), or whether they should be allowed# to varymt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +  geom_point()mt + facet_grid(vars(cyl), scales = "free")# If scales and space are free, then the mapping between position# and values in the data will be the same across all panels. This# is particularly useful for categorical axesggplot(mpg, aes(drv, model)) +  geom_point() +  facet_grid(manufacturer ~ ., scales = "free", space = "free") +  theme(strip.text.y = element_text(angle = 0))# Margins ----------------------------------------------------------# Margins can be specified logically (all yes or all no) or for specific# variables as (character) variable namesmg <- ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point()mg + facet_grid(vs + am ~ gear, margins = TRUE)mg + facet_grid(vs + am ~ gear, margins = "am")# when margins are made over "vs", since the facets for "am" vary# within the values of "vs", the marginal facet for "vs" is also# a margin over "am".mg + facet_grid(vs + am ~ gear, margins = "vs")

Facet specification: a single panel.

Description

Facet specification: a single panel.

Usage

facet_null(shrink = TRUE)

Arguments

shrink

IfTRUE, will shrink scales to fit output ofstatistics, not raw data. IfFALSE, will be range of raw databefore statistical summary.

Layer layout

Thelayer(layout) argument in context offacet_null() iscompletely ignored.

Examples

# facet_null is the default faceting specification if you# don't override it with facet_grid or facet_wrapggplot(mtcars, aes(mpg, wt)) + geom_point()

Wrap a 1d ribbon of panels into 2d

Description

facet_wrap() wraps a 1d sequence of panels into 2d. This is generallya better use of screen space thanfacet_grid() because mostdisplays are roughly rectangular.

Usage

facet_wrap(  facets,  nrow = NULL,  ncol = NULL,  scales = "fixed",  space = "fixed",  shrink = TRUE,  labeller = "label_value",  as.table = TRUE,  switch = deprecated(),  drop = TRUE,  dir = "h",  strip.position = "top",  axes = "margins",  axis.labels = "all")

Arguments

facets

A set of variables or expressions quoted byvars()and defining faceting groups on the rows or columns dimension.The variables can be named (the names are passed tolabeller).

For compatibility with the classic interface, can also be aformula or character vector. Use either a one sided formula,~a + b,or a character vector,c("a", "b").

nrow,ncol

Number of rows and columns.

scales

Should scales be fixed ("fixed", the default),free ("free"), or free in one dimension ("free_x","free_y")?

space

If"fixed" (default), all panels have the same size andthe number of rows and columns in the layout can be arbitrary. If"free_x", panels have widths proportional to the length of the x-scale,but the layout is constrained to one row. If"free_y", panels haveheights proportional to the length of the y-scale, but the layout isconstrained to one column.

shrink

IfTRUE, will shrink scales to fit output ofstatistics, not raw data. IfFALSE, will be range of raw databefore statistical summary.

labeller

A function that takes one data frame of labels andreturns a list or data frame of character vectors. Each inputcolumn corresponds to one factor. Thus there will be more thanone withvars(cyl, am). Each outputcolumn gets displayed as one separate line in the striplabel. This function should inherit from the "labeller" S3 classfor compatibility withlabeller(). You can use different labelingfunctions for different kind of labels, for example uselabel_parsed() forformatting facet labels.label_value() is used by default,check it for more details and pointers to other options.

as.table

[Superseded] Theas.table argumentis now absorbed into thedir argument via the two letter options.IfTRUE, the facets are laid out like a table with highest values at thebottom-right. IfFALSE, the facets are laid out like a plot with thehighest value at the top-right.

switch

By default, the labels are displayed on the top andright of the plot. If"x", the top labels will bedisplayed to the bottom. If"y", the right-hand sidelabels will be displayed to the left. Can also be set to"both".

drop

IfTRUE, the default, all factor levels not used in thedata will automatically be dropped. IfFALSE, all factor levelswill be shown, regardless of whether or not they appear in the data.

dir

Direction: either"h" for horizontal, the default, or"v",for vertical. When"h" or"v" will be combined withas.table toset final layout. Alternatively, a combination of"t" (top) or"b" (bottom) with"l" (left) or"r" (right) to set a layout directly.These two letters give the starting position and the first letter givesthe growing direction. For example"rt" will place the first panel inthe top-right and starts filling in panels right-to-left.

strip.position

By default, the labels are displayed on the top ofthe plot. Usingstrip.position it is possible to place the labels oneither of the four sides by settingstrip.position = c("top", "bottom", "left", "right")

axes

Determines which axes will be drawn in case of fixed scales.When"margins" (default), axes will be drawn at the exterior margins."all_x" and"all_y" will draw the respective axes at the interiorpanels too, whereas"all" will draw all axes at all panels.

axis.labels

Determines whether to draw labels for interior axes whenthe scale is fixed and theaxis argument is not"margins". When"all" (default), all interior axes get labels. When"margins", onlythe exterior axes get labels, and the interior axes get none. When"all_x" or"all_y", only draws the labels at the interior axes in thex- or y-direction respectively.

Layer layout

Thelayer(layout) argument in context offacet_wrap() can takethe following values:

See Also

Thefacet wrap section of the online ggplot2 book.

Examples

p <- ggplot(mpg, aes(displ, hwy)) + geom_point()# Use vars() to supply faceting variables:p + facet_wrap(vars(class))# Control the number of rows and columns with nrow and ncolp + facet_wrap(vars(class), nrow = 4)# You can facet by multiple variablesggplot(mpg, aes(displ, hwy)) +  geom_point() +  facet_wrap(vars(cyl, drv))# Use the `labeller` option to control how labels are printed:ggplot(mpg, aes(displ, hwy)) +  geom_point() +  facet_wrap(vars(cyl, drv), labeller = "label_both")# To change the order in which the panels appear, change the levels# of the underlying factor.mpg$class2 <- reorder(mpg$class, mpg$displ)ggplot(mpg, aes(displ, hwy)) +  geom_point() +  facet_wrap(vars(class2))# By default, the same scales are used for all panels. You can allow# scales to vary across the panels with the `scales` argument.# Free scales make it easier to see patterns within each panel, but# harder to compare across panels.ggplot(mpg, aes(displ, hwy)) +  geom_point() +  facet_wrap(vars(class), scales = "free")# When scales are constant, duplicated axes can be shown with# or without labelsggplot(mpg, aes(displ, hwy)) +  geom_point() +  facet_wrap(vars(class), axes = "all", axis.labels = "all_y")# To repeat the same data in every panel, simply construct a data frame# that does not contain the faceting variable.ggplot(mpg, aes(displ, hwy)) +  geom_point(data = transform(mpg, class = NULL), colour = "grey85") +  geom_point() +  facet_wrap(vars(class))# Use `strip.position` to display the facet labels at the side of your# choice. Setting it to `bottom` makes it act as a subtitle for the axis.# This is typically used with free scales and a theme without boxes around# strip labels.ggplot(economics_long, aes(date, value)) +  geom_line() +  facet_wrap(vars(variable), scales = "free_y", nrow = 2, strip.position = "top") +  theme(strip.background = element_blank(), strip.placement = "outside")# The two letters determine the starting position, so 'tr' starts# in the top-right.# The first letter determines direction, so 'tr' fills top-to-bottom.# `dir = "tr"` is equivalent to `dir = "v", as.table = FALSE`ggplot(mpg, aes(displ, hwy)) +  geom_point() +  facet_wrap(vars(class), dir = "tr")

2d density estimate of Old Faithful data

Description

A 2d density estimate of the waiting and eruptions variables datafaithful.

Usage

faithfuld

Format

A data frame with 5,625 observations and 3 variables:

eruptions

Eruption time in mins

waiting

Waiting time to next eruption in mins

density

2d density estimate


Modify fill transparency

Description

This works much likealpha() in that it modifies thetransparency of fill colours. It differs in thatfill_alpha() also attemptsto set the transparency of⁠<GridPattern>⁠ objects.

Usage

fill_alpha(fill, alpha)

Arguments

fill

A fill colour given as acharacter orinteger vector, or as a(list of)⁠<GridPattern>⁠ object(s).

alpha

A transparency value between 0 (transparent) and 1 (opaque),parallel tofill.

Value

Acharacter vector of colours, or list of⁠<GridPattern>⁠ objects.

Examples

# Typical colour inputfill_alpha("red", 0.5)if (utils::packageVersion("grid") > "4.2") {  # Pattern input  fill_alpha(list(grid::linearGradient()), 0.5)}

Find panels in a gtable

Description

These functions help detect the placement of panels in a gtable, if they arenamed with "panel" in the beginning.find_panel() returns the extend ofthe panel area, whilepanel_cols() andpanel_rows() returns thecolumns and rows that contains panels respectively.

Usage

find_panel(table)panel_cols(table)panel_rows(table)

Arguments

table

A gtable

Value

A data.frame with some or all of the columns t(op), r(ight),b(ottom), and l(eft)


Fortify a model with data.

Description

Rather than using this function, I now recommend using thebroompackage, which implements a much wider range of methods.fortify()may be deprecated in the future.

Usage

fortify(model, data, ...)

Arguments

model

model or other R object to convert to data frame

data

original dataset, if needed

...

Arguments passed to methods.

See Also

fortify.lm()

Other plotting automation topics:autolayer(),automatic_plotting,autoplot()


Fortify methods for objects produced bymultcomp

Description

[Deprecated]

This function is deprecated because usingbroom::tidy() is a bettersolution to convert model objects.

Usage

## S3 method for class 'glht'fortify(model, data, ...)## S3 method for class 'confint.glht'fortify(model, data, ...)## S3 method for class 'summary.glht'fortify(model, data, ...)## S3 method for class 'cld'fortify(model, data, ...)

Arguments

model

an object of classglht,confint.glht,summary.glht ormultcomp::cld()

data,...

other arguments to the generic ignored in this method.

Examples

amod <- aov(breaks ~ wool + tension, data = warpbreaks)wht <- multcomp::glht(amod, linfct = multcomp::mcp(tension = "Tukey"))tidy(wht) # recommendedfortify(wht)ggplot(tidy(wht), aes(contrast, estimate)) + geom_point()ci <- confint(wht)tidy(ci) # recommendedfortify(ci)ggplot(tidy(confint(wht)),       aes(contrast, estimate, ymin = conf.low, ymax = conf.high)) +   geom_pointrange()smry <- summary(wht)tidy(smry) # recommendedfortify(smry)ggplot(mapping = aes(contrast, estimate)) +   geom_linerange(aes(ymin = conf.low, ymax = conf.high), data = tidy(ci)) +   geom_point(aes(size = adj.p.value), data = tidy(smry)) +   scale_size(transform = "reverse")cld <- multcomp::cld(wht)tidy(cld) # recommendedfortify(cld)

Supplement the data fitted to a linear model with model fit statistics.

Description

[Deprecated]

This method is deprecated because usingbroom::augment() is a bettersolution to supplement data from a linear model.If you have missing values in your model data, you may need to refitthe model withna.action = na.exclude.

Usage

## S3 method for class 'lm'fortify(model, data = model$model, ...)

Arguments

model

linear model

data

data set, defaults to data used to fit model

...

not used by this method

Value

The original data with extra columns:

.hat

Diagonal of the hat matrix

.sigma

Estimate of residual standard deviation whencorresponding observation is dropped from model

.cooksd

Cooks distance,cooks.distance()

.fitted

Fitted values of model

.resid

Residuals

.stdresid

Standardised residuals

Examples

mod <- lm(mpg ~ wt, data = mtcars)# Show augmented modelhead(augment(mod))head(fortify(mod))# Using augment to convert model to ready-to-plot dataggplot(augment(mod), aes(.fitted, .resid)) +  geom_point() +  geom_hline(yintercept = 0) +  geom_smooth(se = FALSE)# Colouring by original data not included in the modelggplot(augment(mod, mtcars), aes(.fitted, .std.resid, colour = factor(cyl))) +  geom_point()

Fortify method for map objects

Description

[Deprecated]

This function turns a map into a data frame that can more easily beplotted with ggplot2.

Usage

## S3 method for class 'map'fortify(model, data, ...)

Arguments

model

map object

data

not used by this method

...

not used by this method

See Also

map_data() andannotation_borders()

Examples

if (require("maps")) {ca <- map("county", "ca", plot = FALSE, fill = TRUE)head(fortify(ca))ggplot(ca, aes(long, lat)) +  geom_polygon(aes(group = group))}if (require("maps")) {tx <- map("county", "texas", plot = FALSE, fill = TRUE)head(fortify(tx))ggplot(tx, aes(long, lat)) +  geom_polygon(aes(group = group), colour = "white")}

Fortify method for classes from the sp package.

Description

[Deprecated]

To figure out the correct variable name for region, inspectas.data.frame(model).

Usage

## S3 method for class 'SpatialPolygonsDataFrame'fortify(model, data, region = NULL, ...)## S3 method for class 'SpatialPolygons'fortify(model, data, ...)## S3 method for class 'Polygons'fortify(model, data, ...)## S3 method for class 'Polygon'fortify(model, data, ...)## S3 method for class 'SpatialLinesDataFrame'fortify(model, data, ...)## S3 method for class 'Lines'fortify(model, data, ...)## S3 method for class 'Line'fortify(model, data, ...)

Arguments

model

SpatialPolygonsDataFrame to convert into a dataframe.

data

not used by this method

region

name of variable used to split up regions

...

not used by this method


Reference lines: horizontal, vertical, and diagonal

Description

These geoms add reference lines (sometimes called rules) to a plot, eitherhorizontal, vertical, or diagonal (specified by slope and intercept).These are useful for annotating plots.

Usage

geom_abline(  mapping = NULL,  data = NULL,  stat = "identity",  ...,  slope,  intercept,  na.rm = FALSE,  show.legend = NA,  inherit.aes = FALSE)geom_hline(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  yintercept,  na.rm = FALSE,  show.legend = NA,  inherit.aes = FALSE)geom_vline(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  xintercept,  na.rm = FALSE,  show.legend = NA,  inherit.aes = FALSE)

Arguments

mapping

Set of aesthetic mappings created byaes().

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

xintercept,yintercept,slope,intercept

Parameters that control theposition of the line. If these are set,data,mapping andshow.legend are overridden.

Details

These geoms act slightly differently from other geoms. You can supply theparameters in two ways: either as arguments to the layer function,or via aesthetics. If you use arguments, e.g.geom_abline(intercept = 0, slope = 1), then behind the scenesthe geom makes a new data frame containing just the data you've supplied.That means that the lines will be the same in all facets; if you want themto vary across facets, construct the data frame yourself and use aesthetics.

Unlike most other geoms, these geoms do not inherit aesthetics from the plotdefault, because they do not understand x and y aesthetics which arecommonly set in the plot. They also do not affect the x and y scales.

Aesthetics

These geoms are drawn usinggeom_line() so they support thesame aesthetics:alpha,colour,linetype andlinewidth. They also each have aesthetics that control the position ofthe line:

See Also

Seegeom_segment() for a more general approach toadding straight line segments to a plot.

Examples

p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()# Fixed valuesp + geom_vline(xintercept = 5)p + geom_vline(xintercept = 1:5)p + geom_hline(yintercept = 20)p + geom_abline() # Can't see it - outside the range of the datap + geom_abline(intercept = 20)# Calculate slope and intercept of line of best fitcoef(lm(mpg ~ wt, data = mtcars))p + geom_abline(intercept = 37, slope = -5)# But this is easier to do with geom_smooth:p + geom_smooth(method = "lm", se = FALSE)# To show different lines in different facets, use aestheticsp <- ggplot(mtcars, aes(mpg, wt)) +  geom_point() +  facet_wrap(~ cyl)mean_wt <- data.frame(cyl = c(4, 6, 8), wt = c(2.28, 3.11, 4.00))p + geom_hline(aes(yintercept = wt), mean_wt)# You can also control other aestheticsggplot(mtcars, aes(mpg, wt, colour = wt)) +  geom_point() +  geom_hline(aes(yintercept = wt, colour = wt), mean_wt) +  facet_wrap(~ cyl)

Bar charts

Description

There are two types of bar charts:geom_bar() andgeom_col().geom_bar() makes the height of the bar proportional to the number ofcases in each group (or if theweight aesthetic is supplied, the sumof the weights). If you want the heights of the bars to represent valuesin the data, usegeom_col() instead.geom_bar() usesstat_count() bydefault: it counts the number of cases at each x position.geom_col()usesstat_identity(): it leaves the data as is.

Usage

geom_bar(  mapping = NULL,  data = NULL,  stat = "count",  position = "stack",  ...,  just = 0.5,  lineend = "butt",  linejoin = "mitre",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_col(  mapping = NULL,  data = NULL,  stat = "identity",  position = "stack",  ...,  just = 0.5,  lineend = "butt",  linejoin = "mitre",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_count(  mapping = NULL,  data = NULL,  geom = "bar",  position = "stack",  ...,  orientation = NA,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

just

Adjustment for column placement. Set to0.5 by default, meaningthat columns will be centered about axis breaks. Set to0 or1 to placecolumns to the left/right of axis breaks. Note that this argument may haveunintended behaviour when used with alternative positions, e.g.position_dodge().

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Override the default connection betweengeom_bar() andstat_count(). For more information about overriding these connections,see how thestat andgeom arguments work.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

Details

A bar chart uses height to represent a value, and so the base of thebar must always be shown to produce a valid visual comparison.Proceed with caution when using transformed scales with a bar chart.It's important to always use a meaningful reference point for the base of the bar.For example, for log transformations the reference point is 1. In fact, whenusing a log scale,geom_bar() automatically places the base of the bar at 1.Furthermore, never use stacked bars with a transformed scale, because scalinghappens before stacking. As a consequence, the height of bars will be wrongwhen stacking occurs with a transformed scale.

By default, multiple bars occupying the samex position will be stackedatop one another byposition_stack(). If you want them to be dodgedside-to-side, useposition_dodge() orposition_dodge2(). Finally,position_fill() shows relative proportions at eachx by stacking thebars and then standardising each bar to have the same height.

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Aesthetics

geom_bar() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
width0.9

geom_col() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
width0.9

stat_count() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

xory
group → inferred
weight1

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

geom_histogram() for continuous data,position_dodge() andposition_dodge2() for creating side-by-sidebar charts.

stat_bin(), which bins data in ranges and counts thecases in each range. It differs fromstat_count(), which counts thenumber of cases at eachx position (without binning into ranges).stat_bin() requires continuousx data, whereasstat_count() can be used for both discrete and continuousx data.

Examples

# geom_bar is designed to make it easy to create bar charts that show# counts (or sums of weights)g <- ggplot(mpg, aes(class))# Number of cars in each class:g + geom_bar()# Total engine displacement of each classg + geom_bar(aes(weight = displ))# Map class to y instead to flip the orientationggplot(mpg) + geom_bar(aes(y = class))# Bar charts are automatically stacked when multiple bars are placed# at the same location. The order of the fill is designed to match# the legendg + geom_bar(aes(fill = drv))# If you need to flip the order (because you've flipped the orientation)# call position_stack() explicitly:ggplot(mpg, aes(y = class)) + geom_bar(aes(fill = drv), position = position_stack(reverse = TRUE)) + theme(legend.position = "top")# To show (e.g.) means, you need geom_col()df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))ggplot(df, aes(trt, outcome)) +  geom_col()# But geom_point() displays exactly the same information and doesn't# require the y-axis to touch zero.ggplot(df, aes(trt, outcome)) +  geom_point()# You can also use geom_bar() with continuous data, in which case# it will show counts at unique locationsdf <- data.frame(x = rep(c(2.9, 3.1, 4.5), c(5, 10, 4)))ggplot(df, aes(x)) + geom_bar()# cf. a histogram of the same dataggplot(df, aes(x)) + geom_histogram(binwidth = 0.5)# Use `just` to control how columns are aligned with axis breaks:df <- data.frame(x = as.Date(c("2020-01-01", "2020-02-01")), y = 1:2)# Columns centered on the first day of the monthggplot(df, aes(x, y)) + geom_col(just = 0.5)# Columns begin on the first day of the monthggplot(df, aes(x, y)) + geom_col(just = 1)

Heatmap of 2d bin counts

Description

Divides the plane into rectangles, counts the number of cases ineach rectangle, and then (by default) maps the number of cases to therectangle's fill. This is a useful alternative togeom_point()in the presence of overplotting.

Usage

geom_bin_2d(  mapping = NULL,  data = NULL,  stat = "bin2d",  position = "identity",  ...,  lineend = "butt",  linejoin = "mitre",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_bin_2d(  mapping = NULL,  data = NULL,  geom = "tile",  position = "identity",  ...,  binwidth = NULL,  bins = 30,  breaks = NULL,  drop = TRUE,  boundary = NULL,  closed = NULL,  center = NULL,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Use to override the default connection betweengeom_bin_2d() andstat_bin_2d(). For more information about overridingthese connections, see how thestat andgeomarguments work.

binwidth

The width of the bins. Can be specified as a numeric valueor as a function that takes x after scale transformation as input andreturns a single numeric value. When specifying a function along with agrouping structure, the function will be called once per group.The default is to use the number of bins inbins,covering the range of the data. You should always overridethis value, exploring multiple widths to find the best to illustrate thestories in your data.

The bin width of a date variable is the number of days in each time; thebin width of a time variable is the number of seconds.

bins

Number of bins. Overridden bybinwidth. Defaults to 30.

breaks

Alternatively, you can supply a numeric vector givingthe bin boundaries. Overridesbinwidth,bins,center,andboundary. Can also be a function that takes group-wise values as input and returns bin boundaries.

drop

ifTRUE removes all cells with 0 counts.

closed

One of"right" or"left" indicating whether rightor left edges of bins are included in the bin.

center,boundary

bin position specifiers. Only one,center orboundary, may be specified for a single plot.center specifies thecenter of one of the bins.boundary specifies the boundary between twobins. Note that if either is above or below the range of the data, thingswill be shifted by the appropriate integer multiple ofbinwidth.For example, to center on integers usebinwidth = 1 andcenter = 0, evenif0 is outside the range of the data. Alternatively, this same alignmentcan be specified withbinwidth = 1 andboundary = 0.5, even if0.5 isoutside the range of the data.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Controlling binning parameters for the x and y directions

The argumentsbins,binwidth,breaks,center, andboundary canbe set separately for the x and y directions. When given as a scalar, onevalue applies to both directions. When given as a vector of length two,the first is applied to the x direction and the second to the y direction.Alternatively, these can be a named list containingx andy elements,for examplelist(x = 10, y = 20).

Aesthetics

geom_bin2d() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
height1
linetype → viatheme()
linewidth → viatheme()
width1

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

stat_bin_hex() for hexagonal binning

Examples

d <- ggplot(diamonds, aes(x, y)) + xlim(4, 10) + ylim(4, 10)d + geom_bin_2d()# You can control the size of the bins by specifying the number of# bins in each direction:d + geom_bin_2d(bins = 10)d + geom_bin_2d(bins = list(x = 30, y = 10))# Or by specifying the width of the binsd + geom_bin_2d(binwidth = c(0.1, 0.1))

Draw nothing

Description

The blank geom draws nothing, but can be a useful way of ensuring commonscales between different plots. Seeexpand_limits() formore details.

Usage

geom_blank(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Examples

ggplot(mtcars, aes(wt, mpg))# Nothing to see here!

A box and whiskers plot (in the style of Tukey)

Description

The boxplot compactly displays the distribution of a continuous variable.It visualises five summary statistics (the median, two hingesand two whiskers), and all "outlying" points individually.

Usage

geom_boxplot(  mapping = NULL,  data = NULL,  stat = "boxplot",  position = "dodge2",  ...,  outliers = TRUE,  outlier.colour = NULL,  outlier.color = NULL,  outlier.fill = NULL,  outlier.shape = NULL,  outlier.size = NULL,  outlier.stroke = 0.5,  outlier.alpha = NULL,  whisker.colour = NULL,  whisker.color = NULL,  whisker.linetype = NULL,  whisker.linewidth = NULL,  staple.colour = NULL,  staple.color = NULL,  staple.linetype = NULL,  staple.linewidth = NULL,  median.colour = NULL,  median.color = NULL,  median.linetype = NULL,  median.linewidth = NULL,  box.colour = NULL,  box.color = NULL,  box.linetype = NULL,  box.linewidth = NULL,  notch = FALSE,  notchwidth = 0.5,  staplewidth = 0,  varwidth = FALSE,  na.rm = FALSE,  orientation = NA,  show.legend = NA,  inherit.aes = TRUE)stat_boxplot(  mapping = NULL,  data = NULL,  geom = "boxplot",  position = "dodge2",  ...,  orientation = NA,  coef = 1.5,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

outliers

Whether to display (TRUE) or discard (FALSE) outliersfrom the plot. Hiding or discarding outliers can be useful when, forexample, raw data points need to be displayed on top of the boxplot.By discarding outliers, the axis limits will adapt to the box and whiskersonly, not the full data range. If outliers need to be hidden and the axesneeds to show the full data range, please useoutlier.shape = NA instead.

outlier.colour,outlier.color,outlier.fill,outlier.shape,outlier.size,outlier.stroke,outlier.alpha

Default aesthetics for outliers. Set toNULL to inherit from thedata's aesthetics.

whisker.colour,whisker.color,whisker.linetype,whisker.linewidth

Default aesthetics for the whiskers. Set toNULL to inherit from thedata's aesthetics.

staple.colour,staple.color,staple.linetype,staple.linewidth

Default aesthetics for the staples. Set toNULL to inherit from thedata's aesthetics. Note that staples don't appear unless thestaplewidthargument is set to a non-zero size.

median.colour,median.color,median.linetype,median.linewidth

Default aesthetics for the median line. Set toNULL to inherit from thedata's aesthetics.

box.colour,box.color,box.linetype,box.linewidth

Default aesthetics for the boxes. Set toNULL to inherit from thedata's aesthetics.

notch

IfFALSE (default) make a standard box plot. IfTRUE, make a notched box plot. Notches are used to compare groups;if the notches of two boxes do not overlap, this suggests that the mediansare significantly different.

notchwidth

For a notched box plot, width of the notch relative tothe body (defaults tonotchwidth = 0.5).

staplewidth

The relative width of staples to the width of the box.Staples mark the ends of the whiskers with a line.

varwidth

IfFALSE (default) make a standard box plot. IfTRUE, boxes are drawn with widths proportional to thesquare-roots of the number of observations in the groups (possiblyweighted, using theweight aesthetic).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Use to override the default connection betweengeom_boxplot() andstat_boxplot(). For more information aboutoverriding these connections, see how thestat andgeom arguments work.

coef

Length of the whiskers as multiple of IQR. Defaults to 1.5.

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Summary statistics

The lower and upper hinges correspond to the first and third quartiles(the 25th and 75th percentiles). This differs slightly from the method usedby theboxplot() function, and may be apparent with small samples.Seeboxplot.stats() for more information on how hingepositions are calculated forboxplot().

The upper whisker extends from the hinge to the largest value no further than1.5 * IQR from the hinge (where IQR is the inter-quartile range, or distancebetween the first and third quartiles). The lower whisker extends from thehinge to the smallest value at most 1.5 * IQR of the hinge. Data beyond theend of the whiskers are called "outlying" points and are plottedindividually.

In a notched box plot, the notches extend1.58 * IQR / sqrt(n).This gives a roughly 95% confidence interval for comparing medians.See McGill et al. (1978) for more details.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.stat_boxplot() provides the following variables, some of which depend on the orientation:

Aesthetics

geom_boxplot() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

xory
lowerorxlower
upperorxupper
middleorxmiddle
yminorxmin
ymaxorxmax
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
shape → viatheme()
size → viatheme()
weight1
width0.9

Learn more about setting these aesthetics invignette("ggplot2-specs").

Note

In the unlikely event you specify both US and UK spellings of colour,the US spelling will take precedence.

References

McGill, R., Tukey, J. W. and Larsen, W. A. (1978) Variations ofbox plots. The American Statistician 32, 12-16.

See Also

geom_quantile() for continuousx,geom_violin() for a richer display of the distribution, andgeom_jitter() for a useful technique for small data.

Examples

p <- ggplot(mpg, aes(class, hwy))p + geom_boxplot()# Orientation follows the discrete axisggplot(mpg, aes(hwy, class)) + geom_boxplot()p + geom_boxplot(notch = TRUE)p + geom_boxplot(varwidth = TRUE)p + geom_boxplot(fill = "white", colour = "#3366FF")# By default, outlier points match the colour of the box. Use# outlier.colour to overridep + geom_boxplot(outlier.colour = "red", outlier.shape = 1)# Remove outliers when overlaying boxplot with original data pointsp + geom_boxplot(outlier.shape = NA) + geom_jitter(width = 0.2)# Boxplots are automatically dodged when any aesthetic is a factorp + geom_boxplot(aes(colour = drv))# You can also use boxplots with continuous x, as long as you supply# a grouping variable. cut_width is particularly usefulggplot(diamonds, aes(carat, price)) +  geom_boxplot()ggplot(diamonds, aes(carat, price)) +  geom_boxplot(aes(group = cut_width(carat, 0.25)))# Adjust the transparency of outliers using outlier.alphaggplot(diamonds, aes(carat, price)) +  geom_boxplot(aes(group = cut_width(carat, 0.25)), outlier.alpha = 0.1)# It's possible to draw a boxplot with your own computations if you# use stat = "identity":set.seed(1)y <- rnorm(100)df <- data.frame(  x = 1,  y0 = min(y),  y25 = quantile(y, 0.25),  y50 = median(y),  y75 = quantile(y, 0.75),  y100 = max(y))ggplot(df, aes(x)) +  geom_boxplot(   aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),   stat = "identity" )

2D contours of a 3D surface

Description

ggplot2 can not draw true 3D surfaces, but you can usegeom_contour(),geom_contour_filled(), andgeom_tile() to visualise 3D surfaces in 2D.

These functions require regular data, where thex andy coordinatesform an equally spaced grid, and each combination ofx andy appearsonce. Missing values ofz are allowed, but contouring will only work forgrid points where all four corners are non-missing. If you have irregulardata, you'll need to first interpolate on to a grid before visualising,usinginterp::interp(),akima::bilinear(), or similar.

Usage

geom_contour(  mapping = NULL,  data = NULL,  stat = "contour",  position = "identity",  ...,  bins = NULL,  binwidth = NULL,  breaks = NULL,  arrow = NULL,  arrow.fill = NULL,  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_contour_filled(  mapping = NULL,  data = NULL,  stat = "contour_filled",  position = "identity",  ...,  bins = NULL,  binwidth = NULL,  breaks = NULL,  rule = "evenodd",  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_contour(  mapping = NULL,  data = NULL,  geom = "contour",  position = "identity",  ...,  bins = NULL,  binwidth = NULL,  breaks = NULL,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_contour_filled(  mapping = NULL,  data = NULL,  geom = "contour_filled",  position = "identity",  ...,  bins = NULL,  binwidth = NULL,  breaks = NULL,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

bins

Number of contour bins. Overridden bybreaks.

binwidth

The width of the contour bins. Overridden bybins.

breaks

One of:

  • Numeric vector to set the contour breaks

  • A function that takes the range of the data and binwidth as inputand returns breaks as output. A function can be created from a formula(e.g. ~ fullseq(.x, .y)).

Overridesbinwidth andbins. By default, this is a vector of lengthten withpretty() breaks.

arrow

Arrow specification, as created bygrid::arrow().

arrow.fill

fill colour to use for the arrow head (if closed).NULLmeans usecolour aesthetic.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

rule

Either"evenodd" or"winding". If polygons with holes arebeing drawn (using thesubgroup aesthetic) this argument defines how thehole coordinates are interpreted. See the examples ingrid::pathGrob() foran explanation.

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation. The computed variables differ somewhat for contour lines (computed bystat_contour()) and contour bands (filled contours, computed bystat_contour_filled()). The variablesnlevel andpiece are available for both, whereaslevel_low,level_high, andlevel_mid are only available for bands. The variablelevel is a numeric or a factor depending on whether lines or bands are calculated.

Dropped variables

z

After contouring, the z values of individual data points are no longer available.

Aesthetics

geom_contour() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
weight1

geom_contour_filled() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
subgroupNULL

stat_contour() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
z
group → inferred
orderafter_stat(level)

stat_contour_filled() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
z
fillafter_stat(level)
group → inferred
orderafter_stat(level)

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

geom_density_2d(): 2d density contours

Examples

# Basic plotv <- ggplot(faithfuld, aes(waiting, eruptions, z = density))v + geom_contour()# Or compute from raw dataggplot(faithful, aes(waiting, eruptions)) +  geom_density_2d()# use geom_contour_filled() for filled contoursv + geom_contour_filled()# Setting bins creates evenly spaced contours in the range of the datav + geom_contour(bins = 3)v + geom_contour(bins = 5)# Setting binwidth does the same thing, parameterised by the distance# between contoursv + geom_contour(binwidth = 0.01)v + geom_contour(binwidth = 0.001)# Other parametersv + geom_contour(aes(colour = after_stat(level)))v + geom_contour(colour = "red")v + geom_raster(aes(fill = density)) +  geom_contour(colour = "white")

Count overlapping points

Description

This is a variant ofgeom_point() that counts the number ofobservations at each location, then maps the count to point area. Ituseful when you have discrete data and overplotting.

Usage

geom_count(  mapping = NULL,  data = NULL,  stat = "sum",  position = "identity",  ...,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_sum(  mapping = NULL,  data = NULL,  geom = "point",  position = "identity",  ...,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Use to override the default connection betweengeom_count() andstat_sum(). For more information about overridingthese connections, see how thestat andgeomarguments work.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Aesthetics

geom_point() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
shape → viatheme()
size → viatheme()
stroke → viatheme()

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

For continuousx andy, usegeom_bin_2d().

Examples

ggplot(mpg, aes(cty, hwy)) + geom_point()ggplot(mpg, aes(cty, hwy)) + geom_count()# Best used in conjunction with scale_size_area which ensures that# counts of zero would be given size 0. Doesn't make much different# here because the smallest count is already close to 0.ggplot(mpg, aes(cty, hwy)) + geom_count() + scale_size_area()# Display proportions instead of counts -------------------------------------# By default, all categorical variables in the plot form the groups.# Specifying geom_count without a group identifier leads to a plot which is# not useful:d <- ggplot(diamonds, aes(x = cut, y = clarity))d + geom_count(aes(size = after_stat(prop)))# To correct this problem and achieve a more desirable plot, we need# to specify which group the proportion is to be calculated over.d + geom_count(aes(size = after_stat(prop), group = 1)) +  scale_size_area(max_size = 10)# Or group by x/y variables to have rows/columns sum to 1.d + geom_count(aes(size = after_stat(prop), group = cut)) +  scale_size_area(max_size = 10)d + geom_count(aes(size = after_stat(prop), group = clarity)) +  scale_size_area(max_size = 10)

Vertical intervals: lines, crossbars & errorbars

Description

Various ways of representing a vertical interval defined byx,ymin andymax. Each case draws a single graphical object.

Usage

geom_crossbar(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  middle.colour = NULL,  middle.color = NULL,  middle.linetype = NULL,  middle.linewidth = NULL,  box.colour = NULL,  box.color = NULL,  box.linetype = NULL,  box.linewidth = NULL,  fatten = deprecated(),  na.rm = FALSE,  orientation = NA,  show.legend = NA,  inherit.aes = TRUE)geom_errorbar(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  orientation = NA,  lineend = "butt",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_errorbarh(..., orientation = "y")geom_linerange(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  orientation = NA,  lineend = "butt",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_pointrange(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  orientation = NA,  fatten = deprecated(),  lineend = "butt",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

middle.colour,middle.color,middle.linetype,middle.linewidth

Default aesthetics for the middle line. Set toNULL to inherit from thedata's aesthetics.

box.colour,box.color,box.linetype,box.linewidth

Default aesthetics for the boxes. Set toNULL to inherit from thedata's aesthetics.

fatten

[Deprecated] A multiplicative factorused to increase the size of the middle bar ingeom_crossbar() and themiddle point ingeom_pointrange().

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

lineend

Line end style (round, butt, square).

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Aesthetics

geom_linerange() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

xory
yminorxmin
ymaxorxmax
alphaNA
colour → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()

Note thatgeom_pointrange() also understandssize for the size of the points.

Learn more about setting these aesthetics invignette("ggplot2-specs").

Note

geom_errorbarh() is[Deprecated]. Usegeom_errorbar(orientation = "y") instead.

See Also

stat_summary() for examples of these guys in use,geom_smooth() for continuous analogue

Examples

# Create a simple example datasetdf <- data.frame(  trt = factor(c(1, 1, 2, 2)),  resp = c(1, 5, 3, 4),  group = factor(c(1, 2, 1, 2)),  upper = c(1.1, 5.3, 3.3, 4.2),  lower = c(0.8, 4.6, 2.4, 3.6))p <- ggplot(df, aes(trt, resp, colour = group))p + geom_linerange(aes(ymin = lower, ymax = upper))p + geom_pointrange(aes(ymin = lower, ymax = upper))p + geom_crossbar(aes(ymin = lower, ymax = upper), width = 0.2)p + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2)# Flip the orientation by changing mappingggplot(df, aes(resp, trt, colour = group)) +  geom_linerange(aes(xmin = lower, xmax = upper))# Draw lines connecting group meansp +  geom_line(aes(group = group)) +  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2)# If you want to dodge bars and errorbars, you need to manually# specify the dodge widthp <- ggplot(df, aes(trt, resp, fill = group))p + geom_col(position = "dodge") + geom_errorbar(aes(ymin = lower, ymax = upper), position = "dodge", width = 0.25)# Because the bars and errorbars have different widths# we need to specify how wide the objects we are dodging aredodge <- position_dodge(width=0.9)p +  geom_col(position = dodge) +  geom_errorbar(aes(ymin = lower, ymax = upper), position = dodge, width = 0.25)# When using geom_errorbar() with position_dodge2(), extra padding will be# needed between the error bars to keep them aligned with the bars.p +geom_col(position = "dodge2") +geom_errorbar(  aes(ymin = lower, ymax = upper),  position = position_dodge2(width = 0.5, padding = 0.5))

Smoothed density estimates

Description

Computes and draws kernel density estimate, which is a smoothed version ofthe histogram. This is a useful alternative to the histogram for continuousdata that comes from an underlying smooth distribution.

Usage

geom_density(  mapping = NULL,  data = NULL,  stat = "density",  position = "identity",  ...,  outline.type = "upper",  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_density(  mapping = NULL,  data = NULL,  geom = "area",  position = "stack",  ...,  orientation = NA,  bw = "nrd0",  adjust = 1,  kernel = "gaussian",  n = 512,  trim = FALSE,  bounds = c(-Inf, Inf),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

outline.type

Type of the outline of the area;"both" draws both theupper and lower lines,"upper"/"lower" draws the respective lines only."full" draws a closed polygon around the area.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Use to override the default connection betweengeom_density() andstat_density(). For more information aboutoverriding these connections, see how thestat andgeom arguments work.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

bw

The smoothing bandwidth to be used.If numeric, the standard deviation of the smoothing kernel.If character, a rule to choose the bandwidth, as listed instats::bw.nrd(). Note that automatic calculation of the bandwidth doesnot take weights into account.

adjust

A multiplicate bandwidth adjustment. This makes it possibleto adjust the bandwidth while still using the a bandwidth estimator.For example,adjust = 1/2 means use half of the default bandwidth.

kernel

Kernel. See list of available kernels indensity().

n

number of equally spaced points at which the density is to beestimated, should be a power of two, seedensity() fordetails

trim

IfFALSE, the default, each density is computed on thefull range of the data. IfTRUE, each density is computed over therange of that group: this typically means the estimated x values willnot line-up, and hence you won't be able to stack density values.This parameter only matters if you are displaying multiple densities inone plot or if you are manually adjusting the scale limits.

bounds

Known lower and upper bounds for estimated data. Defaultc(-Inf, Inf) means that there are no (finite) bounds. If any bound isfinite, boundary effect of default density estimation will be corrected byreflecting tails outsidebounds around their closest edge. Data pointsoutside of bounds are removed with a warning.

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Aesthetics

geom_density() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
weight1

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

Seegeom_histogram(),geom_freqpoly() forother methods of displaying continuous distribution.Seegeom_violin() for a compact density display.

Examples

ggplot(diamonds, aes(carat)) +  geom_density()# Map the values to y to flip the orientationggplot(diamonds, aes(y = carat)) +  geom_density()ggplot(diamonds, aes(carat)) +  geom_density(adjust = 1/5)ggplot(diamonds, aes(carat)) +  geom_density(adjust = 5)ggplot(diamonds, aes(depth, colour = cut)) +  geom_density() +  xlim(55, 70)ggplot(diamonds, aes(depth, fill = cut, colour = cut)) +  geom_density(alpha = 0.1) +  xlim(55, 70)# Use `bounds` to adjust computation for known data limitsbig_diamonds <- diamonds[diamonds$carat >= 1, ]ggplot(big_diamonds, aes(carat)) +  geom_density(color = 'red') +  geom_density(bounds = c(1, Inf), color = 'blue')# Stacked density plots: if you want to create a stacked density plot, you# probably want to 'count' (density * n) variable instead of the default# density# Loses marginal densitiesggplot(diamonds, aes(carat, fill = cut)) +  geom_density(position = "stack")# Preserves marginal densitiesggplot(diamonds, aes(carat, after_stat(count), fill = cut)) +  geom_density(position = "stack")# You can use position="fill" to produce a conditional density estimateggplot(diamonds, aes(carat, after_stat(count), fill = cut)) +  geom_density(position = "fill")

Contours of a 2D density estimate

Description

Perform a 2D kernel density estimation usingMASS::kde2d() anddisplay the results with contours. This can be useful for dealing withoverplotting. This is a 2D version ofgeom_density().geom_density_2d()draws contour lines, andgeom_density_2d_filled() draws filled contourbands.

Usage

geom_density_2d(  mapping = NULL,  data = NULL,  stat = "density_2d",  position = "identity",  ...,  contour_var = "density",  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_density_2d_filled(  mapping = NULL,  data = NULL,  stat = "density_2d_filled",  position = "identity",  ...,  contour_var = "density",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_density_2d(  mapping = NULL,  data = NULL,  geom = "density_2d",  position = "identity",  ...,  contour = TRUE,  contour_var = "density",  h = NULL,  adjust = c(1, 1),  n = 100,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_density_2d_filled(  mapping = NULL,  data = NULL,  geom = "density_2d_filled",  position = "identity",  ...,  contour = TRUE,  contour_var = "density",  h = NULL,  adjust = c(1, 1),  n = 100,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Arguments passed on togeom_contour

binwidth

The width of the contour bins. Overridden bybins.

bins

Number of contour bins. Overridden bybreaks.

breaks

One of:

  • Numeric vector to set the contour breaks

  • A function that takes the range of the data and binwidth as inputand returns breaks as output. A function can be created from a formula(e.g. ~ fullseq(.x, .y)).

Overridesbinwidth andbins. By default, this is a vector of lengthten withpretty() breaks.

contour_var

Character string identifying the variable to contourby. Can be one of"density","ndensity", or"count". See the sectionon computed variables for details.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Use to override the default connection betweengeom_density_2d() andstat_density_2d(). For more information atoverriding these connections, see how thestat andgeom arguments work.

contour

IfTRUE, contour the results of the 2d densityestimation.

h

Bandwidth (vector of length two). IfNULL, estimatedusingMASS::bandwidth.nrd().

adjust

A multiplicative bandwidth adjustment to be used if 'h' is'NULL'. This makes it possible to adjust the bandwidth while stillusing the a bandwidth estimator. For example,adjust = 1/2 meansuse half of the default bandwidth.

n

Number of grid points in each direction.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.stat_density_2d() andstat_density_2d_filled() compute different variables depending on whether contouring is turned on or off. With contouring off (contour = FALSE), both stats behave the same, and the following variables are provided:

With contouring on (contour = TRUE), eitherstat_contour() orstat_contour_filled() (for contour lines or contour bands,respectively) is run after the density estimate has been obtained,and the computed variables are determined by these stats.Contours are calculated for one of the three types of density estimatesobtained before contouring,density,ndensity, andcount. Whichof those should be used is determined by thecontour_var parameter.

Dropped variables

z

After density estimation, the z values of individual data points are no longer available.

If contouring is enabled, then similarlydensity,ndensity, andcountare no longer available after the contouring pass.

Aesthetics

geom_density2d() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()

geom_density2d_filled() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
subgroupNULL

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

geom_contour(),geom_contour_filled() for information abouthow contours are drawn;geom_bin_2d() for another way of dealing withoverplotting.

Examples

m <- ggplot(faithful, aes(x = eruptions, y = waiting)) + geom_point() + xlim(0.5, 6) + ylim(40, 110)# contour linesm + geom_density_2d()# contour bandsm + geom_density_2d_filled(alpha = 0.5)# contour bands and contour linesm + geom_density_2d_filled(alpha = 0.5) +  geom_density_2d(linewidth = 0.25, colour = "black")set.seed(4393)dsmall <- diamonds[sample(nrow(diamonds), 1000), ]d <- ggplot(dsmall, aes(x, y))# If you map an aesthetic to a categorical variable, you will get a# set of contours for each value of that variabled + geom_density_2d(aes(colour = cut))# If you draw filled contours across multiple facets, the same bins are# used across all facetsd + geom_density_2d_filled() + facet_wrap(vars(cut))# If you want to make sure the peak intensity is the same in each facet,# use `contour_var = "ndensity"`.d + geom_density_2d_filled(contour_var = "ndensity") + facet_wrap(vars(cut))# If you want to scale intensity by the number of observations in each group,# use `contour_var = "count"`.d + geom_density_2d_filled(contour_var = "count") + facet_wrap(vars(cut))# If we turn contouring off, we can use other geoms, such as tiles:d + stat_density_2d(  geom = "raster",  aes(fill = after_stat(density)),  contour = FALSE) + scale_fill_viridis_c()# Or points:d + stat_density_2d(geom = "point", aes(size = after_stat(density)), n = 20, contour = FALSE)

Dot plot

Description

In a dot plot, the width of a dot corresponds to the bin width(or maximum width, depending on the binning algorithm), and dots arestacked, with each dot representing one observation.

Usage

geom_dotplot(  mapping = NULL,  data = NULL,  position = "identity",  ...,  binwidth = NULL,  binaxis = "x",  method = "dotdensity",  binpositions = "bygroup",  stackdir = "up",  stackratio = 1,  dotsize = 1,  stackgroups = FALSE,  origin = NULL,  right = TRUE,  width = 0.9,  drop = FALSE,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

binwidth

Whenmethod is "dotdensity", this specifies maximum binwidth. Whenmethod is "histodot", this specifies bin width.Defaults to 1/30 of the range of the data

binaxis

The axis to bin along, "x" (default) or "y"

method

"dotdensity" (default) for dot-density binning, or"histodot" for fixed bin widths (like stat_bin)

binpositions

Whenmethod is "dotdensity", "bygroup" (default)determines positions of the bins for each group separately. "all" determinespositions of the bins with all the data taken together; this is used foraligning dot stacks across multiple groups.

stackdir

which direction to stack the dots. "up" (default),"down", "center", "centerwhole" (centered, but with dots aligned)

stackratio

how close to stack the dots. Default is 1, where dotsjust touch. Use smaller values for closer, overlapping dots.

dotsize

The diameter of the dots relative tobinwidth, default 1.

stackgroups

should dots be stacked across groups? This has the effectthatposition = "stack" should have, but can't (because this geom hassome odd properties).

origin

Whenmethod is "histodot", origin of first bin

right

Whenmethod is "histodot", should intervals be closedon the right (a, b], or not [a, b)

width

Whenbinaxis is "y", the spacing of the dot stacksfor dodging.

drop

If TRUE, remove all bins with zero counts

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Details

There are two basic approaches:dot-density andhistodot.With dot-density binning, the bin positions are determined by the data andbinwidth, which is the maximum width of each bin. See Wilkinson(1999) for details on the dot-density binning algorithm. With histodotbinning, the bins have fixed positions and fixed widths, much like ahistogram.

When binning along the x axis and stacking along the y axis, the numbers ony axis are not meaningful, due to technical limitations of ggplot2. You canhide the y axis, as in one of the examples, or manually scale itto match the number of dots.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Aesthetics

geom_dotplot() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
stroke → viatheme()
weight1
width0.9

Learn more about setting these aesthetics invignette("ggplot2-specs").

References

Wilkinson, L. (1999) Dot plots. The American Statistician,53(3), 276-281.

Examples

ggplot(mtcars, aes(x = mpg)) +  geom_dotplot()ggplot(mtcars, aes(x = mpg)) +  geom_dotplot(binwidth = 1.5)# Use fixed-width binsggplot(mtcars, aes(x = mpg)) +  geom_dotplot(method="histodot", binwidth = 1.5)# Some other stacking methodsggplot(mtcars, aes(x = mpg)) +  geom_dotplot(binwidth = 1.5, stackdir = "center")ggplot(mtcars, aes(x = mpg)) +  geom_dotplot(binwidth = 1.5, stackdir = "centerwhole")# y axis isn't really meaningful, so hide itggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5) +  scale_y_continuous(NULL, breaks = NULL)# Overlap dots verticallyggplot(mtcars, aes(x = mpg)) +  geom_dotplot(binwidth = 1.5, stackratio = .7)# Expand dot diameterggplot(mtcars, aes(x = mpg)) +  geom_dotplot(binwidth = 1.5, dotsize = 1.25)# Change dot fill colour, stroke widthggplot(mtcars, aes(x = mpg)) +  geom_dotplot(binwidth = 1.5, fill = "white", stroke = 2)# Examples with stacking along y axis instead of xggplot(mtcars, aes(x = 1, y = mpg)) +  geom_dotplot(binaxis = "y", stackdir = "center")ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +  geom_dotplot(binaxis = "y", stackdir = "center")ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +  geom_dotplot(binaxis = "y", stackdir = "centerwhole")ggplot(mtcars, aes(x = factor(vs), fill = factor(cyl), y = mpg)) +  geom_dotplot(binaxis = "y", stackdir = "center", position = "dodge")# binpositions="all" ensures that the bins are aligned between groupsggplot(mtcars, aes(x = factor(am), y = mpg)) +  geom_dotplot(binaxis = "y", stackdir = "center", binpositions="all")# Stacking multiple groups, with different fillggplot(mtcars, aes(x = mpg, fill = factor(cyl))) +  geom_dotplot(stackgroups = TRUE, binwidth = 1, binpositions = "all")ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) +  geom_dotplot(stackgroups = TRUE, binwidth = 1, method = "histodot")ggplot(mtcars, aes(x = 1, y = mpg, fill = factor(cyl))) +  geom_dotplot(binaxis = "y", stackgroups = TRUE, binwidth = 1, method = "histodot")

Histograms and frequency polygons

Description

Visualise the distribution of a single continuous variable by dividingthe x axis into bins and counting the number of observations in each bin.Histograms (geom_histogram()) display the counts with bars; frequencypolygons (geom_freqpoly()) display the counts with lines. Frequencypolygons are more suitable when you want to compare the distributionacross the levels of a categorical variable.

Usage

geom_freqpoly(  mapping = NULL,  data = NULL,  stat = "bin",  position = "identity",  ...,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_histogram(  mapping = NULL,  data = NULL,  stat = "bin",  position = "stack",  ...,  binwidth = NULL,  bins = NULL,  orientation = NA,  lineend = "butt",  linejoin = "mitre",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_bin(  mapping = NULL,  data = NULL,  geom = "bar",  position = "stack",  ...,  orientation = NA,  binwidth = NULL,  bins = NULL,  center = NULL,  boundary = NULL,  closed = c("right", "left"),  pad = FALSE,  breaks = NULL,  drop = "none",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

binwidth

The width of the bins. Can be specified as a numeric valueor as a function that takes x after scale transformation as input andreturns a single numeric value. When specifying a function along with agrouping structure, the function will be called once per group.The default is to use the number of bins inbins,covering the range of the data. You should always overridethis value, exploring multiple widths to find the best to illustrate thestories in your data.

The bin width of a date variable is the number of days in each time; thebin width of a time variable is the number of seconds.

bins

Number of bins. Overridden bybinwidth. Defaults to 30.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

geom,stat

Use to override the default connection betweengeom_histogram()/geom_freqpoly() andstat_bin(). For more informationat overriding these connections, see how thestat andgeom arguments work.

center,boundary

bin position specifiers. Only one,center orboundary, may be specified for a single plot.center specifies thecenter of one of the bins.boundary specifies the boundary between twobins. Note that if either is above or below the range of the data, thingswill be shifted by the appropriate integer multiple ofbinwidth.For example, to center on integers usebinwidth = 1 andcenter = 0, evenif0 is outside the range of the data. Alternatively, this same alignmentcan be specified withbinwidth = 1 andboundary = 0.5, even if0.5 isoutside the range of the data.

closed

One of"right" or"left" indicating whether rightor left edges of bins are included in the bin.

pad

IfTRUE, adds empty bins at either end of x. This ensuresfrequency polygons touch 0. Defaults toFALSE.

breaks

Alternatively, you can supply a numeric vector givingthe bin boundaries. Overridesbinwidth,bins,center,andboundary. Can also be a function that takes group-wise values as input and returns bin boundaries.

drop

Treatment of zero count bins. If"none" (default), suchbins are kept as-is. If"all", all zero count bins are filtered out.If"extremes" only zero count bins at the flanks are filtered out, butnot in the middle.TRUE is shorthand for"all" andFALSE is shorthandfor"none".

Details

stat_bin() is suitable only for continuous x data. If your x data isdiscrete, you probably want to usestat_count().

By default, the underlying computation (stat_bin()) uses 30 bins;this is not a good default, but the idea is to get you experimenting withdifferent number of bins. You can also experiment modifying thebinwidth withcenter orboundary arguments.binwidth overridesbins so you should doone change at a time. You may need to look at a few options to uncoverthe full story behind your data.

By default, theheight of the bars represent the counts within each bin.However, there are situations where this behavior might produce misleadingplots (e.g., when non-equal-width bins are used), in which case it might bepreferable to have thearea of the bars represent the counts (by settingaes(y = after_stat(count / width))). See example below.

In addition togeom_histogram(), you can create a histogram plot by usingscale_x_binned() withgeom_bar(). This method by default plots tick marksin between each bar.

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Aesthetics

geom_histogram() uses the same aesthetics asgeom_bar();geom_freqpoly() uses the same aesthetics asgeom_line().

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Dropped variables

weight

After binning, weights of individual data points (if supplied) are no longer available.

See Also

stat_count(), which counts the number of cases at each xposition, without binning. It is suitable for both discrete and continuousx data, whereasstat_bin() is suitable only for continuous x data.

Examples

ggplot(diamonds, aes(carat)) +  geom_histogram()ggplot(diamonds, aes(carat)) +  geom_histogram(binwidth = 0.01)ggplot(diamonds, aes(carat)) +  geom_histogram(bins = 200)# Map values to y to flip the orientationggplot(diamonds, aes(y = carat)) +  geom_histogram()# For histograms with tick marks between each bin, use `geom_bar()` with# `scale_x_binned()`.ggplot(diamonds, aes(carat)) +  geom_bar() +  scale_x_binned()# Rather than stacking histograms, it's easier to compare frequency# polygonsggplot(diamonds, aes(price, fill = cut)) +  geom_histogram(binwidth = 500)ggplot(diamonds, aes(price, colour = cut)) +  geom_freqpoly(binwidth = 500)# To make it easier to compare distributions with very different counts,# put density on the y axis instead of the default countggplot(diamonds, aes(price, after_stat(density), colour = cut)) +  geom_freqpoly(binwidth = 500)# When using the non-equal-width bins, we should set the area of the bars to# represent the counts (not the height).# Here we're using 10 equi-probable bins:price_bins <- quantile(diamonds$price, probs = seq(0, 1, length = 11))ggplot(diamonds, aes(price)) +  geom_histogram(breaks = price_bins, color = "black") # misleading (height = count)ggplot(diamonds, aes(price, after_stat(count / width))) +  geom_histogram(breaks = price_bins, color = "black") # area = countif (require("ggplot2movies")) {# Often we don't want the height of the bar to represent the# count of observations, but the sum of some other variable.# For example, the following plot shows the number of movies# in each rating.m <- ggplot(movies, aes(rating))m + geom_histogram(binwidth = 0.1)# If, however, we want to see the number of votes cast in each# category, we need to weight by the votes variablem +  geom_histogram(aes(weight = votes), binwidth = 0.1) +  ylab("votes")# For transformed scales, binwidth applies to the transformed data.# The bins have constant width on the transformed scale.m + geom_histogram() + scale_x_log10()m +  geom_histogram(binwidth = 0.05) +  scale_x_log10()# For transformed coordinate systems, the binwidth applies to the# raw data. The bins have constant width on the original scale.# Using log scales does not work here, because the first# bar is anchored at zero, and so when transformed becomes negative# infinity. This is not a problem when transforming the scales, because# no observations have 0 ratings.m +  geom_histogram(boundary = 0) +  coord_transform(x = "log10")# Use boundary = 0, to make sure we don't take sqrt of negative valuesm +  geom_histogram(boundary = 0) +  coord_transform(x = "sqrt")# You can also transform the y axis.  Remember that the base of the bars# has value 0, so log transformations are not appropriatem <- ggplot(movies, aes(x = rating))m +  geom_histogram(binwidth = 0.5) +  scale_y_sqrt()}# You can specify a function for calculating binwidth, which is# particularly useful when faceting along variables with# different ranges because the function will be called once per facetggplot(economics_long, aes(value)) +  facet_wrap(~variable, scales = 'free_x') +  geom_histogram(binwidth = \(x) 2 * IQR(x) / (length(x)^(1/3)))

Draw a function as a continuous curve

Description

Computes and draws a function as a continuous curve. This makes it easy tosuperimpose a function on top of an existing plot. The function is calledwith a grid of evenly spaced values along the x axis, and the results aredrawn (by default) with a line.

Usage

geom_function(  mapping = NULL,  data = NULL,  stat = "function",  position = "identity",  ...,  arrow = NULL,  arrow.fill = NULL,  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_function(  mapping = NULL,  data = NULL,  geom = "function",  position = "identity",  ...,  fun,  xlim = NULL,  n = 101,  args = list(),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

Ignored bystat_function(), do not use.

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

arrow

Arrow specification, as created bygrid::arrow().

arrow.fill

fill colour to use for the arrow head (if closed).NULLmeans usecolour aesthetic.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

fun

Function to use. Either 1) an anonymous function in the base orrlang formula syntax (seerlang::as_function())or 2) a quoted or character name referencing a function; see examples. Mustbe vectorised.

xlim

Optionally, specify the range of the function.

n

Number of points to interpolate along the x axis.

args

List of additional arguments passed on to the function defined byfun.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Aesthetics

geom_function() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

rlang::as_function()

Examples

# geom_function() is useful for overlaying functionsset.seed(1492)ggplot(data.frame(x = rnorm(100)), aes(x)) +  geom_density() +  geom_function(fun = dnorm, colour = "red")# To plot functions without data, specify range of x-axisbase <-  ggplot() +  xlim(-5, 5)base + geom_function(fun = dnorm)base + geom_function(fun = dnorm, args = list(mean = 2, sd = .5))# The underlying mechanics evaluate the function at discrete points# and connect the points with linesbase + stat_function(fun = dnorm, geom = "point")base + stat_function(fun = dnorm, geom = "point", n = 20)base + stat_function(fun = dnorm, geom = "polygon", color = "blue", fill = "blue", alpha = 0.5)base + geom_function(fun = dnorm, n = 20)# Two functions on the same plotbase +  geom_function(aes(colour = "normal"), fun = dnorm) +  geom_function(aes(colour = "t, df = 1"), fun = dt, args = list(df = 1))# Using a custom anonymous functionbase + geom_function(fun = \(x) 0.5 * exp(-abs(x)))# or using lambda syntax:# base + geom_function(fun = ~ 0.5 * exp(-abs(.x)))# or using a custom named function:# f <- function(x) 0.5 * exp(-abs(x))# base + geom_function(fun = f)# Using xlim to restrict the range of functionggplot(data.frame(x = rnorm(100)), aes(x)) +geom_density() +geom_function(fun = dnorm, colour = "red", xlim=c(-1, 1))# Using xlim to widen the range of functionggplot(data.frame(x = rnorm(100)), aes(x)) +geom_density() +geom_function(fun = dnorm, colour = "red", xlim=c(-7, 7))

Hexagonal heatmap of 2d bin counts

Description

Divides the plane into regular hexagons, counts the number of cases ineach hexagon, and then (by default) maps the number of cases to the hexagonfill. Hexagon bins avoid the visual artefacts sometimes generated bythe very regular alignment ofgeom_bin_2d().

Usage

geom_hex(  mapping = NULL,  data = NULL,  stat = "binhex",  position = "identity",  ...,  lineend = "butt",  linejoin = "mitre",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_bin_hex(  mapping = NULL,  data = NULL,  geom = "hex",  position = "identity",  ...,  binwidth = NULL,  bins = 30,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Override the default connection betweengeom_hex() andstat_bin_hex(). For more information about overriding these connections,see how thestat andgeom arguments work.

binwidth

The width of the bins. Can be specified as a numeric valueor as a function that takes x after scale transformation as input andreturns a single numeric value. When specifying a function along with agrouping structure, the function will be called once per group.The default is to use the number of bins inbins,covering the range of the data. You should always overridethis value, exploring multiple widths to find the best to illustrate thestories in your data.

The bin width of a date variable is the number of days in each time; thebin width of a time variable is the number of seconds.

bins

Number of bins. Overridden bybinwidth. Defaults to 30.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Controlling binning parameters for the x and y directions

The argumentsbins andbinwidth canbe set separately for the x and y directions. When given as a scalar, onevalue applies to both directions. When given as a vector of length two,the first is applied to the x direction and the second to the y direction.Alternatively, these can be a named list containingx andy elements,for examplelist(x = 10, y = 20).

Aesthetics

geom_hex() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()

stat_binhex() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
fillafter_stat(count)
group → inferred
weight1

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

stat_bin_2d() for rectangular binning

Examples

d <- ggplot(diamonds, aes(carat, price))d + geom_hex()# You can control the size of the bins by specifying the number of# bins in each direction:d + geom_hex(bins = 10)d + geom_hex(bins = 30)# Or by specifying the width of the binsd + geom_hex(binwidth = c(1, 1000))d + geom_hex(binwidth = c(.1, 500))

Jittered points

Description

The jitter geom is a convenient shortcut forgeom_point(position = "jitter"). It adds a small amount of randomvariation to the location of each point, and is a useful way of handlingoverplotting caused by discreteness in smaller datasets.

Usage

geom_jitter(  mapping = NULL,  data = NULL,  stat = "identity",  position = "jitter",  ...,  width = NULL,  height = NULL,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

width,height

Amount of vertical and horizontal jitter. The jitteris added in both positive and negative directions, so the total spreadis twice the value specified here.

If omitted, defaults to 40% of the resolution of the data: this means thejitter values will occupy 80% of the implied bins. Categorical datais aligned on the integers, so a width or height of 0.5 will spread thedata so it's not possible to see the distinction between the categories.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Aesthetics

geom_point() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
shape → viatheme()
size → viatheme()
stroke → viatheme()

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

geom_point() for regular, unjittered points,geom_boxplot() for another way of looking at the conditionaldistribution of a variable

Examples

p <- ggplot(mpg, aes(cyl, hwy))p + geom_point()p + geom_jitter()# Add aesthetic mappingsp + geom_jitter(aes(colour = class))# Use smaller width/height to emphasise categoriesggplot(mpg, aes(cyl, hwy)) +  geom_jitter()ggplot(mpg, aes(cyl, hwy)) +  geom_jitter(width = 0.25)# Use larger width/height to completely smooth away discretenessggplot(mpg, aes(cty, hwy)) +  geom_jitter()ggplot(mpg, aes(cty, hwy)) +  geom_jitter(width = 0.5, height = 0.5)

Text

Description

Text geoms are useful for labeling plots. They can be used by themselves asscatterplots or in combination with other geoms, for example, for labelingpoints or for annotating the height of bars.geom_text() adds only textto the plot.geom_label() draws a rectangle behind the text, making iteasier to read.

Usage

geom_label(  mapping = NULL,  data = NULL,  stat = "identity",  position = "nudge",  ...,  parse = FALSE,  label.padding = unit(0.25, "lines"),  label.r = unit(0.15, "lines"),  label.size = deprecated(),  border.colour = NULL,  border.color = NULL,  text.colour = NULL,  text.color = NULL,  size.unit = "mm",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_text(  mapping = NULL,  data = NULL,  stat = "identity",  position = "nudge",  ...,  parse = FALSE,  check_overlap = FALSE,  size.unit = "mm",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

parse

IfTRUE, the labels will be parsed into expressions anddisplayed as described in?plotmath.

label.padding

Amount of padding around label. Defaults to 0.25 lines.

label.r

Radius of rounded corners. Defaults to 0.15 lines.

label.size

[Deprecated] Replaced by thelinewidth aesthetic. Size of label border, in mm.

border.colour,border.color

Colour of label border. WhenNULL(default), thecolour aesthetic determines the colour of the label border.border.color is an alias forborder.colour.

text.colour,text.color

Colour of the text. WhenNULL (default), thecolour aesthetic determines the colour of the text.text.color is analias fortext.colour.

size.unit

How thesize aesthetic is interpreted: as millimetres("mm", default), points ("pt"), centimetres ("cm"), inches ("in"),or picas ("pc").

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

check_overlap

IfTRUE, text that overlaps previous text in thesame layer will not be plotted.check_overlap happens at draw time and inthe order of the data. Therefore data should be arranged by the labelcolumn before callinggeom_text(). Note that this argument is notsupported bygeom_label().

Details

Note that when you resize a plot, text labels stay the same size, eventhough the size of the plot area changes. This happens because the "width"and "height" of a text element are 0. Obviously, text labels do have heightand width, but they are physical units, not data units. For the same reason,stacking and dodging text will not work by default, and axis limits are notautomatically expanded to include all text.

geom_text() andgeom_label() add labels for each row in thedata, even if coordinates x, y are set to single values in the calltogeom_label() orgeom_text().To add labels at specified points useannotate() withannotate(geom = "text", ...) orannotate(geom = "label", ...).

To automatically position non-overlapping text labels see theggrepelpackage.

geom_label()

Currentlygeom_label() does not support thecheck_overlap argument. Also,it is considerably slower thangeom_text(). Thefill aesthetic controlsthe background colour of the label.

Alignment

You can modify text alignment with thevjust andhjustaesthetics. These can either be a number between 0 (left/bottom) and1 (right/top) or a character ("left","middle","right","bottom","center","top"). There are two special alignments:"inward" and"outward". Inward always aligns text towards the center, and outwardaligns it away from the center.

Aesthetics

geom_text() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
label
alphaNA
angle0
colour → viatheme()
family → viatheme()
fontface1
group → inferred
hjust0.5
lineheight1.2
size → viatheme()
vjust0.5

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

Thetext labels section of the online ggplot2 book.

Examples

p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars)))p + geom_text()# Avoid overlapsp + geom_text(check_overlap = TRUE)# Labels with backgroundp + geom_label()# Change size of the labelp + geom_text(size = 10)# Set aesthetics to fixed valuep +  geom_point() +  geom_text(hjust = 0, nudge_x = 0.05)p +  geom_point() +  geom_text(vjust = 0, nudge_y = 0.5)p +  geom_point() +  geom_text(angle = 45)## Not run: # Doesn't work on all systemsp +  geom_text(family = "Times New Roman")## End(Not run)# Add aesthetic mappingsp + geom_text(aes(colour = factor(cyl)))p + geom_text(aes(colour = factor(cyl))) +  scale_colour_hue(l = 40)p + geom_label(aes(fill = factor(cyl)), colour = "white", fontface = "bold")# Scale size of text, and change legend key glyph from a to pointp + geom_text(aes(size = wt), key_glyph = "point")# Scale height of text, rather than sqrt(height)p +  geom_text(aes(size = wt), key_glyph = "point") +  scale_radius(range = c(3,6))# You can display expressions by setting parse = TRUE.  The# details of the display are described in ?plotmath, but note that# geom_text uses strings, not expressions.p +  geom_text(    aes(label = paste(wt, "^(", cyl, ")", sep = "")),    parse = TRUE  )# Add a text annotationp +  geom_text() +  annotate(    "text", label = "plot mpg vs. wt",    x = 2, y = 15, size = 8, colour = "red"  )# Aligning labels and bars --------------------------------------------------df <- data.frame(  x = factor(c(1, 1, 2, 2)),  y = c(1, 3, 2, 1),  grp = c("a", "b", "a", "b"))# ggplot2 doesn't know you want to give the labels the same virtual width# as the bars:ggplot(data = df, aes(x, y, group = grp)) +  geom_col(aes(fill = grp), position = "dodge") +  geom_text(aes(label = y), position = "dodge")# So tell it:ggplot(data = df, aes(x, y, group = grp)) +  geom_col(aes(fill = grp), position = "dodge") +  geom_text(aes(label = y), position = position_dodge(0.9))# You can't nudge and dodge text, so instead adjust the y positionggplot(data = df, aes(x, y, group = grp)) +  geom_col(aes(fill = grp), position = "dodge") +  geom_text(    aes(label = y, y = y + 0.05),    position = position_dodge(0.9),    vjust = 0  )# To place text in the middle of each bar in a stacked barplot, you# need to set the vjust parameter of position_stack()ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp)) + geom_text(aes(label = y), position = position_stack(vjust = 0.5))# Justification -------------------------------------------------------------df <- data.frame(  x = c(1, 1, 2, 2, 1.5),  y = c(1, 2, 1, 2, 1.5),  text = c("bottom-left", "top-left", "bottom-right", "top-right", "center"))ggplot(df, aes(x, y)) +  geom_text(aes(label = text))ggplot(df, aes(x, y)) +  geom_text(aes(label = text), vjust = "inward", hjust = "inward")

Polygons from a reference map

Description

Display polygons as a map. This is meant as annotation, so it does notaffect position scales. Note that this function predates thegeom_sf()framework and does not work with sf geometry columns as input. However,it can be used in conjunction withgeom_sf() layers and/orcoord_sf() (see examples).

Usage

geom_map(  mapping = NULL,  data = NULL,  stat = "identity",  ...,  map,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

map

Data frame that contains the map coordinates. This willtypically be created usingfortify() on a spatial object.It must contain columnsx orlong,y orlat, andregion orid.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Aesthetics

geom_map() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

map_id
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
subgroupNULL

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

# First, a made-up example containing a few polygons, to explain# how `geom_map()` works. It requires two data frames:# One contains the coordinates of each polygon (`positions`), and is# provided via the `map` argument. The other contains the# values associated with each polygon (`values`).  An id# variable links the two together.ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))values <- data.frame(  id = ids,  value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5))positions <- data.frame(  id = rep(ids, each = 4),  x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,  0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),  y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,  2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2))ggplot(values) +  geom_map(aes(map_id = id), map = positions) +  expand_limits(positions)ggplot(values, aes(fill = value)) +  geom_map(aes(map_id = id), map = positions) +  expand_limits(positions)ggplot(values, aes(fill = value)) +  geom_map(aes(map_id = id), map = positions) +  expand_limits(positions) + ylim(0, 3)# Now some examples with real mapsif (require(maps)) {  crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)  # Equivalent to crimes |> tidyr::pivot_longer(Murder:Rape)  vars <- lapply(names(crimes)[-1], function(j) {    data.frame(state = crimes$state, variable = j, value = crimes[[j]])  })  crimes_long <- do.call("rbind", vars)  states_map <- map_data("state")  # without geospatial coordinate system, the resulting plot  # looks weird  ggplot(crimes, aes(map_id = state)) +    geom_map(aes(fill = Murder), map = states_map) +    expand_limits(x = states_map$long, y = states_map$lat)  # in combination with `coord_sf()` we get an appropriate result  ggplot(crimes, aes(map_id = state)) +    geom_map(aes(fill = Murder), map = states_map) +    # crs = 5070 is a Conus Albers projection for North America,    #   see: https://epsg.io/5070    # default_crs = 4326 tells coord_sf() that the input map data    #   are in longitude-latitude format    coord_sf(      crs = 5070, default_crs = 4326,      xlim = c(-125, -70), ylim = c(25, 52)    ) ggplot(crimes_long, aes(map_id = state)) +   geom_map(aes(fill = value), map = states_map) +   coord_sf(     crs = 5070, default_crs = 4326,     xlim = c(-125, -70), ylim = c(25, 52)   ) +   facet_wrap(~variable)}

Connect observations

Description

geom_path() connects the observations in the order in which they appearin the data.geom_line() connects them in order of the variable on thex axis.geom_step() creates a stairstep plot, highlighting exactlywhen changes occur. Thegroup aesthetic determines which cases areconnected together.

Usage

geom_path(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  arrow = NULL,  arrow.fill = NULL,  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_line(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  orientation = NA,  arrow = NULL,  arrow.fill = NULL,  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_step(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  orientation = NA,  lineend = "butt",  linejoin = "round",  linemitre = 10,  arrow = NULL,  arrow.fill = NULL,  direction = "hv",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

arrow

Arrow specification, as created bygrid::arrow().

arrow.fill

fill colour to use for the arrow head (if closed).NULLmeans usecolour aesthetic.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

direction

direction of stairs: 'vh' for vertical then horizontal,'hv' for horizontal then vertical, or 'mid' for step half-way betweenadjacent x-values.

Details

An alternative parameterisation isgeom_segment(), where each linecorresponds to a single case which provides the start and end coordinates.

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Missing value handling

geom_path(),geom_line(), andgeom_step() handleNA as follows:

Aesthetics

geom_path() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

geom_polygon(): Filled paths (polygons);geom_segment(): Line segments

Examples

# geom_line() is suitable for time seriesggplot(economics, aes(date, unemploy)) + geom_line()# separate by colour and use "timeseries" legend key glyphggplot(economics_long, aes(date, value01, colour = variable)) +  geom_line(key_glyph = "timeseries")# You can get a timeseries that run vertically by setting the orientationggplot(economics, aes(unemploy, date)) + geom_line(orientation = "y")# geom_step() is useful when you want to highlight exactly when# the y value changesrecent <- economics[economics$date > as.Date("2013-01-01"), ]ggplot(recent, aes(date, unemploy)) + geom_line()ggplot(recent, aes(date, unemploy)) + geom_step()# geom_path lets you explore how two variables are related over time,# e.g. unemployment and personal savings ratem <- ggplot(economics, aes(unemploy/pop, psavert))m + geom_path()m + geom_path(aes(colour = as.numeric(date)))# Changing parameters ----------------------------------------------ggplot(economics, aes(date, unemploy)) +  geom_line(colour = "red")# Use the arrow parameter to add an arrow to the line# See ?arrow for more detailsc <- ggplot(economics, aes(x = date, y = pop))c + geom_line(arrow = arrow())c + geom_line(  arrow = arrow(angle = 15, ends = "both", type = "closed"))# Control line join parametersdf <- data.frame(x = 1:3, y = c(4, 1, 9))base <- ggplot(df, aes(x, y))base + geom_path(linewidth = 10)base + geom_path(linewidth = 10, lineend = "round")base + geom_path(linewidth = 10, linejoin = "mitre", lineend = "butt")# You can use NAs to break the line.df <- data.frame(x = 1:5, y = c(1, 2, NA, 4, 5))ggplot(df, aes(x, y)) + geom_point() + geom_line()# Setting line type vs colour/size# Line type needs to be applied to a line as a whole, so it can# not be used with colour or size that vary across a linex <- seq(0.01, .99, length.out = 100)df <- data.frame(  x = rep(x, 2),  y = c(qlogis(x), 2 * qlogis(x)),  group = rep(c("a","b"),  each = 100))p <- ggplot(df, aes(x=x, y=y, group=group))# These workp + geom_line(linetype = 2)p + geom_line(aes(colour = group), linetype = 2)p + geom_line(aes(colour = x))# But this doesn'tshould_stop(p + geom_line(aes(colour = x), linetype=2))

Points

Description

The point geom is used to create scatterplots. The scatterplot is mostuseful for displaying the relationship between two continuous variables.It can be used to compare one continuous and one categorical variable, ortwo categorical variables, but a variation likegeom_jitter(),geom_count(), orgeom_bin_2d() is usually moreappropriate. Abubblechart is a scatterplot with a third variablemapped to the size of points.

Usage

geom_point(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Overplotting

The biggest potential problem with a scatterplot is overplotting: wheneveryou have more than a few points, points may be plotted on top of oneanother. This can severely distort the visual appearance of the plot.There is no one solution to this problem, but there are some techniquesthat can help. You can add additional information withgeom_smooth(),geom_quantile() orgeom_density_2d(). If you have few uniquex values,geom_boxplot() may also be useful.

Alternatively, you cansummarise the number of points at each location and display that in someway, usinggeom_count(),geom_hex(), orgeom_density2d().

Another technique is to make the points transparent (e.g.geom_point(alpha = 0.05)) or very small (e.g.geom_point(shape = ".")).

Aesthetics

geom_point() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
shape → viatheme()
size → viatheme()
stroke → viatheme()

Thefill aesthetic only applies to shapes 21-25.

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

p <- ggplot(mtcars, aes(wt, mpg))p + geom_point()# Add aesthetic mappingsp + geom_point(aes(colour = factor(cyl)))p + geom_point(aes(shape = factor(cyl)))# A "bubblechart":p + geom_point(aes(size = qsec))# Set aesthetics to fixed valueggplot(mtcars, aes(wt, mpg)) + geom_point(colour = "red", size = 3)# Varying alpha is useful for large datasetsd <- ggplot(diamonds, aes(carat, price))d + geom_point(alpha = 1/10)d + geom_point(alpha = 1/20)d + geom_point(alpha = 1/100)# For shapes that have a border (like 21), you can colour the inside and# outside separately. Use the stroke aesthetic to modify the width of the# borderggplot(mtcars, aes(wt, mpg)) +  geom_point(shape = 21, colour = "black", fill = "white", size = 5, stroke = 5)# The default shape in legends is not filled, but you can override the shape# in the guide to reflect the fill in the legendggplot(mtcars, aes(wt, mpg, fill = factor(carb), shape = factor(cyl))) +  geom_point(size = 5, stroke = 1) +  scale_shape_manual(values = 21:25) +  scale_fill_ordinal(guide = guide_legend(override.aes = list(shape = 21)))# You can create interesting shapes by layering multiple points of# different sizesp <- ggplot(mtcars, aes(mpg, wt, shape = factor(cyl)))p +  geom_point(aes(colour = factor(cyl)), size = 4) +  geom_point(colour = "grey90", size = 1.5)p +  geom_point(colour = "black", size = 4.5) +  geom_point(colour = "pink", size = 4) +  geom_point(aes(shape = factor(cyl)))# geom_point warns when missing values have been dropped from the data set# and not plotted, you can turn this off by setting na.rm = TRUEset.seed(1)mtcars2 <- transform(mtcars, mpg = ifelse(runif(32) < 0.2, NA, mpg))ggplot(mtcars2, aes(wt, mpg)) +  geom_point()ggplot(mtcars2, aes(wt, mpg)) +  geom_point(na.rm = TRUE)

Polygons

Description

Polygons are very similar to paths (as drawn bygeom_path())except that the start and end points are connected and the inside iscoloured byfill. Thegroup aesthetic determines which casesare connected together into a polygon. From R 3.6 and onwards it is possibleto draw polygons with holes by providing a subgroup aesthetic thatdifferentiates the outer ring points from those describing holes in thepolygon.

Usage

geom_polygon(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  rule = "evenodd",  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

rule

Either"evenodd" or"winding". If polygons with holes arebeing drawn (using thesubgroup aesthetic) this argument defines how thehole coordinates are interpreted. See the examples ingrid::pathGrob() foran explanation.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Aesthetics

geom_polygon() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
subgroupNULL

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

geom_path() for an unfilled polygon,geom_ribbon() for a polygon anchored on the x-axis

Examples

# When using geom_polygon, you will typically need two data frames:# one contains the coordinates of each polygon (positions),  and the# other the values associated with each polygon (values).  An id# variable links the two togetherids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))values <- data.frame(  id = ids,  value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5))positions <- data.frame(  id = rep(ids, each = 4),  x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,  0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),  y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,  2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2))# Currently we need to manually merge the two togetherdatapoly <- merge(values, positions, by = c("id"))p <- ggplot(datapoly, aes(x = x, y = y)) +  geom_polygon(aes(fill = value, group = id))p# Which seems like a lot of work, but then it's easy to add on# other features in this coordinate system, e.g.:set.seed(1)stream <- data.frame(  x = cumsum(runif(50, max = 0.1)),  y = cumsum(runif(50,max = 0.1)))p + geom_line(data = stream, colour = "grey30", linewidth = 5)# And if the positions are in longitude and latitude, you can use# coord_map to produce different map projections.if (packageVersion("grid") >= "3.6") {  # As of R version 3.6 geom_polygon() supports polygons with holes  # Use the subgroup aesthetic to differentiate holes from the main polygon  holes <- do.call(rbind, lapply(split(datapoly, datapoly$id), function(df) {    df$x <- df$x + 0.5 * (mean(df$x) - df$x)    df$y <- df$y + 0.5 * (mean(df$y) - df$y)    df  }))  datapoly$subid <- 1L  holes$subid <- 2L  datapoly <- rbind(datapoly, holes)  p <- ggplot(datapoly, aes(x = x, y = y)) +    geom_polygon(aes(fill = value, group = id, subgroup = subid))  p}

A quantile-quantile plot

Description

geom_qq() andstat_qq() produce quantile-quantile plots.geom_qq_line() andstat_qq_line() compute the slope and intercept of the line connecting thepoints at specified quartiles of the theoretical and sample distributions.

Usage

geom_qq_line(  mapping = NULL,  data = NULL,  geom = "abline",  position = "identity",  ...,  distribution = stats::qnorm,  dparams = list(),  line.p = c(0.25, 0.75),  fullrange = FALSE,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_qq_line(  mapping = NULL,  data = NULL,  geom = "abline",  position = "identity",  ...,  distribution = stats::qnorm,  dparams = list(),  line.p = c(0.25, 0.75),  fullrange = FALSE,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_qq(  mapping = NULL,  data = NULL,  geom = "point",  position = "identity",  ...,  distribution = stats::qnorm,  dparams = list(),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_qq(  mapping = NULL,  data = NULL,  geom = "point",  position = "identity",  ...,  distribution = stats::qnorm,  dparams = list(),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

distribution

Distribution function to use, if x not specified

dparams

Additional parameters passed on todistributionfunction.

line.p

Vector of quantiles to use when fitting the Q-Q line, defaultsdefaults toc(.25, .75).

fullrange

Should the q-q line span the full range of the plot, or justthe data

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.
Variables computed bystat_qq():

Variables computed bystat_qq_line():

Aesthetics

stat_qq() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

sample
group → inferred
xafter_stat(theoretical)
yafter_stat(sample)

stat_qq_line() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

sample
group → inferred
xafter_stat(x)
yafter_stat(y)

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

df <- data.frame(y = rt(200, df = 5))p <- ggplot(df, aes(sample = y))p + stat_qq() + stat_qq_line()# Use fitdistr from MASS to estimate distribution params:# if (requireNamespace("MASS", quietly = TRUE)) {#   params <- as.list(MASS::fitdistr(df$y, "t")$estimate)# }# Here, we use pre-computed paramsparams <- list(m = -0.02505057194115, s = 1.122568610124, df = 6.63842653897)ggplot(df, aes(sample = y)) +  stat_qq(distribution = qt, dparams = params["df"]) +  stat_qq_line(distribution = qt, dparams = params["df"])# Using to explore the distribution of a variableggplot(mtcars, aes(sample = mpg)) +  stat_qq() +  stat_qq_line()ggplot(mtcars, aes(sample = mpg, colour = factor(cyl))) +  stat_qq() +  stat_qq_line()

Quantile regression

Description

This fits a quantile regression to the data and draws the fitted quantileswith lines. This is as a continuous analogue togeom_boxplot().

Usage

geom_quantile(  mapping = NULL,  data = NULL,  stat = "quantile",  position = "identity",  ...,  arrow = NULL,  arrow.fill = NULL,  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_quantile(  mapping = NULL,  data = NULL,  geom = "quantile",  position = "identity",  ...,  quantiles = c(0.25, 0.5, 0.75),  formula = NULL,  method = "rq",  method.args = list(),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

arrow

Arrow specification, as created bygrid::arrow().

arrow.fill

fill colour to use for the arrow head (if closed).NULLmeans usecolour aesthetic.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Use to override the default connection betweengeom_quantile() andstat_quantile(). For more information aboutoverriding these connections, see how thestat andgeom arguments work.

quantiles

conditional quantiles of y to calculate and display

formula

formula relating y variables to x variables

method

Quantile regression method to use. Available options are"rq" (forquantreg::rq()) and"rqss" (forquantreg::rqss()).

method.args

List of additional arguments passed on to the modellingfunction defined bymethod.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Aesthetics

geom_quantile() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
weight1

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

m <-  ggplot(mpg, aes(displ, 1 / hwy)) +  geom_point()m + geom_quantile()m + geom_quantile(quantiles = 0.5)q10 <- seq(0.05, 0.95, by = 0.05)m + geom_quantile(quantiles = q10)# You can also use rqss to fit smooth quantilesm + geom_quantile(method = "rqss")# Note that rqss doesn't pick a smoothing constant automatically, so# you'll need to tweak lambda yourselfm + geom_quantile(method = "rqss", lambda = 0.1)# Set aesthetics to fixed valuem + geom_quantile(colour = "red", linewidth = 2, alpha = 0.5)

Rectangles

Description

geom_rect() andgeom_tile() do the same thing, but areparameterised differently:geom_tile() uses the center of the tile and itssize (x,y,width,height), whilegeom_rect() can use those or thelocations of the corners (xmin,xmax,ymin andymax).geom_raster() is a high performance special case for when all the tilesare the same size, and no pattern fills are applied.

Usage

geom_raster(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  interpolate = FALSE,  hjust = 0.5,  vjust = 0.5,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_rect(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  lineend = "butt",  linejoin = "mitre",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_tile(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  lineend = "butt",  linejoin = "mitre",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

interpolate

IfTRUE interpolate linearly, ifFALSE(the default) don't interpolate.

hjust,vjust

horizontal and vertical justification of the grob. Eachjustification value should be a number between 0 and 1. Defaults to 0.5for both, centering each pixel over its data location.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

Details

Please note that thewidth andheight aesthetics are not true positionaesthetics and therefore are not subject to scale transformation. It isonly after transformation that these aesthetics are applied.

Aesthetics

geom_rect() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

xorwidthorxminorxmax
yorheightoryminorymax
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()

geom_tile() understands only thex/width andy/height combinations.Note thatgeom_raster() ignorescolour.

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

# The most common use for rectangles is to draw a surface. You always want# to use geom_raster here because it's so much faster, and produces# smaller output when saving to PDFggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density))# Interpolation smooths the surface & is most helpful when rendering images.ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density), interpolate = TRUE)# If you want to draw arbitrary rectangles, use geom_tile() or geom_rect()df <- data.frame(  x = rep(c(2, 5, 7, 9, 12), 2),  y = rep(c(1, 2), each = 5),  z = factor(rep(1:5, each = 2)),  w = rep(diff(c(0, 4, 6, 8, 10, 14)), 2))ggplot(df, aes(x, y)) +  geom_tile(aes(fill = z), colour = "grey50")ggplot(df, aes(x, y, width = w)) +  geom_tile(aes(fill = z), colour = "grey50")ggplot(df, aes(xmin = x - w / 2, xmax = x + w / 2, ymin = y, ymax = y + 1)) +  geom_rect(aes(fill = z), colour = "grey50")# Justification controls where the cells are anchoreddf <- expand.grid(x = 0:5, y = 0:5)set.seed(1)df$z <- runif(nrow(df))# default is compatible with geom_tile()ggplot(df, aes(x, y, fill = z)) +  geom_raster()# zero paddingggplot(df, aes(x, y, fill = z)) +  geom_raster(hjust = 0, vjust = 0)# Inspired by the image-density plots of Ken Knoblauchcars <- ggplot(mtcars, aes(mpg, factor(cyl)))cars + geom_point()cars + stat_bin_2d(aes(fill = after_stat(count)), binwidth = c(3,1))cars + stat_bin_2d(aes(fill = after_stat(density)), binwidth = c(3,1))cars +  stat_density(    aes(fill = after_stat(density)),    geom = "raster",    position = "identity"   )cars +  stat_density(    aes(fill = after_stat(count)),    geom = "raster",    position = "identity"  )

Ribbons and area plots

Description

For each x value,geom_ribbon() displays a y interval definedbyymin andymax.geom_area() is a special case ofgeom_ribbon(), where theymin is fixed to 0 andy is used insteadofymax.

Usage

geom_ribbon(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  orientation = NA,  lineend = "butt",  linejoin = "round",  linemitre = 10,  outline.type = "both",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_area(  mapping = NULL,  data = NULL,  stat = "align",  position = "stack",  ...,  orientation = NA,  outline.type = "upper",  lineend = "butt",  linejoin = "round",  linemitre = 10,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_align(  mapping = NULL,  data = NULL,  geom = "area",  position = "identity",  ...,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

linemitre

Line mitre limit (number greater than 1).

outline.type

Type of the outline of the area;"both" draws both theupper and lower lines,"upper"/"lower" draws the respective lines only."full" draws a closed polygon around the area.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

Details

An area plot is the continuous analogue of a stacked bar chart (seegeom_bar()), and can be used to show how composition of thewhole varies over the range of x. Choosing the order in which differentcomponents is stacked is very important, as it becomes increasing hard tosee the individual pattern as you move up the stack. Seeposition_stack() for the details of stacking algorithm. To facilitatestacking, the defaultstat = "align" interpolates groups to a common setof x-coordinates. To turn off this interpolation,stat = "identity" canbe used instead.

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Aesthetics

geom_ribbon() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

xory
yminorxmin
ymaxorxmax
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

geom_bar() for discrete intervals (bars),geom_linerange() for discrete intervals (lines),geom_polygon() for general polygons

Examples

# Generate datahuron <- data.frame(year = 1875:1972, level = as.vector(LakeHuron))h <- ggplot(huron, aes(year))h + geom_ribbon(aes(ymin=0, ymax=level))h + geom_area(aes(y = level))# Orientation cannot be deduced by mapping, so must be given explicitly for# flipped orientationh + geom_area(aes(x = level, y = year), orientation = "y")# Add aesthetic mappingsh +  geom_ribbon(aes(ymin = level - 1, ymax = level + 1), fill = "grey70") +  geom_line(aes(y = level))# The underlying stat_align() takes care of unaligned data pointsdf <- data.frame(  g = c("a", "a", "a", "b", "b", "b"),  x = c(1, 3, 5, 2, 4, 6),  y = c(2, 5, 1, 3, 6, 7))a <- ggplot(df, aes(x, y, fill = g)) +  geom_area()# Two groups have points on different X values.a + geom_point(size = 8) + facet_grid(g ~ .)# stat_align() interpolates and aligns the value so that the areas can stack# properly.a + geom_point(stat = "align", position = "stack", size = 8)# To turn off the alignment, the stat can be set to "identity"ggplot(df, aes(x, y, fill = g)) +  geom_area(stat = "identity")

Rug plots in the margins

Description

A rug plot is a compact visualisation designed to supplement a 2d displaywith the two 1d marginal distributions. Rug plots display individualcases so are best used with smaller datasets.

Usage

geom_rug(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  lineend = "butt",  sides = "bl",  outside = FALSE,  length = unit(0.03, "npc"),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

lineend

Line end style (round, butt, square).

sides

A string that controls which sides of the plot the rugs appear on.It can be set to a string containing any of"trbl", for top, right,bottom, and left.

outside

logical that controls whether to move the rug tassels outside of the plot area. Default is off (FALSE). You will also need to usecoord_cartesian(clip = "off"). When set to TRUE, also consider changing the sides argument to "tr". See examples.

length

Agrid::unit() object that sets the length of the rug lines. Use scale expansion to avoid overplotting of data.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Details

By default, the rug lines are drawn with a length that corresponds to 3%of the total plot size. Since the default scale expansion of for continuousvariables is 5% at both ends of the scale, the rug will not overlap withany data points under the default settings.

Aesthetics

geom_rug() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

alphaNA
colour → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
x
y

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

p <- ggplot(mtcars, aes(wt, mpg)) +  geom_point()pp + geom_rug()p + geom_rug(sides="b")    # Rug on bottom onlyp + geom_rug(sides="trbl") # All four sides# Use jittering to avoid overplotting for smaller datasetsggplot(mpg, aes(displ, cty)) +  geom_point() +  geom_rug()ggplot(mpg, aes(displ, cty)) +  geom_jitter() +  geom_rug(alpha = 1/2, position = "jitter")# move the rug tassels to outside the plot# remember to set clip = "off".p +  geom_rug(outside = TRUE) +  coord_cartesian(clip = "off")# set sides to top right, and then move the marginsp +  geom_rug(outside = TRUE, sides = "tr") +  coord_cartesian(clip = "off") +  theme(plot.margin = margin_auto(1, unit = "cm"))# increase the line length and# expand axis to avoid overplottingp +  geom_rug(length = unit(0.05, "npc")) +  scale_y_continuous(expand = c(0.1, 0.1))

Line segments and curves

Description

geom_segment() draws a straight line between points (x, y) and(xend, yend).geom_curve() draws a curved line. See the underlyingdrawing functiongrid::curveGrob() for the parameters thatcontrol the curve.

Usage

geom_segment(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  arrow = NULL,  arrow.fill = NULL,  lineend = "butt",  linejoin = "round",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)geom_curve(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  curvature = 0.5,  angle = 90,  ncp = 5,  arrow = NULL,  arrow.fill = NULL,  lineend = "butt",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

arrow

specification for arrow heads, as created bygrid::arrow().

arrow.fill

fill colour to use for the arrow head (if closed).NULLmeans usecolour aesthetic.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

curvature

A numeric value giving the amount of curvature.Negative values produce left-hand curves, positive valuesproduce right-hand curves, and zero produces a straight line.

angle

A numeric value between 0 and 180,giving an amount to skew the controlpoints of the curve. Values less than 90 skew the curve towardsthe start point and values greater than 90 skew the curvetowards the end point.

ncp

The number of control points used to draw the curve.More control points creates a smoother curve.

Details

Both geoms draw a single segment/curve per case. Seegeom_path() if youneed to connect points across multiple cases.

Aesthetics

geom_segment() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
xendoryend
alphaNA
colour → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

geom_path() andgeom_line() for multi-segment lines and paths.

geom_spoke() for a segment parameterised by a location(x, y), and an angle and radius.

Examples

b <- ggplot(mtcars, aes(wt, mpg)) +  geom_point()df <- data.frame(x1 = 2.62, x2 = 3.57, y1 = 21.0, y2 = 15.0)b + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2, colour = "curve"), data = df) + geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2, colour = "segment"), data = df)b + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2), data = df, curvature = -0.2)b + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2), data = df, curvature = 1)b + geom_curve(  aes(x = x1, y = y1, xend = x2, yend = y2),  data = df,  arrow = arrow(length = unit(0.03, "npc")))if (requireNamespace('maps', quietly = TRUE)) {ggplot(seals, aes(long, lat)) +  geom_segment(aes(xend = long + delta_long, yend = lat + delta_lat),    arrow = arrow(length = unit(0.1,"cm"))) +  annotation_borders("state")}# Use lineend and linejoin to change the style of the segmentsdf2 <- expand.grid(  lineend = c('round', 'butt', 'square'),  linejoin = c('round', 'mitre', 'bevel'),  stringsAsFactors = FALSE)df2 <- data.frame(df2, y = 1:9)ggplot(df2, aes(x = 1, y = y, xend = 2, yend = y, label = paste(lineend, linejoin))) +  geom_segment(     lineend = df2$lineend, linejoin = df2$linejoin,     size = 3, arrow = arrow(length = unit(0.3, "inches"))  ) +  geom_text(hjust = 'outside', nudge_x = -0.2) +  xlim(0.5, 2)# You can also use geom_segment to recreate plot(type = "h") :set.seed(1)counts <- as.data.frame(table(x = rpois(100,5)))counts$x <- as.numeric(as.character(counts$x))with(counts, plot(x, Freq, type = "h", lwd = 10))ggplot(counts, aes(x, Freq)) +  geom_segment(aes(xend = x, yend = 0), linewidth = 10, lineend = "butt")

Smoothed conditional means

Description

Aids the eye in seeing patterns in the presence of overplotting.geom_smooth() andstat_smooth() are effectively aliases: theyboth use the same arguments. Usestat_smooth() if you want todisplay the results with a non-standard geom.

Usage

geom_smooth(  mapping = NULL,  data = NULL,  stat = "smooth",  position = "identity",  ...,  method = NULL,  formula = NULL,  se = TRUE,  na.rm = FALSE,  orientation = NA,  show.legend = NA,  inherit.aes = TRUE)stat_smooth(  mapping = NULL,  data = NULL,  geom = "smooth",  position = "identity",  ...,  orientation = NA,  method = NULL,  formula = NULL,  se = TRUE,  n = 80,  span = 0.75,  fullrange = FALSE,  xseq = NULL,  level = 0.95,  method.args = list(),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

method

Smoothing method (function) to use, accepts eitherNULL or a character vector, e.g."lm","glm","gam","loess"or a function, e.g.MASS::rlm ormgcv::gam,stats::lm, orstats::loess."auto" is also accepted for backwards compatibility. It is equivalent toNULL.

Formethod = NULL the smoothing method is chosen based on thesize of the largest group (across all panels).stats::loess() isused for less than 1,000 observations; otherwisemgcv::gam() isused withformula = y ~ s(x, bs = "cs") withmethod = "REML". Somewhat anecdotally,loess gives a better appearance, but isO(N^{2}) in memory,so does not work for larger datasets.

If you have fewer than 1,000 observations but want to use the samegam()model thatmethod = NULL would use, then set⁠method = "gam", formula = y ~ s(x, bs = "cs")⁠.

formula

Formula to use in smoothing function, eg.y ~ x,y ~ poly(x, 2),y ~ log(x).NULL by default, in which casemethod = NULL impliesformula = y ~ x when there are fewer than 1,000observations andformula = y ~ s(x, bs = "cs") otherwise.

se

Display confidence band around smooth? (TRUE by default, seelevel to control.)

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Use to override the default connection betweengeom_smooth() andstat_smooth(). For more information about overridingthese connections, see how thestat andgeomarguments work.

n

Number of points at which to evaluate smoother.

span

Controls the amount of smoothing for the default loess smoother.Smaller numbers produce wigglier lines, larger numbers produce smootherlines. Only used with loess, i.e. whenmethod = "loess",or whenmethod = NULL (the default) and there are fewer than 1,000observations.

fullrange

IfTRUE, the smoothing line gets expanded to the range of the plot,potentially beyond the data. This does not extend the line into any additional paddingcreated byexpansion.

xseq

A numeric vector of values at which the smoother is evaluated.WhenNULL (default),xseq is internally evaluated as a sequence ofnequally spaced points for continuous data.

level

Level of confidence band to use (0.95 by default).

method.args

List of additional arguments passed on to the modellingfunction defined bymethod.

Details

Calculation is performed by the (currently undocumented)predictdf() generic and its methods. For most methods the standarderror bounds are computed using thepredict() method – theexceptions areloess(), which uses a t-based approximation, andglm(), where the normal confidence band is constructed on the linkscale and then back-transformed to the response scale.

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.stat_smooth() provides the following variables, some of which depend on the orientation:

Aesthetics

geom_smooth() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alpha0.4
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
weight1
ymax
ymin

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

See individual modelling functions for more details:lm() for linear smooths,glm() for generalised linear smooths, andloess() for local smooths.

Examples

ggplot(mpg, aes(displ, hwy)) +  geom_point() +  geom_smooth()# If you need the fitting to be done along the y-axis set the orientationggplot(mpg, aes(displ, hwy)) +  geom_point() +  geom_smooth(orientation = "y")# Use span to control the "wiggliness" of the default loess smoother.# The span is the fraction of points used to fit each local regression:# small numbers make a wigglier curve, larger numbers make a smoother curve.ggplot(mpg, aes(displ, hwy)) +  geom_point() +  geom_smooth(span = 0.3)# Instead of a loess smooth, you can use any other modelling function:ggplot(mpg, aes(displ, hwy)) +  geom_point() +  geom_smooth(method = lm, se = FALSE)ggplot(mpg, aes(displ, hwy)) +  geom_point() +  geom_smooth(method = lm, formula = y ~ splines::bs(x, 3), se = FALSE)# Smooths are automatically fit to each group (defined by categorical# aesthetics or the group aesthetic) and for each facet.ggplot(mpg, aes(displ, hwy, colour = class)) +  geom_point() +  geom_smooth(se = FALSE, method = lm)ggplot(mpg, aes(displ, hwy)) +  geom_point() +  geom_smooth(span = 0.8) +  facet_wrap(~drv)binomial_smooth <- function(...) {  geom_smooth(method = "glm", method.args = list(family = "binomial"), ...)}# To fit a logistic regression, you need to coerce the values to# a numeric vector lying between 0 and 1.ggplot(rpart::kyphosis, aes(Age, Kyphosis)) +  geom_jitter(height = 0.05) +  binomial_smooth()ggplot(rpart::kyphosis, aes(Age, as.numeric(Kyphosis) - 1)) +  geom_jitter(height = 0.05) +  binomial_smooth()ggplot(rpart::kyphosis, aes(Age, as.numeric(Kyphosis) - 1)) +  geom_jitter(height = 0.05) +  binomial_smooth(formula = y ~ splines::ns(x, 2))# But in this case, it's probably better to fit the model yourself# so you can exercise more control and see whether or not it's a good model.

Line segments parameterised by location, direction and distance

Description

This is a polar parameterisation ofgeom_segment(). It isuseful when you have variables that describe direction and distance.The angles start from east and increase counterclockwise.

Usage

geom_spoke(  mapping = NULL,  data = NULL,  stat = "identity",  position = "identity",  ...,  arrow = NULL,  arrow.fill = NULL,  lineend = "butt",  linejoin = "round",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

arrow

specification for arrow heads, as created bygrid::arrow().

arrow.fill

fill colour to use for the arrow head (if closed).NULLmeans usecolour aesthetic.

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Aesthetics

geom_spoke() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
angle
radius
alphaNA
colour → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

df <- expand.grid(x = 1:10, y=1:10)set.seed(1)df$angle <- runif(100, 0, 2*pi)df$speed <- runif(100, 0, sqrt(0.1 * df$x))ggplot(df, aes(x, y)) +  geom_point() +  geom_spoke(aes(angle = angle), radius = 0.5)ggplot(df, aes(x, y)) +  geom_point() +  geom_spoke(aes(angle = angle, radius = speed))

Violin plot

Description

A violin plot is a compact display of a continuous distribution. It is ablend ofgeom_boxplot() andgeom_density(): aviolin plot is a mirrored density plot displayed in the same way as aboxplot.

Usage

geom_violin(  mapping = NULL,  data = NULL,  stat = "ydensity",  position = "dodge",  ...,  trim = TRUE,  bounds = c(-Inf, Inf),  quantile.colour = NULL,  quantile.color = NULL,  quantile.linetype = 0L,  quantile.linewidth = NULL,  draw_quantiles = deprecated(),  scale = "area",  na.rm = FALSE,  orientation = NA,  show.legend = NA,  inherit.aes = TRUE)stat_ydensity(  mapping = NULL,  data = NULL,  geom = "violin",  position = "dodge",  ...,  orientation = NA,  bw = "nrd0",  adjust = 1,  kernel = "gaussian",  trim = TRUE,  scale = "area",  drop = TRUE,  bounds = c(-Inf, Inf),  quantiles = c(0.25, 0.5, 0.75),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

trim

IfTRUE (default), trim the tails of the violinsto the range of the data. IfFALSE, don't trim the tails.

bounds

Known lower and upper bounds for estimated data. Defaultc(-Inf, Inf) means that there are no (finite) bounds. If any bound isfinite, boundary effect of default density estimation will be corrected byreflecting tails outsidebounds around their closest edge. Data pointsoutside of bounds are removed with a warning.

quantile.colour,quantile.color,quantile.linewidth,quantile.linetype

Default aesthetics for the quantile lines. Set toNULL to inherit fromthe data's aesthetics. By default, quantile lines are hidden and can beturned on by changingquantile.linetype. Quantile values can be setusing thequantiles argument when usingstat = "ydensity" (default).

draw_quantiles

[Deprecated] Previousspecification of drawing quantiles.

scale

if "area" (default), all violins have the same area (before trimmingthe tails). If "count", areas are scaled proportionally to the number ofobservations. If "width", all violins have the same maximum width.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

geom,stat

Use to override the default connection betweengeom_violin() andstat_ydensity(). For more information aboutoverriding these connections, see how thestat andgeom arguments work.

bw

The smoothing bandwidth to be used.If numeric, the standard deviation of the smoothing kernel.If character, a rule to choose the bandwidth, as listed instats::bw.nrd(). Note that automatic calculation of the bandwidth doesnot take weights into account.

adjust

A multiplicate bandwidth adjustment. This makes it possibleto adjust the bandwidth while still using the a bandwidth estimator.For example,adjust = 1/2 means use half of the default bandwidth.

kernel

Kernel. See list of available kernels indensity().

drop

Whether to discard groups with less than 2 observations(TRUE, default) or keep such groups for position adjustment purposes(FALSE).

quantiles

A numeric vector with numbers between 0 and 1 to indicatequantiles marked by thequantile computed variable. The default marks the25th, 50th and 75th percentiles. The display of quantiles can beturned on by settingquantile.linetype to non-blank when usinggeom = "violin" (default).

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Aesthetics

geom_violin() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
alphaNA
colour → viatheme()
fill → viatheme()
group → inferred
linetype → viatheme()
linewidth → viatheme()
weight1
width0.9

Learn more about setting these aesthetics invignette("ggplot2-specs").

References

Hintze, J. L., Nelson, R. D. (1998) Violin Plots: A BoxPlot-Density Trace Synergism. The American Statistician 52, 181-184.

See Also

geom_violin() for examples, andstat_density()for examples with data along the x axis.

Examples

p <- ggplot(mtcars, aes(factor(cyl), mpg))p + geom_violin()# Orientation follows the discrete axisggplot(mtcars, aes(mpg, factor(cyl))) +  geom_violin()p + geom_violin() + geom_jitter(height = 0, width = 0.1)# Scale maximum width proportional to sample size:p + geom_violin(scale = "count")# Scale maximum width to 1 for all violins:p + geom_violin(scale = "width")# Default is to trim violins to the range of the data. To disable:p + geom_violin(trim = FALSE)# Use a smaller bandwidth for closer density fit (default is 1).p + geom_violin(adjust = .5)# Add aesthetic mappings# Note that violins are automatically dodged when any aesthetic is# a factorp + geom_violin(aes(fill = cyl))p + geom_violin(aes(fill = factor(cyl)))p + geom_violin(aes(fill = factor(vs)))p + geom_violin(aes(fill = factor(am)))# Set aesthetics to fixed valuep + geom_violin(fill = "grey80", colour = "#3366FF")# Show quartilesp + geom_violin(draw_quantiles = c(0.25, 0.5, 0.75))# Scales vs. coordinate transforms -------if (require("ggplot2movies")) {# Scale transformations occur before the density statistics are computed.# Coordinate transformations occur afterwards.  Observe the effect on the# number of outliers.m <- ggplot(movies, aes(y = votes, x = rating, group = cut_width(rating, 0.5)))m + geom_violin()m +  geom_violin() +  scale_y_log10()m +  geom_violin() +  coord_transform(y = "log10")m +  geom_violin() +  scale_y_log10() + coord_transform(y = "log10")# Violin plots with continuous x:# Use the group aesthetic to group observations in violinsggplot(movies, aes(year, budget)) +  geom_violin()ggplot(movies, aes(year, budget)) +  geom_violin(aes(group = cut_width(year, 10)), scale = "width")}

Extract alt text from a plot

Description

This function returns a text that can be used as alt-text in webpages etc.Currently it will use thealt label, added with⁠+ labs(alt = <...>)⁠, ora return an empty string, but in the future it might try to generate an alttext from the information stored in the plot.

Usage

get_alt_text(p, ...)

Arguments

p

a ggplot object

...

Arguments passed to methods.

Value

A text string

Examples

p <- ggplot(mpg, aes(displ, hwy)) +  geom_point()# Returns an empty stringget_alt_text(p)# A user provided alt textp <- p + labs(  alt = paste("A scatterplot showing the negative correlation between engine",              "displacement as a function of highway miles per gallon"))get_alt_text(p)

Resolve and get geom defaults

Description

Resolve and get geom defaults

Usage

get_geom_defaults(geom, theme = theme_get())

Arguments

geom

Some definition of a geom:

  • Afunction that creates a layer, e.g.geom_path().

  • A layer created by such function

  • A string naming a geom class in snake case without thegeom_-prefix,e.g."contour_filled".

  • A geom class object.

theme

Atheme object. Defaults to the current global theme.

Value

A list of aesthetics

Examples

# Using a functionget_geom_defaults(geom_raster)# Using a layer includes static aesthetics as defaultget_geom_defaults(geom_tile(fill = "white"))# Using a class nameget_geom_defaults("density_2d")# Using a classget_geom_defaults(GeomPoint)# Changed themeget_geom_defaults("point", theme(geom = element_geom(ink = "purple")))

Extract tick information from guides

Description

get_guide_data() builds a plot and extracts information from guide keys. Thisinformation typically contains positions, values and/or labels, dependingon which aesthetic is queried or guide is used.

Usage

get_guide_data(plot = get_last_plot(), aesthetic, panel = 1L)

Arguments

plot

Aggplot orggplot_build object.

aesthetic

A string that describes a single aesthetic for which toextract guide information. For example:"colour","size","x" or"y.sec".

panel

An integer giving a panel number for which to return position guideinformation.

Value

One of the following:

Examples

# A standard plotp <- ggplot(mtcars) +  aes(mpg, disp, colour = drat, size = drat) +  geom_point() +  facet_wrap(vars(cyl), scales = "free_x")# Guide information for legendsget_guide_data(p, "size")# Note that legend guides can be mergedmerged <- p + guides(colour = "legend")get_guide_data(merged, "size")# Guide information for positionsget_guide_data(p, "x", panel = 2)# Coord polar doesn't support proper guides, so we get a listpolar <- p + coord_polar()get_guide_data(polar, "theta", panel = 2)

Retrieve the last plot to be modified or created.

Description

Retrieve the last plot to be modified or created.

Usage

get_last_plot()last_plot()

See Also

ggsave()


Accessing a plot's facet strip labels

Description

This functions retrieves labels from facet strips with the labeller applied.

Usage

get_strip_labels(plot = get_last_plot())

Arguments

plot

A ggplot or build ggplot object.

Value

NULL if there are no labels, otherwise a list of data.framescontaining the labels.

Examples

# Basic plotp <- ggplot(mpg, aes(displ, hwy)) +  geom_point()get_strip_labels(p) # empty facetsget_strip_labels(p + facet_wrap(year ~ cyl))get_strip_labels(p + facet_grid(year ~ cyl))

Get, set, and modify the active theme

Description

The current/active theme (seetheme()) is automatically applied to everyplot you draw. Useget_theme() to get the current theme, andset_theme() tocompletely override it.update_theme() andreplace_theme() are shorthands forchanging individual elements.

Usage

get_theme()theme_get()set_theme(new = NULL)theme_set(new = NULL)update_theme(...)theme_update(...)replace_theme(...)theme_replace(...)e1 %+replace% e2

Arguments

new

new theme (a list of theme elements). Sets theme to the default (theme_grey()) ifnew isn't supplied.

...

named list of theme settings

e1,e2

Theme and element to combine

Value

set_theme(),update_theme(), andreplace_theme()invisibly return the previous theme so you can easily save it, thenlater restore it.

Adding on to a theme

+ and⁠%+replace%⁠ can be used to modify elements in themes.

+ updates the elements of e1 that differ from elements specified (notNULL) in e2. Thus this operator can be used to incrementally add or modifyattributes of a ggplot theme.

In contrast,⁠%+replace%⁠ replaces the entire element; any element of atheme not specified in e2 will not be present in the resulting theme (i.e.NULL). Thus this operator can be used to overwrite an entire theme.

update_theme() uses the+ operator, so that any unspecified values in thetheme element will default to the values they are set in the theme.replace_theme() uses⁠%+replace%⁠ to completely replace the element, so anyunspecified values will overwrite the current value in the theme withNULL.

In summary, the main differences betweenset_theme(),update_theme(),andreplace_theme() are:

See Also

add_gg()

Examples

p <- ggplot(mtcars, aes(mpg, wt)) +  geom_point()p# Use set_theme() to completely override the current theme.# update_theme() and replace_theme() are similar except they# apply directly to the current/active theme.# update_theme() modifies a particular element of the current theme.# Here we have the old theme so we can later restore it.# Note that the theme is applied when the plot is drawn, not# when it is created.old <- set_theme(theme_bw())pset_theme(old)update_theme(panel.grid.minor = element_line(colour = "red"))pset_theme(old)replace_theme(panel.grid.minor = element_line(colour = "red"))pset_theme(old)p# Modifying theme objects -----------------------------------------# You can use + and %+replace% to modify a theme object.# They differ in how they deal with missing arguments in# the theme elements.add_el <- theme_grey() +  theme(text = element_text(family = "Times"))add_el$textrep_el <- theme_grey() %+replace%  theme(text = element_text(family = "Times"))rep_el$text

Give a deprecation error, warning, or message, depending on version number.

Description

[Deprecated]

Usage

gg_dep(version, msg)

Arguments

version

The last version of ggplot2 where this function was good(in other words, the last version where it was not deprecated).

msg

The message to print.


Interpreter for graphical parameters

Description

This is a wrapper forgrid::gpar() that applies ggplot2's interpretationof graphical parameters.

Usage

gg_par(..., stroke = NULL, pointsize = NULL)

Arguments

...

Named arguments passed on togpar().

stroke

Linewidth for points. Populates thelwd grid parameter.

pointsize

Size for points. Populates thefontsize grid parameter.

Value

An object of class 'gpar'.


Create a new ggplot

Description

ggplot() initializes a ggplot object. It can be used todeclare the input data frame for a graphic and to specify theset of aesthetic mappings for the plot, intended to be common throughout allsubsequent layers unless specifically overridden.

Usage

ggplot(data = NULL, mapping = aes(), ..., environment = parent.frame())

Arguments

data

Default dataset to use for plot. If not already a data.frame,will be converted to one byfortify(). If not specified,must be supplied in each layer added to the plot.

mapping

Default list of aesthetic mappings to use for plot.If not specified, must be supplied in each layer added to the plot.

...

Other arguments passed on to methods. Not currently used.

environment

[Deprecated] Used prior to tidyevaluation.

Details

ggplot() is used to construct the initial plot object,and is almost always followed by a plus sign (+) to addcomponents to the plot.

There are three common patterns used to invokeggplot():

The first pattern is recommended if all layers use the samedata and the same set of aesthetics, although this methodcan also be used when adding a layer using data from anotherdata frame.

The second pattern specifies the default data frame to usefor the plot, but no aesthetics are defined up front. Thisis useful when one data frame is used predominantly for theplot, but the aesthetics vary from one layer to another.

The third pattern initializes a skeletonggplot object, whichis fleshed out as layers are added. This is useful whenmultiple data frames are used to produce different layers, asis often the case in complex graphics.

The⁠data =⁠ and⁠mapping =⁠ specifications in the arguments are optional(and are often omitted in practice), so long as the data and the mappingvalues are passed into the function in the right order. In the examplesbelow, however, they are left in place for clarity.

See Also

Thefirst steps chapter of the online ggplot2 book.

Examples

# Create a data frame with some sample data, then create a data frame# containing the mean value for each group in the sample data.set.seed(1)sample_df <- data.frame(  group = factor(rep(letters[1:3], each = 10)),  value = rnorm(30))group_means_df <- setNames(  aggregate(value ~ group, sample_df, mean),  c("group", "group_mean"))# The following three code blocks create the same graphic, each using one# of the three patterns specified above. In each graphic, the sample data# are plotted in the first layer and the group means data frame is used to# plot larger red points on top of the sample data in the second layer.# Pattern 1# Both the `data` and `mapping` arguments are passed into the `ggplot()`# call. Those arguments are omitted in the first `geom_point()` layer# because they get passed along from the `ggplot()` call. Note that the# second `geom_point()` layer re-uses the `x = group` aesthetic through# that mechanism but overrides the y-position aesthetic.ggplot(data = sample_df, mapping = aes(x = group, y = value)) +  geom_point() +  geom_point(    mapping = aes(y = group_mean), data = group_means_df,    colour = 'red', size = 3  )# Pattern 2# Same plot as above, passing only the `data` argument into the `ggplot()`# call. The `mapping` arguments are now required in each `geom_point()`# layer because there is no `mapping` argument passed along from the# `ggplot()` call.ggplot(data = sample_df) +  geom_point(mapping = aes(x = group, y = value)) +  geom_point(    mapping = aes(x = group, y = group_mean), data = group_means_df,    colour = 'red', size = 3  )# Pattern 3# Same plot as above, passing neither the `data` or `mapping` arguments# into the `ggplot()` call. Both those arguments are now required in# each `geom_point()` layer. This pattern can be particularly useful when# creating more complex graphics with many layers using data from multiple# data frames.ggplot() +  geom_point(mapping = aes(x = group, y = value), data = sample_df) +  geom_point(    mapping = aes(x = group, y = group_mean), data = group_means_df,    colour = 'red', size = 3  )

Base ggproto classes for ggplot2

Description

If you are creating a new geom, stat, position, or scale in another package,you'll need to extend fromggplot2::Geom,ggplot2::Stat,ggplot2::Position, orggplot2::Scale.

See Also

ggproto


Generate a ggplot2 plot grob.

Description

Generate a ggplot2 plot grob.

Usage

ggplotGrob(x)

Arguments

x

ggplot2 object


Build ggplot for rendering.

Description

build_ggplot() takes the plot object, and performs all steps necessaryto produce an object that can be rendered. This function outputs two pieces:a list of data frames (one for each layer), and a panel object, whichcontain all information about axis limits, breaks etc. Theggplot_build()function is vestigial andbuild_ggplot() should be used instead.

Usage

ggplot_build(plot, ...)get_layer_data(plot = get_last_plot(), i = 1L)layer_data(plot = get_last_plot(), i = 1L)get_panel_scales(plot = get_last_plot(), i = 1L, j = 1L)layer_scales(plot = get_last_plot(), i = 1L, j = 1L)get_layer_grob(plot = get_last_plot(), i = 1L)layer_grob(plot = get_last_plot(), i = 1L)

Arguments

plot

ggplot object

...

Not currently in use.

i

An integer. Inget_layer_data(), the data to return (in the order added to theplot). Inget_layer_grob(), the grob to return (in the order added to theplot). Inget_panel_scales(), the row of a facet to return scales for.

j

An integer. Inget_panel_scales(), the column of a facet to returnscales for.

Details

get_layer_data(),get_layer_grob(), andget_panel_scales() are helperfunctions that return the data, grob, or scales associated with a givenlayer. These are useful for tests.

See Also

print.ggplot() andbenchplot() forfunctions that contain the complete set of steps for generatinga ggplot2 plot.

Thebuild step section of the online ggplot2 book.


Build a plot with all the usual bits and pieces.

Description

This function builds all grobs necessary for displaying the plot, andstores them in a special data structure called agtable.This object is amenable to programmatic manipulation, should you wantto (e.g.) make the legend box 2 cm wide, or combine multiple plots intoa single display, preserving aspect ratios across the plots.

Usage

ggplot_gtable(data)

Arguments

data

plot data generated byggplot_build()

Details

Theggplot_gtable() function is vestigial and thegtable_ggplot() functionshould be used instead.

Value

agtable object

See Also

print.ggplot() andbenchplot() forfor functions that contain the complete set of steps for generatinga ggplot2 plot.

Thegtable step section of the online ggplot2 book.


Create a new ggproto object

Description

Construct a new object withggproto(), test withis_ggproto(),and access parent methods/fields withggproto_parent().

Usage

ggproto(`_class` = NULL, `_inherit` = NULL, ...)ggproto_parent(parent, self)

Arguments

_class

Class name to assign to the object. This is stored as the classattribute of the object. This is optional: ifNULL (the default),no class name will be added to the object.

_inherit

ggproto object to inherit from. IfNULL, don'tinherit from any object.

...

A list of named members in the ggproto object. These can befunctions that become methods of the class or regular objects.

parent,self

Access parent classparent of objectself.

Details

ggproto implements a protype based OO system which blurs the lines betweenclasses and instances. It is inspired by the proto package, but it has someimportant differences. Notably, it cleanly supports cross-packageinheritance, and has faster performance.

In most cases, creating a new OO system to be used by a single package isnot a good idea. However, it was the least-bad solution for ggplot2 becauseit required the fewest changes to an already complex code base.

Calling methods

ggproto methods can take an optionalself argument: if it is present,it is a regular method; if it's absent, it's a "static" method (i.e. itdoesn't use any fields).

Imagine you have a ggproto objectAdder, which has amethodaddx = function(self, n) n + self$x. Then, to call thisfunction, you would useAdder$addx(10) – theself is passedin automatically by the wrapper function.self be located anywherein the function signature, although customarily it comes first.

Calling methods in a parent

To explicitly call a methods in a parent, useggproto_parent(Parent, self).

Working with ggproto classes

The ggproto objects constructed are build on top of environments, which hassome ramifications. Environments do not follow the 'copy on modify' semanticsone might be accustomed to in regular objects. Instead they have'modify in place'semantics.

See Also

Theggproto introduction section of the online ggplot2 book.

Examples

Adder <- ggproto("Adder",  x = 0,  add = function(self, n) {    self$x <- self$x + n    self$x  } )is_ggproto(Adder)Adder$add(10)Adder$add(10)Doubler <- ggproto("Doubler", Adder,  add = function(self, n) {    ggproto_parent(Adder, self)$add(n * 2)  })Doubler$xDoubler$add(10)

Save a ggplot (or other grid object) with sensible defaults

Description

ggsave() is a convenient function for saving a plot. It defaults tosaving the last plot that you displayed, using the size of the currentgraphics device. It also guesses the type of graphics device from theextension.

Usage

ggsave(  filename,  plot = get_last_plot(),  device = NULL,  path = NULL,  scale = 1,  width = NA,  height = NA,  units = c("in", "cm", "mm", "px"),  dpi = 300,  limitsize = TRUE,  bg = NULL,  create.dir = FALSE,  ...)

Arguments

filename

File name to create on disk.

plot

Plot to save, defaults to last plot displayed.

device

Device to use. Can either be a device function(e.g.png), or one of "eps", "ps", "tex" (pictex),"pdf", "jpeg", "tiff", "png", "bmp", "svg" or "wmf" (windows only). IfNULL (default), the device is guessed based on thefilename extension.

path

Path of the directory to save plot to:path andfilenameare combined to create the fully qualified file name. Defaults to theworking directory.

scale

Multiplicative scaling factor.

width,height

Plot size in units expressed by theunits argument.If not supplied, uses the size of the current graphics device.

units

One of the following units in which thewidth andheightarguments are expressed:"in","cm","mm" or"px".

dpi

Plot resolution. Also accepts a string input: "retina" (320),"print" (300), or "screen" (72). Only applies when converting pixel units,as is typical for raster output types.

limitsize

WhenTRUE (the default),ggsave() will notsave images larger than 50x50 inches, to prevent the common error ofspecifying dimensions in pixels.

bg

Background colour. IfNULL, uses theplot.background fill valuefrom the plot theme.

create.dir

Whether to create new directories if a non-existingdirectory is specified in thefilename orpath (TRUE) or return anerror (FALSE, default). IfFALSE and run in an interactive session,a prompt will appear asking to create a new directory when necessary.

...

Other arguments passed on to the graphics device function,as specified bydevice.

Details

Note: Filenames with page numbers can be generated by including a Cinteger format expression, such as⁠%03d⁠ (as in the default file namefor most R graphics devices, see e.g.png()).Thus,filename = "figure%03d.png" will produce successive filenamesfigure001.png,figure002.png,figure003.png, etc. To write a filenamecontaining the⁠%⁠ sign, use%%. For example,filename = "figure-100%%.png"will produce the filename⁠figure-100%.png⁠.

Saving images without ggsave()

In most casesggsave() is the simplest way to save your plot, butsometimes you may wish to save the plot by writing directly to agraphics device. To do this, you can open a regular R graphicsdevice such aspng() orpdf(), print the plot, and then closethe device usingdev.off(). This technique is illustrated in theexamples section.

See Also

Thesaving section of the online ggplot2 book.

Examples

## Not run: ggplot(mtcars, aes(mpg, wt)) +  geom_point()# here, the device is inferred from the filename extensionggsave("mtcars.pdf")ggsave("mtcars.png")# setting dimensions of the plotggsave("mtcars.pdf", width = 4, height = 4)ggsave("mtcars.pdf", width = 20, height = 20, units = "cm")# passing device-specific arguments to '...'ggsave("mtcars.pdf", colormodel = "cmyk")# delete files with base::unlink()unlink("mtcars.pdf")unlink("mtcars.png")# specify device when saving to a file with unknown extension# (for example a server supplied temporary file)file <- tempfile()ggsave(file, device = "pdf")unlink(file)# save plot to file without using ggsavep <-  ggplot(mtcars, aes(mpg, wt)) +  geom_point()png("mtcars.png")print(p)dev.off()## End(Not run)

Complete themes

Description

These are complete themes which control all non-data display. Usetheme() if you just need to tweak the display of an existingtheme.

Usage

theme_grey(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = "white",  accent = "#3366FF")theme_gray(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = "white",  accent = "#3366FF")theme_bw(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = "white",  accent = "#3366FF")theme_linedraw(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = "white",  accent = "#3366FF")theme_light(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = "white",  accent = "#3366FF")theme_dark(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = "white",  accent = "#3366FF")theme_minimal(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = "white",  accent = "#3366FF")theme_classic(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = "white",  accent = "#3366FF")theme_void(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = alpha(ink, 0),  accent = "#3366FF")theme_test(  base_size = 11,  base_family = "",  header_family = NULL,  base_line_size = base_size/22,  base_rect_size = base_size/22,  ink = "black",  paper = "white",  accent = "#3366FF")

Arguments

base_size

base font size, given in pts.

base_family

base font family

header_family

font family for titles and headers. The default,NULL,uses theme inheritance to set the font. This setting affects axis titles,legend titles, the plot title and tag text.

base_line_size

base size for line elements

base_rect_size

base size for rect elements

ink,paper,accent

colour for foreground, background, and accented elements respectively.

Details

theme_gray()

The signature ggplot2 theme with a grey background and white gridlines,designed to put the data forward yet make comparisons easy.

theme_bw()

The classic dark-on-light ggplot2 theme. May work better for presentationsdisplayed with a projector.

theme_linedraw()

A theme with only black lines of various widths on white backgrounds,reminiscent of a line drawing. Serves a purpose similar totheme_bw().Note that this theme has some very thin lines (<< 1 pt) which some journalsmay refuse.

theme_light()

A theme similar totheme_linedraw() but with light grey lines and axes,to direct more attention towards the data.

theme_dark()

The dark cousin oftheme_light(), with similar line sizes but a dark background. Useful to make thin coloured lines pop out.

theme_minimal()

A minimalistic theme with no background annotations.

theme_classic()

A classic-looking theme, with x and y axis lines and no gridlines.

theme_void()

A completely empty theme.

theme_test()

A theme for visual unit tests. It should ideally never change exceptfor new features.

See Also

Thecomplete themes section of the online ggplot2 book.

Examples

mtcars2 <- within(mtcars, {  vs <- factor(vs, labels = c("V-shaped", "Straight"))  am <- factor(am, labels = c("Automatic", "Manual"))  cyl  <- factor(cyl)  gear <- factor(gear)})p1 <- ggplot(mtcars2) +  geom_point(aes(x = wt, y = mpg, colour = gear)) +  labs(    title = "Fuel economy declines as weight increases",    subtitle = "(1973-74)",    caption = "Data from the 1974 Motor Trend US magazine.",    tag = "Figure 1",    x = "Weight (1000 lbs)",    y = "Fuel economy (mpg)",    colour = "Gears"  )p1 + theme_gray() # the defaultp1 + theme_bw()p1 + theme_linedraw()p1 + theme_light()p1 + theme_dark()p1 + theme_minimal()p1 + theme_classic()p1 + theme_void()# Theme examples with panelsp2 <- p1 + facet_grid(vs ~ am)p2 + theme_gray() # the defaultp2 + theme_bw()p2 + theme_linedraw()p2 + theme_light()p2 + theme_dark()p2 + theme_minimal()p2 + theme_classic()p2 + theme_void()

Graphical units

Description

Multiply size in mm by these constants in order to convert to the unitsthat grid uses internally forlwd andfontsize.

Usage

.pt.stroke

Format

An object of classnumeric of length 1.

An object of classnumeric of length 1.


Axis guide

Description

Axis guides are the visual representation of position scales like thosecreated withscale_(x|y)_continuous() andscale_(x|y)_discrete().

Usage

guide_axis(  title = waiver(),  theme = NULL,  check.overlap = FALSE,  angle = waiver(),  n.dodge = 1,  minor.ticks = FALSE,  cap = "none",  order = 0,  position = waiver())

Arguments

title

A character string or expression indicating a title of guide.IfNULL, the title is not shown. By default(waiver()), the name of the scale object or the namespecified inlabs() is used for the title.

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.

check.overlap

silently remove overlapping labels,(recursively) prioritizing the first, last, and middle labels.

angle

Compared to setting the angle intheme() /element_text(),this also uses some heuristics to automatically pick thehjust andvjust thatyou probably want. Can be one of the following:

  • NULL to take the angles andhjust/vjust directly from the theme.

  • waiver() to allow reasonable defaults in special cases.

  • A number representing the text angle in degrees.

n.dodge

The number of rows (for vertical axes) or columns (forhorizontal axes) that should be used to render the labels. This isuseful for displaying labels that would otherwise overlap.

minor.ticks

Whether to draw the minor ticks (TRUE) or not drawminor ticks (FALSE, default).

cap

Acharacter to cut the axis line back to the last breaks. Canbe"none" (default) to draw the axis line along the whole panel, or"upper" and"lower" to draw the axis to the upper or lower break, or"both" to only draw the line in between the most extreme breaks.TRUEandFALSE are shorthand for"both" and"none" respectively.

order

A positiveinteger of length 1 that specifies the order ofthis guide among multiple guides. This controls in which order guides aremerged if there are multiple guides for the same position. If 0 (default),the order is determined by a secret algorithm.

position

Where this guide should be drawn: one of top, bottom,left, or right.

Examples

# plot with overlapping textp <- ggplot(mpg, aes(cty * 100, hwy * 100)) +  geom_point() +  facet_wrap(vars(class))# axis guides can be customized in the scale_* functions or# using guides()p + scale_x_continuous(guide = guide_axis(n.dodge = 2))p + guides(x = guide_axis(angle = 90))# can also be used to add a duplicate guidep + guides(x = guide_axis(n.dodge = 2), y.sec = guide_axis())

Axis with logarithmic tick marks

Description

This axis guide replaces the placement of ticks marks at intervals inlog10 space.

Usage

guide_axis_logticks(  long = 2.25,  mid = 1.5,  short = 0.75,  prescale.base = NULL,  negative.small = NULL,  short.theme = element_line(),  expanded = TRUE,  cap = "none",  theme = NULL,  prescale_base = deprecated(),  negative_small = deprecated(),  short_theme = deprecated(),  ...)

Arguments

long,mid,short

Agrid::unit() object orrel() object settingthe (relative) length of the long, middle and short ticks. Numeric valuesare interpreted asrel() objects. Therel() values are used to multiplyvalues of theaxis.ticks.length theme setting.

prescale.base

Base of logarithm used to transform data manually. Thedefault,NULL, will use the scale transformation to calculate positions.Only setprescale.base if the data has already been log-transformed.When using a log-transform in the position scale or incoord_transform(),keep the defaultNULL argument.

negative.small

When the scale limits include 0 or negative numbers,what should be the smallest absolute value that is marked with a tick?IfNULL (default), will be the smallest of 0.1 or 0.1 times the absolutescale maximum.

short.theme

A themeelement for customising thedisplay of the shortest ticks. Must be a line or blank element, andit inherits from theaxis.minor.ticks setting for the relevant position.

expanded

Whether the ticks should cover the range after scaleexpansion (TRUE, default), or be restricted to the scale limits(FALSE).

cap

Acharacter to cut the axis line back to the last breaks. Canbe"none" (default) to draw the axis line along the whole panel, or"upper" and"lower" to draw the axis to the upper or lower break, or"both" to only draw the line in between the most extreme breaks.TRUEandFALSE are shorthand for"both" and"none" respectively.

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.

prescale_base,negative_small,short_theme

[Deprecated]

...

Arguments passed on toguide_axis

check.overlap

silently remove overlapping labels,(recursively) prioritizing the first, last, and middle labels.

angle

Compared to setting the angle intheme() /element_text(),this also uses some heuristics to automatically pick thehjust andvjust thatyou probably want. Can be one of the following:

  • NULL to take the angles andhjust/vjust directly from the theme.

  • waiver() to allow reasonable defaults in special cases.

  • A number representing the text angle in degrees.

n.dodge

The number of rows (for vertical axes) or columns (forhorizontal axes) that should be used to render the labels. This isuseful for displaying labels that would otherwise overlap.

order

A positiveinteger of length 1 that specifies the order ofthis guide among multiple guides. This controls in which order guides aremerged if there are multiple guides for the same position. If 0 (default),the order is determined by a secret algorithm.

position

Where this guide should be drawn: one of top, bottom,left, or right.

title

A character string or expression indicating a title of guide.IfNULL, the title is not shown. By default(waiver()), the name of the scale object or the namespecified inlabs() is used for the title.

Examples

# A standard plotp <- ggplot(msleep, aes(bodywt, brainwt)) +  geom_point(na.rm = TRUE)# The logticks axis works well with log scalesp + scale_x_log10(guide = "axis_logticks") +  scale_y_log10(guide = "axis_logticks")# Or with log-transformed coordinatesp + coord_transform(x = "log10", y = "log10") +  guides(x = "axis_logticks", y = "axis_logticks")# When data is transformed manually, one should provide `prescale.base`# Keep in mind that this axis uses log10 space for placement, not log2p + aes(x = log2(bodywt), y = log10(brainwt)) +  guides(    x = guide_axis_logticks(prescale.base = 2),    y = guide_axis_logticks(prescale.base = 10)  )# A plot with both positive and negative extremes, pseudo-log transformedset.seed(42)p2 <- ggplot(data.frame(x = rcauchy(1000)), aes(x = x)) +  geom_density() +  scale_x_continuous(    breaks = c(-10^(4:0), 0, 10^(0:4)),    transform = "pseudo_log"  )# The log ticks are mirrored when 0 is includedp2 + guides(x = "axis_logticks")# To control the tick density around 0, one can set `negative.small`p2 + guides(x = guide_axis_logticks(negative.small = 1))

Stacked axis guides

Description

This guide can stack other position guides that represent position scales,like those created withscale_(x|y)_continuous() andscale_(x|y)_discrete().

Usage

guide_axis_stack(  first = "axis",  ...,  title = waiver(),  theme = NULL,  spacing = NULL,  order = 0,  position = waiver())

Arguments

first

A position guide given as one of the following:

  • A string, for example"axis".

  • A call to a guide function, for exampleguide_axis().

...

Additional guides to stack given in the same manner asfirst.

title

A character string or expression indicating a title of guide.IfNULL, the title is not shown. By default(waiver()), the name of the scale object or the namespecified inlabs() is used for the title.

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.

spacing

Aunit() objects that determines how far separate guides arespaced apart.

order

A positiveinteger of length 1 that specifies the order ofthis guide among multiple guides. This controls in which order guides aremerged if there are multiple guides for the same position. If 0 (default),the order is determined by a secret algorithm.

position

Where this guide should be drawn: one of top, bottom,left, or right.

Details

Thefirst guide will be placed closest to the panel and any subsequentguides provided through... will follow in the given order.

Examples

# A standard plotp <- ggplot(mpg, aes(displ, hwy)) +  geom_point() +  theme(axis.line = element_line())# A normal axis first, then a capped axisp + guides(x = guide_axis_stack("axis", guide_axis(cap = "both")))

Angle axis guide

Description

This is a specialised guide used incoord_radial() to represent the thetaposition scale.

Usage

guide_axis_theta(  title = waiver(),  theme = NULL,  angle = waiver(),  minor.ticks = FALSE,  cap = "none",  order = 0,  position = waiver())

Arguments

title

A character string or expression indicating a title of guide.IfNULL, the title is not shown. By default(waiver()), the name of the scale object or the namespecified inlabs() is used for the title.

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.

angle

Compared to setting the angle intheme() /element_text(),this also uses some heuristics to automatically pick thehjust andvjust thatyou probably want. Can be one of the following:

  • NULL to take the angles andhjust/vjust directly from the theme.

  • waiver() to allow reasonable defaults in special cases.

  • A number representing the text angle in degrees.

minor.ticks

Whether to draw the minor ticks (TRUE) or not drawminor ticks (FALSE, default).

cap

Acharacter to cut the axis line back to the last breaks. Canbe"none" (default) to draw the axis line along the whole panel, or"upper" and"lower" to draw the axis to the upper or lower break, or"both" to only draw the line in between the most extreme breaks.TRUEandFALSE are shorthand for"both" and"none" respectively.

order

A positiveinteger of length 1 that specifies the order ofthis guide among multiple guides. This controls in which order guides aremerged if there are multiple guides for the same position. If 0 (default),the order is determined by a secret algorithm.

position

Where this guide should be drawn: one of top, bottom,left, or right.

Note

The axis labels in this guide are insensitive tohjust andvjustsettings. The distance from the tick marks to the labels is determined bythe largestmargin size set in the theme.

Examples

# A plot using coord_radialp <- ggplot(mtcars, aes(disp, mpg)) +  geom_point() +  coord_radial()# The `angle` argument can be used to set relative anglesp + guides(theta = guide_axis_theta(angle = 0))

A binned version of guide_legend

Description

This guide is a version of theguide_legend() guide for binned scales. Itdiffers in that it places ticks correctly between the keys, and sports asmall axis to better show the binning. Likeguide_legend() it can be usedfor all non-position aesthetics though colour and fill defaults toguide_coloursteps(), and it will merge aesthetics together into the sameguide if they are mapped in the same way.

Usage

guide_bins(  title = waiver(),  theme = NULL,  angle = NULL,  position = NULL,  direction = NULL,  override.aes = list(),  reverse = FALSE,  order = 0,  show.limits = NULL,  ...)

Arguments

title

A character string or expression indicating a title of guide.IfNULL, the title is not shown. By default(waiver()), the name of the scale object or the namespecified inlabs() is used for the title.

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.Arguments that apply to a single legend are respected, most of which havethelegend-prefix. Arguments that apply to combined legends(the legend box) are ignored, includinglegend.position,⁠legend.justification.*⁠,legend.location and⁠legend.box.*⁠.

angle

Overrules the theme settings to automatically apply appropriatehjust andvjust for angled legend text. Can be a single numberrepresenting the text angle in degrees, orNULL to not overrule thesettings (default).

position

A character string indicating where the legend should beplaced relative to the plot panels.One of "top", "right", "bottom", "left", or "inside".

direction

A character string indicating the direction of the guide.One of "horizontal" or "vertical".

override.aes

A list specifying aesthetic parameters of legend key.See details and examples.

reverse

logical. IfTRUE the order of legends is reversed.

order

positive integer less than 99 that specifies the order ofthis guide among multiple guides. This controls the order in whichmultiple guides are displayed, not the contents of the guide itself.If 0 (default), the order is determined by a secret algorithm.

show.limits

Logical. Should the limits of the scale be shown withlabels and ticks. Default isNULL meaning it will take the value from thescale. This argument is ignored iflabels is given as a vector ofvalues. If one or both of the limits is also given inbreaks it will beshown irrespective of the value ofshow.limits.

...

ignored.

Value

A guide object

Use with discrete scale

This guide is intended to show binned data and work together with ggplot2'sbinning scales. However, it is sometimes desirable to perform the binning ina separate step, either as part of a stat (e.g.stat_contour_filled()) orprior to the visualisation. If you want to use this guide for discrete datathe levels must follow the naming scheme implemented bybase::cut(). Thismeans that a bin must be encoded as"(<lower>, <upper>]" with⁠<lower>⁠giving the lower bound of the bin and⁠<upper>⁠ giving the upper bound("[<lower>, <upper>)" is also accepted). If you usebase::cut() toperform the binning everything should work as expected, if not, some recodingmay be needed.

See Also

Other guides:guide_colourbar(),guide_coloursteps(),guide_legend(),guides()

Examples

p <- ggplot(mtcars) +  geom_point(aes(disp, mpg, size = hp)) +  scale_size_binned()# Standard lookp# Remove the axis or style itp + guides(size = guide_bins(  theme = theme(legend.axis.line = element_blank())))p + guides(size = guide_bins(show.limits = TRUE))my_arrow <- arrow(length = unit(1.5, "mm"), ends = "both")p + guides(size = guide_bins(  theme = theme(legend.axis.line = element_line(arrow = my_arrow))))# Guides are merged together if possibleggplot(mtcars) +  geom_point(aes(disp, mpg, size = hp, colour = hp)) +  scale_size_binned() +  scale_colour_binned(guide = "bins")

Continuous colour bar guide

Description

Colour bar guide shows continuous colour scales mapped onto values.Colour bar is available withscale_fill andscale_colour.

Usage

guide_colourbar(  title = waiver(),  theme = NULL,  nbin = NULL,  display = "raster",  raster = deprecated(),  alpha = NA,  draw.ulim = TRUE,  draw.llim = TRUE,  angle = NULL,  position = NULL,  direction = NULL,  reverse = FALSE,  order = 0,  available_aes = c("colour", "color", "fill"),  ...)guide_colorbar(  title = waiver(),  theme = NULL,  nbin = NULL,  display = "raster",  raster = deprecated(),  alpha = NA,  draw.ulim = TRUE,  draw.llim = TRUE,  angle = NULL,  position = NULL,  direction = NULL,  reverse = FALSE,  order = 0,  available_aes = c("colour", "color", "fill"),  ...)

Arguments

title

A character string or expression indicating a title of guide.IfNULL, the title is not shown. By default(waiver()), the name of the scale object or the namespecified inlabs() is used for the title.

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.Arguments that apply to a single legend are respected, most of which havethelegend-prefix. Arguments that apply to combined legends(the legend box) are ignored, includinglegend.position,⁠legend.justification.*⁠,legend.location and⁠legend.box.*⁠.

nbin

A numeric specifying the number of bins for drawing thecolourbar. A smoother colourbar results from a larger value.

display

A string indicating a method to display the colourbar. Can beone of the following:

  • "raster" to display as a bitmap image.

  • "rectangles" to display as a series of rectangles.

  • "gradient" to display as a linear gradient.

Note that not all devices are able to render rasters and gradients.

raster

[Deprecated] A logical. IfTRUE thenthe colourbar is rendered as a raster object. IfFALSE then the colourbaris rendered as a set of rectangles. Note that not all graphics devices arecapable of rendering raster image.

alpha

A numeric between 0 and 1 setting the colour transparency ofthe bar. UseNA to preserve the alpha encoded in the colour itself(default).

draw.ulim

A logical specifying if the upper limit tick marks shouldbe visible.

draw.llim

A logical specifying if the lower limit tick marks shouldbe visible.

angle

Overrules the theme settings to automatically apply appropriatehjust andvjust for angled legend text. Can be a single numberrepresenting the text angle in degrees, orNULL to not overrule thesettings (default).

position

A character string indicating where the legend should beplaced relative to the plot panels.One of "top", "right", "bottom", "left", or "inside".

direction

A character string indicating the direction of the guide.One of "horizontal" or "vertical."

reverse

logical. IfTRUE the colourbar is reversed. By default,the highest value is on the top and the lowest value is on the bottom

order

positive integer less than 99 that specifies the order ofthis guide among multiple guides. This controls the order in whichmultiple guides are displayed, not the contents of the guide itself.If 0 (default), the order is determined by a secret algorithm.

available_aes

A vector of character strings listing the aestheticsfor which a colourbar can be drawn.

...

ignored.

Details

Guides can be specified in each⁠scale_*⁠ or inguides().guide="legend" in⁠scale_*⁠ is syntactic sugar forguide=guide_legend() (e.g.scale_colour_manual(guide = "legend")).As for how to specify the guide for each scale in more detail,seeguides().

Thelegend.ticks.length theme option can be set to a length 2 unit tocontrol ticks at the right/bottom and left/top sides independently.

Value

A guide object

See Also

Thecontinuous legend section of the online ggplot2 book.

Other guides:guide_bins(),guide_coloursteps(),guide_legend(),guides()

Examples

df <- expand.grid(X1 = 1:10, X2 = 1:10)df$value <- df$X1 * df$X2p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))p2 <- p1 + geom_point(aes(size = value))# Basic formp1 + scale_fill_continuous(guide = "colourbar")p1 + scale_fill_continuous(guide = guide_colourbar())p1 + guides(fill = guide_colourbar())# Control styles# bar sizep1 + guides(fill = guide_colourbar(theme = theme(  legend.key.width  = unit(0.5, "lines"),  legend.key.height = unit(10, "lines"))))# no labelp1 + guides(fill = guide_colourbar(theme = theme(  legend.text = element_blank())))# no tick marksp1 + guides(fill = guide_colourbar(theme = theme(  legend.ticks = element_blank())))# label positionp1 + guides(fill = guide_colourbar(theme = theme(  legend.text.position = "left")))# label themep1 + guides(fill = guide_colourbar(theme = theme(  legend.text = element_text(colour = "blue", angle = 0))))# small number of binsp1 + guides(fill = guide_colourbar(nbin = 3))# large number of binsp1 + guides(fill = guide_colourbar(nbin = 100))# make top- and bottom-most ticks invisiblep1 +  scale_fill_continuous(    limits = c(0,20), breaks = c(0, 5, 10, 15, 20),    guide = guide_colourbar(nbin = 100, draw.ulim = FALSE, draw.llim = FALSE)  )# guides can be controlled independentlyp2 +  scale_fill_continuous(guide = "colourbar") +  scale_size(guide = "legend")p2 + guides(fill = "colourbar", size = "legend")p2 +  scale_fill_continuous(guide = guide_colourbar(theme = theme(    legend.direction = "horizontal"  ))) +  scale_size(guide = guide_legend(theme = theme(    legend.direction = "vertical"  )))

Discretized colourbar guide

Description

This guide is version ofguide_colourbar() for binned colour and fillscales. It shows areas between breaks as a single constant colour instead ofthe gradient known from the colourbar counterpart.

Usage

guide_coloursteps(  title = waiver(),  theme = NULL,  alpha = NA,  angle = NULL,  even.steps = TRUE,  show.limits = NULL,  direction = NULL,  position = NULL,  reverse = FALSE,  order = 0,  available_aes = c("colour", "color", "fill"),  ...)guide_colorsteps(  title = waiver(),  theme = NULL,  alpha = NA,  angle = NULL,  even.steps = TRUE,  show.limits = NULL,  direction = NULL,  position = NULL,  reverse = FALSE,  order = 0,  available_aes = c("colour", "color", "fill"),  ...)

Arguments

title

A character string or expression indicating a title of guide.IfNULL, the title is not shown. By default(waiver()), the name of the scale object or the namespecified inlabs() is used for the title.

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.Arguments that apply to a single legend are respected, most of which havethelegend-prefix. Arguments that apply to combined legends(the legend box) are ignored, includinglegend.position,⁠legend.justification.*⁠,legend.location and⁠legend.box.*⁠.

alpha

A numeric between 0 and 1 setting the colour transparency ofthe bar. UseNA to preserve the alpha encoded in the colour itself(default).

angle

Overrules the theme settings to automatically apply appropriatehjust andvjust for angled legend text. Can be a single numberrepresenting the text angle in degrees, orNULL to not overrule thesettings (default).

even.steps

Should the rendered size of the bins be equal, or shouldthey be proportional to their length in the data space? Defaults toTRUE

show.limits

Logical. Should the limits of the scale be shown withlabels and ticks. Default isNULL meaning it will take the value from thescale. This argument is ignored iflabels is given as a vector ofvalues. If one or both of the limits is also given inbreaks it will beshown irrespective of the value ofshow.limits.

direction

A character string indicating the direction of the guide.One of "horizontal" or "vertical."

position

A character string indicating where the legend should beplaced relative to the plot panels.One of "top", "right", "bottom", "left", or "inside".

reverse

logical. IfTRUE the colourbar is reversed. By default,the highest value is on the top and the lowest value is on the bottom

order

positive integer less than 99 that specifies the order ofthis guide among multiple guides. This controls the order in whichmultiple guides are displayed, not the contents of the guide itself.If 0 (default), the order is determined by a secret algorithm.

available_aes

A vector of character strings listing the aestheticsfor which a colourbar can be drawn.

...

ignored.

Value

A guide object

Use with discrete scale

This guide is intended to show binned data and work together with ggplot2'sbinning scales. However, it is sometimes desirable to perform the binning ina separate step, either as part of a stat (e.g.stat_contour_filled()) orprior to the visualisation. If you want to use this guide for discrete datathe levels must follow the naming scheme implemented bybase::cut(). Thismeans that a bin must be encoded as"(<lower>, <upper>]" with⁠<lower>⁠giving the lower bound of the bin and⁠<upper>⁠ giving the upper bound("[<lower>, <upper>)" is also accepted). If you usebase::cut() toperform the binning everything should work as expected, if not, some recodingmay be needed.

See Also

Thebinned legend section of the online ggplot2 book.

Other guides:guide_bins(),guide_colourbar(),guide_legend(),guides()

Examples

df <- expand.grid(X1 = 1:10, X2 = 1:10)df$value <- df$X1 * df$X2p <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))# Coloursteps guide is the default for binned colour scalesp + scale_fill_binned()# By default each bin in the guide is the same size irrespectively of how# their sizes relate in data spacep + scale_fill_binned(breaks = c(10, 25, 50))# This can be changed with the `even.steps` argumentp + scale_fill_binned(  breaks = c(10, 25, 50),  guide = guide_coloursteps(even.steps = FALSE))# By default the limits is not shown, but this can be changedp + scale_fill_binned(guide = guide_coloursteps(show.limits = TRUE))# (can also be set in the scale)p + scale_fill_binned(show.limits = TRUE)

Custom guides

Description

This is a special guide that can be used to display any graphical object(grob) along with the regular guides. This guide has no associated scale.

Usage

guide_custom(  grob,  width = grobWidth(grob),  height = grobHeight(grob),  title = NULL,  theme = NULL,  position = NULL,  order = 0)

Arguments

grob

A grob to display.

width,height

The allocated width and height to display the grob, giveningrid::unit()s.

title

A character string or expression indicating the title of guide.IfNULL (default), no title is shown.

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.Arguments that apply to a single legend are respected, most of which havethelegend-prefix. Arguments that apply to combined legends(the legend box) are ignored, includinglegend.position,⁠legend.justification.*⁠,legend.location and⁠legend.box.*⁠.

position

A character string indicating where the legend should beplaced relative to the plot panels.One of "top", "right", "bottom", "left", or "inside".

order

positive integer less than 99 that specifies the order ofthis guide among multiple guides. This controls the order in whichmultiple guides are displayed, not the contents of the guide itself.If 0 (default), the order is determined by a secret algorithm.

Examples

# A standard plotp <- ggplot(mpg, aes(displ, hwy)) +  geom_point()# Define a graphical objectcircle <- grid::circleGrob()# Rendering a grob as a guidep + guides(custom = guide_custom(circle, title = "My circle"))# Controlling the size of the grob defined in relative unitsp + guides(custom = guide_custom(  circle, title = "My circle",  width = unit(2, "cm"), height = unit(2, "cm")))# Size of grobs in absolute units is taken directly without the need to# set these manuallyp + guides(custom = guide_custom(  title = "My circle",  grob = grid::circleGrob(r = unit(1, "cm"))))

Legend guide

Description

Legend type guide shows key (i.e., geoms) mapped onto values.Legend guides for various scales are integrated if possible.

Usage

guide_legend(  title = waiver(),  theme = NULL,  position = NULL,  direction = NULL,  override.aes = list(),  nrow = NULL,  ncol = NULL,  reverse = FALSE,  order = 0,  ...)

Arguments

title

A character string or expression indicating a title of guide.IfNULL, the title is not shown. By default(waiver()), the name of the scale object or the namespecified inlabs() is used for the title.

theme

Atheme object to style the guide individually ordifferently from the plot's theme settings. Thetheme argument in theguide partially overrides, and is combined with, the plot's theme.Arguments that apply to a single legend are respected, most of which havethelegend-prefix. Arguments that apply to combined legends(the legend box) are ignored, includinglegend.position,⁠legend.justification.*⁠,legend.location and⁠legend.box.*⁠.

position

A character string indicating where the legend should beplaced relative to the plot panels.One of "top", "right", "bottom", "left", or "inside".

direction

A character string indicating the direction of the guide.One of "horizontal" or "vertical".

override.aes

A list specifying aesthetic parameters of legend key.See details and examples.

nrow,ncol

The desired number of rows and column of legendsrespectively.

reverse

logical. IfTRUE the order of legends is reversed.

order

positive integer less than 99 that specifies the order ofthis guide among multiple guides. This controls the order in whichmultiple guides are displayed, not the contents of the guide itself.If 0 (default), the order is determined by a secret algorithm.

...

ignored.

Details

Guides can be specified in each⁠scale_*⁠ or inguides().guide = "legend" in⁠scale_*⁠ is syntactic sugar forguide = guide_legend() (e.g.scale_color_manual(guide = "legend")).As for how to specify the guide for each scale in more detail,seeguides().

See Also

Thelegends section of the online ggplot2 book.

Other guides:guide_bins(),guide_colourbar(),guide_coloursteps(),guides()

Examples

df <- expand.grid(X1 = 1:10, X2 = 1:10)df$value <- df$X1 * df$X2p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))p2 <- p1 + geom_point(aes(size = value))# Basic formp1 + scale_fill_continuous(guide = guide_legend())# Control styles# title positionp1 + guides(fill = guide_legend(  title = "LEFT", theme(legend.title.position = "left")))# title text styles via element_textp1 + guides(fill = guide_legend(theme = theme(  legend.title = element_text(size = 15, face = "italic", colour = "red"))))# label positionp1 + guides(fill = guide_legend(theme = theme(  legend.text.position = "left",  legend.text = element_text(hjust = 1))))# label stylesp1 +  scale_fill_continuous(    breaks = c(5, 10, 15),    labels = paste("long", c(5, 10, 15)),    guide = guide_legend(theme = theme(      legend.direction = "horizontal",      legend.title.position = "top",      legend.text.position = "bottom",      legend.text = element_text(hjust = 0.5, vjust = 1, angle = 90)    ))  )# Set aesthetic of legend key# very low alpha value make it difficult to see legend keyp3 <- ggplot(mtcars, aes(vs, am, colour = factor(cyl))) +  geom_jitter(alpha = 1/5, width = 0.01, height = 0.01)p3# override.aes overwrites the alphap3 + guides(colour = guide_legend(override.aes = list(alpha = 1)))# multiple row/col legendsdf <- data.frame(x = 1:20, y = 1:20, color = letters[1:20])p <- ggplot(df, aes(x, y)) +  geom_point(aes(colour = color))p + guides(col = guide_legend(nrow = 8))p + guides(col = guide_legend(ncol = 8))p + guides(col = guide_legend(nrow = 8, theme = theme(legend.byrow = TRUE)))# reversed order legendp + guides(col = guide_legend(reverse = TRUE))

Empty guide

Description

This guide draws nothing.

Usage

guide_none(title = waiver(), position = waiver())

Arguments

title

A character string or expression indicating a title of guide.IfNULL, the title is not shown. By default(waiver()), the name of the scale object or the namespecified inlabs() is used for the title.

position

Where this guide should be drawn: one of top, bottom,left, or right.


Set guides for each scale

Description

Guides for each scale can be set scale-by-scale with theguideargument, or en masse withguides().

Usage

guides(...)

Arguments

...

List of scale name-guide pairs. The guide can eitherbe a string (i.e. "colorbar" or "legend"), or a call to a guide function(i.e.guide_colourbar() orguide_legend())specifying additional arguments.

Value

A list containing the mapping between scale and guide.

See Also

Other guides:guide_bins(),guide_colourbar(),guide_coloursteps(),guide_legend()

Examples

# ggplot objectdat <- data.frame(x = 1:5, y = 1:5, p = 1:5, q = factor(1:5), r = factor(1:5))p <-  ggplot(dat, aes(x, y, colour = p, size = q, shape = r)) +  geom_point()# without guide specificationp# Show colorbar guide for colour.# All these examples below have a same effect.p + guides(colour = "colorbar", size = "legend", shape = "legend")p + guides(colour = guide_colorbar(), size = guide_legend(),  shape = guide_legend())p + scale_colour_continuous(guide = "colorbar") + scale_size_discrete(guide = "legend") + scale_shape(guide = "legend") # Remove some guides p + guides(colour = "none") p + guides(colour = "colorbar",size = "none")# Guides are integrated where possiblep +  guides(    colour = guide_legend("title"),    size = guide_legend("title"),    shape = guide_legend("title") )# same asg <- guide_legend("title")p + guides(colour = g, size = g, shape = g)p + theme(legend.position = "bottom")# position of guides# Set order for multiple guidesggplot(mpg, aes(displ, cty)) +  geom_point(aes(size = hwy, colour = cyl, shape = drv)) +  guides(   colour = guide_colourbar(order = 1),   shape = guide_legend(order = 2),   size = guide_legend(order = 3) )

A selection of summary functions from Hmisc

Description

These are wrappers around functions fromHmisc designed to make themeasier to use withstat_summary(). See the Hmisc documentationfor more details:

Usage

mean_cl_boot(x, ...)mean_cl_normal(x, ...)mean_sdl(x, ...)median_hilow(x, ...)

Arguments

x

a numeric vector

...

other arguments passed on to the respective Hmisc function.

Value

A data frame with columnsy,ymin, andymax.

Examples

if (requireNamespace("Hmisc", quietly = TRUE)) {set.seed(1)x <- rnorm(100)mean_cl_boot(x)mean_cl_normal(x)mean_sdl(x)median_hilow(x)}

Ignoring and exposing data

Description

The.ignore_data() function is used to hide⁠<AsIs>⁠ columns duringscale interactions inggplot_build(). The.expose_data() function isused to restore hidden columns.

Usage

.ignore_data(data).expose_data(data)

Arguments

data

A list of⁠<data.frame>⁠s.

Value

A modified list of⁠<data.frame>s⁠

Examples

data <- list(  data.frame(x = 1:3, y = I(1:3)),  data.frame(w = I(1:3), z = 1:3))ignored <- .ignore_data(data)str(ignored).expose_data(ignored)

Reports wetherx is a type of object

Description

Reports wetherx is a type of object

Usage

is_ggproto(x)is.ggproto(x) # Deprecatedis_mapping(x)is_geom(x)is_layer(x)is_coord(x)is.Coord(x) # Deprecatedis_facet(x)is.facet(x) # Deprecatedis_stat(x)is_margin(x)is_theme_element(x, type = "any")is_guide(x)is_guides(x)is_ggplot(x)is.ggplot(x) # Deprecatedis_position(x)is_scale(x)is_theme(x)is.theme(x) # Deprecated

Arguments

x

An object to test

type

For testing elements: the type of element to expect. One of"blank","rect","line","text","polygon","point" or"geom".


Reports whether x is a rel object

Description

Reports whether x is a rel object

Usage

is_rel(x)

Arguments

x

An object to test


Label with mathematical expressions

Description

label_bquote() offers a flexible way of labellingfacet rows or columns with plotmath expressions. Backquotedvariables will be replaced with their value in the facet.

Usage

label_bquote(rows = NULL, cols = NULL, default)

Arguments

rows

Backquoted labelling expression for rows.

cols

Backquoted labelling expression for columns.

default

Unused, kept for compatibility.

See Also

labellers,labeller(),

Examples

# The variables mentioned in the plotmath expression must be# backquoted and referred to by their names.p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()p + facet_grid(vs ~ ., labeller = label_bquote(alpha ^ .(vs)))p + facet_grid(. ~ vs, labeller = label_bquote(cols = .(vs) ^ .(vs)))p + facet_grid(. ~ vs + am, labeller = label_bquote(cols = .(am) ^ .(vs)))

Construct labelling specification

Description

This function makes it easy to assign different labellers todifferent factors. The labeller can be a function or it can be anamed character vector that will serve as a lookup table.

Usage

labeller(  ...,  .rows = NULL,  .cols = NULL,  keep.as.numeric = deprecated(),  .multi_line = TRUE,  .default = label_value)

Arguments

...

Named arguments of the formvariable = labeller. Each labeller is passed toas_labeller()and can be a lookup table, a function taking and returningcharacter vectors, or simply a labeller function.

.rows,.cols

Labeller for a whole margin (either the rows orthe columns). It is passed toas_labeller(). When amargin-wide labeller is set, make sure you don't mention in... any variable belonging to the margin.

keep.as.numeric

[Deprecated] All suppliedlabellers and on-labeller functions should be able to work with characterlabels.

.multi_line

Whether to display the labels of multiplefactors on separate lines. This is passed to the labellerfunction.

.default

Default labeller for variables not specified. Alsoused with lookup tables or non-labeller functions.

Details

In case of functions, if the labeller has classlabeller, itis directly applied on the data frame of labels. Otherwise, it isapplied to the columns of the data frame of labels. The data frameis then processed with the function specified in the.default argument. This is intended to be used withfunctions taking a character vector such asHmisc::capitalize().

Value

A labeller function to supply tofacet_grid() orfacet_wrap()for the argumentlabeller.

See Also

as_labeller(),labellers

Examples

p1 <- ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point()# You can assign different labellers to variables:p1 + facet_grid(  vs + am ~ gear,  labeller = labeller(vs = label_both, am = label_value))# Or whole margins:p1 + facet_grid(  vs + am ~ gear,  labeller = labeller(.rows = label_both, .cols = label_value))# You can supply functions operating on strings:capitalize <- function(string) {  substr(string, 1, 1) <- toupper(substr(string, 1, 1))  string}p2 <- ggplot(msleep, aes(x = sleep_total, y = awake)) + geom_point()p2 + facet_grid(vore ~ conservation, labeller = labeller(vore = capitalize))# Or use character vectors as lookup tables:conservation_status <- c(  cd = "Conservation Dependent",  en = "Endangered",  lc = "Least concern",  nt = "Near Threatened",  vu = "Vulnerable",  domesticated = "Domesticated")## Source: http://en.wikipedia.org/wiki/Wikipedia:Conservation_statusp2 + facet_grid(vore ~ conservation, labeller = labeller(  .default = capitalize,  conservation = conservation_status))# In the following example, we rename the levels to the long form,# then apply a wrap labeller to the columns to prevent cropped textidx <- match(msleep$conservation, names(conservation_status))msleep$conservation2 <- conservation_status[idx]p3 <- ggplot(msleep, aes(x = sleep_total, y = awake)) + geom_point()p3 +  facet_grid(vore ~ conservation2,    labeller = labeller(conservation2 = label_wrap_gen(10))  )# labeller() is especially useful to act as a global labeller. You# can set it up once and use it on a range of different plots with# different facet specifications.global_labeller <- labeller(  vore = capitalize,  conservation = conservation_status,  conservation2 = label_wrap_gen(10),  .default = label_both)p2 + facet_grid(vore ~ conservation, labeller = global_labeller)p3 + facet_wrap(~conservation2, labeller = global_labeller)

Useful labeller functions

Description

Labeller functions are in charge of formatting the strip labels offacet grids and wraps. Most of them accept amulti_lineargument to control whether multiple factors (defined in formulaesuch as~first + second) should be displayed on a singleline separated with commas, or each on their own line.

Usage

label_value(labels, multi_line = TRUE)label_both(labels, multi_line = TRUE, sep = ": ")label_context(labels, multi_line = TRUE, sep = ": ")label_parsed(labels, multi_line = TRUE)label_wrap_gen(width = 25, multi_line = TRUE)

Arguments

labels

Data frame of labels. Usually contains only oneelement, but faceting over multiple factors entails multiplelabel variables.

multi_line

Whether to display the labels of multiple factorson separate lines.

sep

String separating variables and values.

width

Maximum number of characters before wrapping the strip.

Details

label_value() only displays the value of a factor whilelabel_both() displays both the variable name and the factorvalue.label_context() is context-dependent and useslabel_value() for single factor faceting andlabel_both() when multiple factors areinvolved.label_wrap_gen() usesbase::strwrap()for line wrapping.

label_parsed() interprets the labels as plotmathexpressions.label_bquote() offers a more flexibleway of constructing plotmath expressions. See examples andbquote() for details on the syntax of theargument.

Writing New Labeller Functions

Note that an easy way to write a labeller function is totransform a function operating on character vectors withas_labeller().

A labeller function accepts a data frame of labels (charactervectors) containing one column for each factor. Multiple factorsoccur with formula of the type~first + second.

The return value must be a rectangular list where each 'row'characterises a single facet. The list elements can be eithercharacter vectors or lists of plotmath expressions. When multipleelements are returned, they get displayed on their own new lines(i.e., each facet gets a multi-line strip of labels).

To illustrate, let's say your labeller returns a list of twocharacter vectors of length 3. This is a rectangular list becauseall elements have the same length. The first facet will get thefirst elements of each vector and display each of them on theirown line. Then the second facet gets the second elements of eachvector, and so on.

If it's useful to your labeller, you can retrieve thetypeattribute of the incoming data frame of labels. The value of thisattribute reflects the kind of strips your labeller is dealingwith:"cols" for columns and"rows" for rows. Notethatfacet_wrap() has columns by default and rowswhen the strips are switched with theswitch option. Thefacet attribute also provides metadata on the labels. Ittakes the values"grid" or"wrap".

For compatibility withlabeller(), each labellerfunction must have thelabeller S3 class.

See Also

labeller(),as_labeller(),label_bquote()

Examples

mtcars$cyl2 <- factor(mtcars$cyl, labels = c("alpha", "beta", "gamma"))p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()# The default is label_valuep + facet_grid(. ~ cyl, labeller = label_value)# Displaying both the values and the variablesp + facet_grid(. ~ cyl, labeller = label_both)# Displaying only the values or both the values and variables# depending on whether multiple factors are facetted overp + facet_grid(am ~ vs+cyl, labeller = label_context)# Interpreting the labels as plotmath expressionsp + facet_grid(. ~ cyl2)p + facet_grid(. ~ cyl2, labeller = label_parsed)# Include optional argument in label functionp + facet_grid(. ~ cyl, labeller = \(x) label_both(x, sep = "="))

Modify axis, legend, and plot labels

Description

Good labels are critical for making your plots accessible to a wideraudience. Always ensure the axis and legend labels display the fullvariable name. Use the plottitle andsubtitle to explain themain findings. It's common to use thecaption to provide informationabout the data source.tag can be used for adding identification tagsto differentiate between multiple plots.

[Superseded]:xlab(),ylab() andggtitle() aresuperseded. It is recommended to use thelabs(x, y, title, subtitle)arguments instead.

get_labs() retrieves completed labels from a plot.

Usage

labs(  ...,  title = waiver(),  subtitle = waiver(),  caption = waiver(),  tag = waiver(),  dictionary = waiver(),  alt = waiver(),  alt_insight = waiver())xlab(label)ylab(label)ggtitle(label, subtitle = waiver())get_labs(plot = get_last_plot())

Arguments

...

New name-value pairs. The name should be an aesthetic. The values can beone of the following:

  • A string or expression to set a label verbatim.

  • A function to use as formatter for the default label.

  • NULL to remove a label.

  • Awaiver() to use the default label.

title

The text for the title.

subtitle

The text for the subtitle for the plot which will bedisplayed below the title.

caption

The text for the caption which will be displayed in thebottom-right of the plot by default.

tag

The text for the tag label which will be displayed at thetop-left of the plot by default.

dictionary

A named character vector to serve as dictionary.Automatically derived labels, such as those based on variables willbe matched withnames(dictionary) and replaced by the matchingentry indictionary.

alt,alt_insight

Text used for the generation of alt-text for the plot.Seeget_alt_text for examples.alt can also be a function thattakes the plot as input and returns text as output.alt also acceptsrlanglambda function notation.

label

The title of the respective axis (forxlab() orylab()) orof the plot (forggtitle()).

plot

A ggplot object

Details

You can also set axis and legend labels in the individual scales (usingthe first argument, thename). If you're changing other scale options, thisis recommended.

If a plot already has a title, subtitle, caption, etc., and you want toremove it, you can do so by setting the respective argument toNULL. Forexample, if plotp has a subtitle, thenp + labs(subtitle = NULL) willremove the subtitle from the plot.

See Also

Theplot and axis titles section of the online ggplot2 book.

Examples

p <- ggplot(mtcars, aes(mpg, wt, colour = cyl)) + geom_point()p + labs(colour = "Cylinders")p + labs(x = "New x label")# Set labels by variable name instead of aestheticp + labs(dictionary = c(  disp = "Displacment", # Not in use  cyl  = "Number of cylinders",  mpg  = "Miles per gallon",  wt   = "Weight (1000 lbs)"))# The plot title appears at the top-left, with the subtitle# display in smaller text underneath itp + labs(title = "New plot title")p + labs(title = "New plot title", subtitle = "A subtitle")# The caption appears in the bottom-right, and is often used for# sources, notes or copyrightp + labs(caption = "(based on data from ...)")# The plot tag appears at the top-left, and is typically used# for labelling a subplot with a letter.p + labs(title = "title", tag = "A")# If you want to remove a label, set it to NULL.p + labs(title = "title") + labs(title = NULL)

Create a new layer

Description

A layer is a combination of data, stat and geom with a potential positionadjustment. Usually layers are created using⁠geom_*⁠ or⁠stat_*⁠calls but it can also be created directly using this function.

Usage

layer(  geom = NULL,  stat = NULL,  data = NULL,  mapping = NULL,  position = NULL,  params = list(),  inherit.aes = TRUE,  check.aes = TRUE,  check.param = TRUE,  show.legend = NA,  key_glyph = NULL,  layout = NULL,  layer_class = Layer)

Arguments

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

params

Additional parameters to thegeom andstat.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

check.aes,check.param

IfTRUE, the default, will check thatsupplied parameters and aesthetics are understood by thegeom orstat. UseFALSE to suppress the checks.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

key_glyph

A legend key drawing function or a string providing thefunction name minus thedraw_key_ prefix. Seedraw_key for details.

layout

Argument to control layout at the layer level. Consult thefaceting documentation to view appropriate values.

layer_class

The type of layer object to be constructed. This isintended for ggplot2 internal use only.

See Also

Theplot building chapter andgeoms chapter of the online ggplot2 book.

Other layer documentation:layer_geoms,layer_positions,layer_stats

Examples

# geom calls are just a short cut for layerggplot(mpg, aes(displ, hwy)) + geom_point()# shortcut forggplot(mpg, aes(displ, hwy)) +  layer(    geom = "point", stat = "identity", position = "identity",    params = list(na.rm = FALSE)  )# use a function as data to plot a subset of global dataggplot(mpg, aes(displ, hwy)) +  layer(    geom = "point", stat = "identity", position = "identity",    data = head, params = list(na.rm = FALSE)  )

Layer geometry display

Description

In ggplot2, a plot in constructed by adding layers to it. A layer consistsof two important parts: the geometry (geoms), and statistical transformations(stats). The 'geom' part of a layer is important because it determines thelooks of the data. Geoms determinehow something is displayed, notwhatis displayed.

Specifying geoms

There are five ways in which the 'geom' part of a layer can be specified.

# 1. The geom can have a layer constructorgeom_area()# 2. A stat can default to a particular geomstat_density() # has `geom = "area"` as default# 3. It can be given to a stat as a stringstat_function(geom = "area")# 4. The ggproto object of a geom can be givenstat_bin(geom = GeomArea)# 5. It can be given to `layer()` directlylayer(  geom = "area",  stat = "smooth",  position = "identity")

Many of these ways are absolutely equivalent. Usingstat_density(geom = "line") is identical to usinggeom_line(stat = "density"). Note that forlayer(), you need toprovide the"position" argument as well. To give geoms as a string, takethe function name, and remove thegeom_ prefix, such thatgeom_pointbecomes"point".

Some of the more well known geoms that can be used for thegeom argumentare:"point","line","area","bar" and"polygon".

Graphical display

A ggplot is build on top of thegrid package. This packageunderstands various graphical primitives, such as points, lines, rectanglesand polygons and theirpositions, as well as graphicalattributes, also termed aesthetics, such ascolours, fills,linewidths and linetypes. The job of the geom partof a layer, is to translate data to grid graphics that can be plotted.

To see how aesthetics are specified, runvignette("ggplot2-specs"). To seewhat geom uses what aesthetics, you can find theAesthetics section intheir documentation, for example in?geom_line.

While almost anything can be represented by polygons if you try hard enough,it is not always convenient to do so manually. For this reason, the geomsprovide abstractions that take most of this hassle away.geom_ribbon()for example is a special case ofgeom_polygon(), where two sets ofy-positions have a shared x-position. In turn,geom_area() is a specialcase of a ribbon, where one of the two sets of y-positions is set at 0.

# A hassle to build a polygonmy_polygon <- data.frame(  x = c(economics$date,    rev(economics$date)),  y = c(economics$uempmed, rev(economics$psavert)))ggplot(my_polygon, aes(x, y)) +  geom_polygon()# More succinctlyggplot(economics, aes(date)) +  geom_ribbon(aes(ymin = uempmed, ymax = psavert))

In addition to abstraction, geoms sometimes also perform composition.A boxplot is a particular arrangement of lines, rectangles and points thatpeople have agreed upon is a summary of some data, which is performed bygeom_boxplot().

Boxplot datavalue <- fivenum(rnorm(100))df <- data.frame(  min = value[1], lower = value[2], middle = value[3],  upper = value[4], max = value[5])# Drawing a boxplot manuallyggplot(df, aes(x = 1, xend = 1)) +  geom_rect(    aes(      xmin = 0.55, xmax = 1.45,      ymin = lower, ymax = upper    ),    colour = "black", fill = "white"  ) +  geom_segment(    aes(      x = 0.55, xend = 1.45,      y = middle, yend = middle    ),    size = 1  ) +  geom_segment(aes(y = lower, yend = min)) +  geom_segment(aes(y = upper, yend = max))# More succinctlyggplot(df, aes(x = 1)) +  geom_boxplot(    aes(ymin = min, ymax = max,        lower = lower, upper = upper,        middle = middle),    stat = "identity"  )

Under the hood

Internally, geoms are represented asggproto classes thatoccupy a slot in a layer. All these classes inherit from the parentalGeom ggproto object that orchestrates how geoms work. Briefly, geomsare given the opportunity to draw the data of the layer as a whole,a facet panel, or of individual groups. For more information on extendinggeoms, see theCreating a new geom section after runningvignette("extending-ggplot2"). Additionally, see theNew geoms sectionof theonline book.

See Also

For an overview of all geom layers, see theonline reference.

Other layer documentation:layer(),layer_positions,layer_stats


Layer position adjustments

Description

In ggplot2, a plot is constructed by adding layers to it. In addition togeoms andstats, position adjustments are thethird required part of a layer. The 'position' part of a layer is responsiblefor dodging, jittering and nudging groups of data to minimise their overlap,or otherwise tweaking their positions.

For example if you addposition = position_nudge(x = 1) to a layer, youcan offset every x-position by 1. For many layers, the default positionadjustment isposition_identity(), which performs no adjustment.

Specifying positions

There are 4 ways in which the 'position' part of a layer can be specified.

1. A layer can have default position adjustmentsgeom_jitter() # has `position = "jitter"`2. It can be given to a layer as a stringgeom_point(position = "jitter")3. The position function can be used to pass extra argumentsgeom_point(position = position_jitter(width = 1))4. It can be given to `layer()` directlylayer(  geom = "point",  stat = "identity",  position = "jitter")

These ways are not always equivalent. Some layers may not understand whatto do with a position adjustment, and require additional parameters passedthrough the⁠position_*()⁠ function, or may not work correctly. Forexampleposition_dodge() requires non-overlapping x intervals, whereasgeom_point() doesn't have dimensions to calculate intervals for. To givepositions as a string, take the function name, and remove theposition_prefix, such thatposition_fill becomes"fill".

Pairing geoms with positions

Some geoms work better with some positions than others. Below follows a briefoverview of geoms and position adjustments that work well together.

Identity

position_identity() can work with virtually any geom.

Dodging

position_dodge() pushes overlapping objects away from one another andrequires agroup variable.position_dodge2() can work without groupvariables and can handle variable widths. As a rule of thumb, layers wheregroups occupy a range on the x-axis pair well with dodging. If layers haveno width, you may be required to specify it manually withposition_dodge(width = ...). Some geoms that pair well with dodging aregeom_bar(),geom_boxplot(),geom_linerange(),geom_errorbar() andgeom_text().

Jittering

position_jitter() adds a some random noise to every point,which can help with overplotting.position_jitterdodge() does the same,but also dodges the points. As a rule of thumb, jittering works bestwhen points have discrete x-positions. Jittering is most useful forgeom_point(), but can also be used ingeom_path() for example.

Nudging

position_nudge() can add offsets to x- and y-positions. This can beuseful for discrete positions where you don't want to put an objectexactly in the middle. While most useful forgeom_text(), it can beused with virtually all geoms.

Stacking

position_stack() is useful for displaying data on top of one another. Itcan be used for geoms that are usually anchored to the x-axis, for examplegeom_bar(),geom_area() orgeom_histogram().

Filling

position_fill() can be used to give proportions at every x-position. Likestacking, filling is most useful for geoms that are anchored to the x-axis,likegeom_bar(),geom_area() orgeom_histogram().

Under the hood

Internally, positions are represented asggproto classes thatoccupy a slot in a layer. All these classes inherit from the parentalPosition ggproto object that orchestrates how positions work. Briefly,positions are given the opportunity to adjust the data of each facet panel.For more information about extending positions, see theNew positionssection of theonline book.

See Also

For an overview of all position adjustments, see theonline reference.

Other layer documentation:layer(),layer_geoms,layer_stats


Create a new sf layer that auto-maps geometry data

Description

Thelayer_sf() function is a variant oflayer() meant to be used byextension developers who are writing new sf-based geoms or stats.The sf layer checks whether the data contains a geometry column, andif one is found it is automatically mapped to thegeometry aesthetic.

Usage

layer_sf(  geom = NULL,  stat = NULL,  data = NULL,  mapping = NULL,  position = NULL,  params = list(),  inherit.aes = TRUE,  check.aes = TRUE,  check.param = TRUE,  show.legend = NA)

Arguments

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

stat

The statistical transformation to use on the data for this layer.When using a⁠geom_*()⁠ function to construct a layer, thestatargument can be used to override the default coupling between geoms andstats. Thestat argument accepts the following:

  • AStat ggproto subclass, for exampleStatCount.

  • A string naming the stat. To give the stat as a string, strip thefunction name of thestat_ prefix. For example, to usestat_count(),give the stat as"count".

  • For more information and other ways to specify the stat, see thelayer stat documentation.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

params

Additional parameters to thegeom andstat.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

check.aes,check.param

IfTRUE, the default, will check thatsupplied parameters and aesthetics are understood by thegeom orstat. UseFALSE to suppress the checks.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.


Layer statistical transformations

Description

In ggplot2, a plot is constructed by adding layers to it. A layer consistsof two important parts: the geometry (geoms), and statistical transformations(stats). The 'stat' part of a layer is important because it performs acomputation on the data before it is displayed. Stats determinewhat isdisplayed, nothow it is displayed.

For example, if you addstat_density() to a plot, a kernel densityestimation is performed, which can be displayed with the 'geom' part of alayer. For many⁠geom_*()⁠ functions,stat_identity() is used,which performs no extra computation on the data.

Specifying stats

There are five ways in which the 'stat' part of a layer can be specified.

# 1. The stat can have a layer constructorstat_density()# 2. A geom can default to a particular statgeom_density() # has `stat = "density"` as default# 3. It can be given to a geom as a stringgeom_line(stat = "density")# 4. The ggproto object of a stat can be givengeom_area(stat = StatDensity)# 5. It can be given to `layer()` directly:layer(  geom = "line",  stat = "density",  position = "identity")

Many of these ways are absolutely equivalent. Usingstat_density(geom = "line") is identical to usinggeom_line(stat = "density"). Note that forlayer(), you need toprovide the"position" argument as well. To give stats as a string, takethe function name, and remove thestat_ prefix, such thatstat_binbecomes"bin".

Some of the more well known stats that can be used for thestat argumentare:"density","bin","count","function" and"smooth".

Paired geoms and stats

Some geoms have paired stats. In some cases, likegeom_density(), it isjust a variant of another geom,geom_area(), with slightly differentdefaults.

In other cases, the relationship is more complex. In the case of boxplots forexample, the stat and the geom have distinct roles. The role of the stat isto compute the five-number summary of the data. In addition to justdisplaying the box of the five-number summary, the geom also provides displayoptions for the outliers and widths of boxplots. In such cases, you cannotfreely exchange geoms and stats: usingstat_boxplot(geom = "line") orgeom_area(stat = "boxplot") give errors.

Some stats and geoms that are paired are:

Using computed variables

As mentioned above, the role of stats is to perform computation on the data.As a result, stats have 'computed variables' that determine compatibilitywith geoms. These computed variables are documented in theComputed variables sections of the documentation, for example in?stat_bin. While more thoroughly documentedinafter_stat(), it should briefly be mentioned that these computed statscan be accessed inaes().

For example, the?stat_density documentation states that,in addition to a variable calleddensity, the stat computes a variablenamedcount. Instead of scaling such that the area integrates to 1, thecount variable scales the computed density such that the valuescan be interpreted as counts. Ifstat_density(aes(y = after_stat(count)))is used, we can display these count-scaled densities instead of the regulardensities.

The computed variables offer flexibility in that arbitrary geom-stat pairingscan be made. While not necessarily recommended,geom_line()can be pairedwithstat = "boxplot" if the line is instructed on how to use the boxplotcomputed variables:

ggplot(mpg, aes(factor(cyl))) +  geom_line(    # Stage gives 'displ' to the stat, and afterwards chooses 'middle' as    # the y-variable to display    aes(y = stage(displ, after_stat = middle),        # Regroup after computing the stats to display a single line        group = after_stat(1)),    stat = "boxplot"  )

Under the hood

Internally, stats are represented asggproto classes thatoccupy a slot in a layer. All these classes inherit from the parentalStat ggproto object that orchestrates how stats work. Briefly, statsare given the opportunity to perform computation either on the layer as awhole, a facet panel, or on individual groups. For more information onextending stats, see theCreating a new stat section afterrunningvignette("extending-ggplot2"). Additionally, see theNew statssection of theonline book.

See Also

For an overview of all stat layers, see theonline reference.

Howcomputed aesthetics work.

Other layer documentation:layer(),layer_geoms,layer_positions


Generate correct scale type for specified limits

Description

Generate correct scale type for specified limits

Usage

limits(lims, var, call = caller_env())

Arguments

lims

vector of limits

var

name of variable

Examples

ggplot2:::limits(c(1, 5), "x")ggplot2:::limits(c(5, 1), "x")ggplot2:::limits(c("A", "b", "c"), "x")ggplot2:::limits(c("A", "b", "c"), "fill")ggplot2:::limits(as.Date(c("2008-01-01", "2009-01-01")), "x")

Set scale limits

Description

This is a shortcut for supplying thelimits argument to the individualscales. By default, any values outside the limits specified are replaced withNA. Be warned that this will remove data outside the limits and this canproduce unintended results. For changing x or y axis limitswithoutdropping data observations, seecoord_cartesian(xlim, ylim), or use a full scale withoob = scales::oob_keep.

Usage

lims(...)xlim(...)ylim(...)

Arguments

...

Forxlim() andylim(): Two numeric values, specifying the left/lowerlimit and the right/upper limit of the scale. If the larger value is given first,the scale will be reversed. You can leave one value asNA if you want to computethe corresponding limit from the range of the data.

Forlims(): A name–value pair. The name must be an aesthetic, and the valuemust be either a length-2 numeric, a character, a factor, or a date/time.A numeric value will create a continuous scale. If the larger value comes first,the scale will be reversed. You can leave one value asNA if you wantto compute the corresponding limit from the range of the data.A character or factor value will create a discrete scale.A date-time value will create a continuous date/time scale.

See Also

To expand the range of a plot to always includecertain values, seeexpand_limits(). For other types of data, seescale_x_discrete(),scale_x_continuous(),scale_x_date().

Examples

# Zoom into a specified areaggplot(mtcars, aes(mpg, wt)) +  geom_point() +  xlim(15, 20)# reverse scaleggplot(mtcars, aes(mpg, wt)) +  geom_point() +  xlim(20, 15)# with automatic lower limitggplot(mtcars, aes(mpg, wt)) +  geom_point() +  xlim(NA, 20)# You can also supply limits that are larger than the data.# This is useful if you want to match scales across different plotssmall <- subset(mtcars, cyl == 4)big <- subset(mtcars, cyl > 4)ggplot(small, aes(mpg, wt, colour = factor(cyl))) +  geom_point() +  lims(colour = c("4", "6", "8"))ggplot(big, aes(mpg, wt, colour = factor(cyl))) +  geom_point() +  lims(colour = c("4", "6", "8"))# There are two ways of setting the axis limits: with limits or# with coordinate systems. They work in two rather different ways.set.seed(1)last_month <- Sys.Date() - 0:59df <- data.frame(  date = last_month,  price = c(rnorm(30, mean = 15), runif(30) + 0.2 * (1:30)))p <- ggplot(df, aes(date, price)) +  geom_line() +  stat_smooth()p# Setting the limits with the scale discards all data outside the range.p + lims(x= c(Sys.Date() - 30, NA), y = c(10, 20))# For changing x or y axis limits **without** dropping data# observations use [coord_cartesian()]. Setting the limits on the# coordinate system performs a visual zoom.p + coord_cartesian(xlim =c(Sys.Date() - 30, NA), ylim = c(10, 20))

colors() in Luv space

Description

All built-incolors() translated into Luv colour space.

Usage

luv_colours

Format

A data frame with 657 observations and 4 variables:

L,u,v

Position in Luv colour space

col

Colour name


Produce boilerplate constructors

Description

Themake_constructor() functions sets up a user-facing constructor forggproto classes. Currently,make_constructor() is implemented forGeom classes.

Usage

make_constructor(x, ...)## S3 method for class 'Geom'make_constructor(  x,  ...,  checks = exprs(),  omit = character(),  env = caller_env())## S3 method for class 'Stat'make_constructor(  x,  ...,  checks = exprs(),  omit = character(),  env = caller_env())

Arguments

x

An object to setup a constructor for.

...

Name-value pairs to use as additional arguments in theconstructor. For layers, these are passed on tolayer(params).

checks

A list of calls to be evaluated before construction of theobject, such as one constructed withexprs().

omit

A character vector of automatically retrieved argument namesthat should not be converted to user-facing arguments. Useful forinternally computed variables.

env

An environment to search for the object.

Value

A function

Examples

# For testing purposes, a geom that returns grobsGeomTest <- ggproto(  "GeomTest", Geom,  draw_group = function(..., grob = grid::pointsGrob()) {    return(grob)  })# Creating a constructorgeom_test <- make_constructor(GeomTest)# Note that `grob` is automatically an argument to the functionnames(formals(geom_test))# Use in a plotset.seed(1234)p <- ggplot(mtcars, aes(disp, mpg))p + geom_test()p + geom_test(grob = grid::circleGrob())# The `checks` argument can be used to evaluate arbitrary expressions in# the constructor before building the layer.geom_path2 <- make_constructor(  GeomPath, checks = rlang::exprs(    match.arg(lineend, c("butt", "round", "square")),    match.arg(linejoin, c("round", "mitre", "bevel"))  ))# Note the inclusion of the expressionsprint(geom_path2)# Argument mismatch is detectedtry(geom_path2(linejoin = "foo"))

Create a data frame of map data

Description

Easily turn data from themaps package into a data frame suitablefor plotting with ggplot2.

Usage

map_data(map, region = ".", exact = FALSE, ...)

Arguments

map

name of map provided by themaps package. Theseinclude"county","france","italy","nz","state","usa","world", or"world2".

region

name(s) of subregion(s) to include. Defaults to. whichincludes all subregions. See documentation formaps::map()for more details.

exact

should theregion be treated as a regular expression(FALSE) or as a fixed string (TRUE).

...

all other arguments passed on tomaps::map()

Examples

if (require("maps")) {states <- map_data("state")arrests <- USArrestsnames(arrests) <- tolower(names(arrests))arrests$region <- tolower(rownames(USArrests))choro <- merge(states, arrests, sort = FALSE, by = "region")choro <- choro[order(choro$order), ]ggplot(choro, aes(long, lat)) +  geom_polygon(aes(group = group, fill = assault)) +  coord_map("albers",  lat0 = 45.5, lat1 = 29.5)}if (require("maps")) {ggplot(choro, aes(long, lat)) +  geom_polygon(aes(group = group, fill = assault / murder)) +  coord_map("albers",  lat0 = 45.5, lat1 = 29.5)}

Theme elements

Description

In conjunction with thetheme system, theelement_ functionsspecify the display of how non-data components of the plot are drawn.

rel() is used to specify sizes relative to the parent,margin(),margin_part() andmargin_auto() are all used to specify themargins of elements.

Usage

margin(t = 0, r = 0, b = 0, l = 0, unit = "pt", ...)margin_part(t = NA, r = NA, b = NA, l = NA, unit = "pt")margin_auto(t = 0, r = t, b = t, l = r, unit = "pt")element()element_blank()element_rect(  fill = NULL,  colour = NULL,  linewidth = NULL,  linetype = NULL,  color = NULL,  linejoin = NULL,  inherit.blank = FALSE,  size = deprecated(),  ...)element_line(  colour = NULL,  linewidth = NULL,  linetype = NULL,  lineend = NULL,  color = NULL,  linejoin = NULL,  arrow = NULL,  arrow.fill = NULL,  inherit.blank = FALSE,  size = deprecated(),  ...)element_text(  family = NULL,  face = NULL,  colour = NULL,  size = NULL,  hjust = NULL,  vjust = NULL,  angle = NULL,  lineheight = NULL,  color = NULL,  margin = NULL,  debug = NULL,  inherit.blank = FALSE,  ...)element_polygon(  fill = NULL,  colour = NULL,  linewidth = NULL,  linetype = NULL,  color = NULL,  linejoin = NULL,  inherit.blank = FALSE,  ...)element_point(  colour = NULL,  shape = NULL,  size = NULL,  fill = NULL,  stroke = NULL,  color = NULL,  inherit.blank = FALSE,  ...)element_geom(  ink = NULL,  paper = NULL,  accent = NULL,  linewidth = NULL,  borderwidth = NULL,  linetype = NULL,  bordertype = NULL,  family = NULL,  fontsize = NULL,  pointsize = NULL,  pointshape = NULL,  colour = NULL,  color = NULL,  fill = NULL,  ...)rel(x)

Arguments

t,r,b,l

Dimensions of each margin. (To remember order, think trouble).

unit

Default units of dimensions. Defaults to "pt" so itcan be most easily scaled with the text.

...

Reserved for future expansion.

fill

Fill colour.fill_alpha() can be used to set the transparencyof the fill.

colour,color

Line/border colour. Color is an alias for colour.alpha() can be used to set the transparency of the colour.

linewidth,borderwidth,stroke

Line/border size in mm.

linetype,bordertype

Line type for lines and borders respectively. Aninteger (0:8), a name (blank, solid, dashed, dotted, dotdash, longdash,twodash), or a string with an even number (up to eight) of hexadecimaldigits which give the lengths in consecutive positions in the string.

linejoin

Line join style, one of"round","mitre" or"bevel".

inherit.blank

Should this element inherit the existence of anelement_blank among its parents? IfTRUE the existence ofa blank element among its parents will cause this element to be blank aswell. IfFALSE any blank parent element will be ignored whencalculating final element state.

size,fontsize,pointsize

text size in pts, point size in mm.

lineend

Line end style, one of"round","butt" or"square".

arrow

Arrow specification, as created bygrid::arrow()

arrow.fill

Fill colour for arrows.

family

The typeface to use. The validity of this value will depend onthe graphics device being used for rendering the plot. Seethe systemfonts vignettefor guidance on the best way to access fonts installed on your computer.The values"sans","serif", and"mono" should always be valid andwill select the default typeface for the respective styles. However, whatis considered default is dependant on the graphics device and the operatingsystem.

face

Font face ("plain", "italic", "bold", "bold.italic")

hjust

Horizontal justification (in[0, 1])

vjust

Vertical justification (in[0, 1])

angle

Angle (in[0, 360])

lineheight

Line height

margin

Margins around the text. Seemargin() for moredetails. When creating a theme, the margins should be placed on theside of the text facing towards the center of the plot.

debug

IfTRUE, aids visual debugging by drawing a solidrectangle behind the complete text area, and a point where each labelis anchored.

shape,pointshape

Shape for points (1-25).

ink

Foreground colour.

paper

Background colour.

accent

Accent colour.

x

A single number specifying size relative to parent element.

Details

Theelement_polygon() andelement_point() functions are not renderedin standard plots and just serve as extension points.

Value

An object of classelement,rel, ormargin.

Examples

# A standard plotplot <- ggplot(mpg, aes(displ, hwy)) + geom_point()# Turning off theme elements by setting them to blankplot + theme(  panel.background = element_blank(),  axis.text = element_blank())# Text adjustmentsplot + theme(  axis.text = element_text(colour = "red", size = rel(1.5)))# Turning on the axis line with an arrowplot + theme(  axis.line = element_line(arrow = arrow()))plot + theme(  panel.background = element_rect(fill = "white"),  plot.margin = margin_auto(2, unit = "cm"),  plot.background = element_rect(    fill = "grey90",    colour = "black",    linewidth = 1  ))ggplot(mpg, aes(displ, hwy)) +  geom_point() +  geom_smooth(formula = y ~ x, method = "lm") +  theme(geom = element_geom(    ink = "red", accent = "black",    pointsize = 1, linewidth = 2  ))

Get the maximal width/length of a list of grobs

Description

Get the maximal width/length of a list of grobs

Usage

max_height(grobs, value_only = FALSE)max_width(grobs, value_only = FALSE)

Arguments

grobs

A list of grobs

value_only

Should the return value be a simple numeric vector givingthe maximum in cm

Value

The largest value. measured in cm as a unit object or a numericvector depending onvalue_only


Calculate mean and standard error of the mean

Description

For use withstat_summary()

Usage

mean_se(x, mult = 1)

Arguments

x

numeric vector.

mult

number of multiples of standard error.

Value

A data frame with three columns:

y

The mean.

ymin

The mean minus the multiples of the standard error.

ymax

The mean plus the multiples of the standard error.

Examples

set.seed(1)x <- rnorm(100)mean_se(x)

Merge a parent element into a child element

Description

This is a generic and element classes must provide an implementation of thismethod

Usage

merge_element(new, old, ...)

Arguments

new

The child element in the theme hierarchy

old

The parent element in the theme hierarchy

Value

A modified version ofnew updated with the properties ofold

Examples

new <- element_text(colour = "red")old <- element_text(colour = "blue", size = 10)# Adopt size but ignore colourmerge_element(new, old)

Midwest demographics

Description

Demographic information of midwest counties from 2000 US census

Usage

midwest

Format

A data frame with 437 rows and 28 variables:

PID

Unique county identifier.

county

County name.

state

State to which county belongs to.

area

Area of county (units unknown).

poptotal

Total population.

popdensity

Population density (person/unit area).

popwhite

Number of whites.

popblack

Number of blacks.

popamerindian

Number of American Indians.

popasian

Number of Asians.

popother

Number of other races.

percwhite

Percent white.

percblack

Percent black.

percamerindan

Percent American Indian.

percasian

Percent Asian.

percother

Percent other races.

popadults

Number of adults.

perchsd

Percent with high school diploma.

percollege

Percent college educated.

percprof

Percent with professional degree.

poppovertyknown

Population with known poverty status.

percpovertyknown

Percent of population with known poverty status.

percbelowpoverty

Percent of people below poverty line.

percchildbelowpovert

Percent of children below poverty line.

percadultpoverty

Percent of adults below poverty line.

percelderlypoverty

Percent of elderly below poverty line.

inmetro

County considered in a metro area.

category

Miscellaneous.

Details

Note: this dataset is included for illustrative purposes. The originaldescriptions were not documented and the current descriptions here are basedon speculation. For more accurate and up-to-date US census data, see theacs package.


Fuel economy data from 1999 to 2008 for 38 popular models of cars

Description

This dataset contains a subset of the fuel economy data that the EPA makesavailable onhttps://fueleconomy.gov/. It contains only models whichhad a new release every year between 1999 and 2008 - this was used as aproxy for the popularity of the car.

Usage

mpg

Format

A data frame with 234 rows and 11 variables:

manufacturer

manufacturer name

model

model name

displ

engine displacement, in litres

year

year of manufacture

cyl

number of cylinders

trans

type of transmission

drv

the type of drive train, where f = front-wheel drive, r = rear wheel drive, 4 = 4wd

cty

city miles per gallon

hwy

highway miles per gallon

fl

fuel type

class

"type" of car


An updated and expanded version of the mammals sleep dataset

Description

This is an updated and expanded version of the mammals sleep dataset.Updated sleep times and weights were taken from V. M. Savage and G. B.West. A quantitative, theoretical framework for understanding mammaliansleep. Proceedings of the National Academy of Sciences, 104 (3):1051-1056,2007.

Usage

msleep

Format

A data frame with 83 rows and 11 variables:

name

common name

genus
vore

carnivore, omnivore or herbivore?

order
conservation

the conservation status of the animal

sleep_total

total amount of sleep, in hours

sleep_rem

rem sleep, in hours

sleep_cycle

length of sleep cycle, in hours

awake

amount of time spent awake, in hours

brainwt

brain weight in kilograms

bodywt

body weight in kilograms

Details

Additional variables order, conservation status and vore were added fromwikipedia.


Guide constructor

Description

A constructor function for guides, which performs some standard compatibilitychecks between the guide and provided arguments.

Usage

new_guide(..., available_aes = "any", super)

Arguments

...

Named arguments that match the parameters ofsuper$params orthe theme elements insuper$elements.

available_aes

A vector of character strings listing the aestheticsfor which the guide can be drawn.

super

The super class to use for the constructed guide. Should be aGuide class object.

Value

AGuide ggproto object.


The previous S3 guide system

Description

The guide system has been overhauled to use the ggproto infrastructure toaccommodate guide extensions with the same flexibility as layers, scales andother ggplot2 objects. In rewriting, the old S3 system has become defunct,meaning that the previous methods for guides have been superseded by ggprotomethods. As a fallback option, the generics, but not the methods, that theprevious S3 system used are encapsulated in theGuideOld ggproto class.

Usage

guide_train(guide, scale, aesthetic = NULL)guide_merge(guide, new_guide)guide_geom(guide, layers, default_mapping = NULL)guide_transform(guide, coord, panel_params)guide_gengrob(guide, theme)old_guide(guide)

Arguments

guide

An old guide object


Modify transparency for patterns

Description

This generic allows you to add your own methods for adding transparency topattern-like objects.

Usage

pattern_alpha(x, alpha)

Arguments

x

Object to be interpreted as pattern.

alpha

Anumeric vector between 0 and 1. IfNA, alpha valuesare preserved.

Value

x with modified transparency


Dodge overlapping objects side-to-side

Description

Dodging preserves the vertical position of an geom while adjusting thehorizontal position.position_dodge() requires the grouping variable to bebe specified in the global or⁠geom_*⁠ layer. Unlikeposition_dodge(),position_dodge2() works without a grouping variable in a layer.position_dodge2() works with bars and rectangles, but isparticularly useful for arranging box plots, whichcan have variable widths.

Usage

position_dodge(  width = NULL,  preserve = "total",  orientation = "x",  reverse = FALSE)position_dodge2(  width = NULL,  preserve = "total",  padding = 0.1,  reverse = FALSE)

Arguments

width

Dodging width, when different to the width of the individualelements. This is useful when you want to align narrow geoms with widergeoms. See the examples.

preserve

Should dodging preserve the"total" width of all elementsat a position, or the width of a"single" element?

orientation

Fallback orientation when the layer or the data does notindicate an explicit orientation, likegeom_point(). Can be"x"(default) or"y".

reverse

IfTRUE, will reverse the default stacking order.This is useful if you're rotating both the plot and legend.

padding

Padding between elements at the same position. Elements areshrunk by this proportion to allow space between them. Defaults to 0.1.

Aesthetics

position_dodge() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

orderNULL

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

Other position adjustments:position_identity(),position_jitter(),position_jitterdodge(),position_nudge(),position_stack()

Examples

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +  geom_bar(position = "dodge2")# By default, dodging with `position_dodge2()` preserves the total width of# the elements. You can choose to preserve the width of each element with:ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +  geom_bar(position = position_dodge2(preserve = "single"))ggplot(diamonds, aes(price, fill = cut)) +  geom_histogram(position="dodge2")# see ?geom_bar for more examples# In this case a frequency polygon is probably a better choiceggplot(diamonds, aes(price, colour = cut)) +  geom_freqpoly()# Dodging with various widths -------------------------------------# To dodge items with different widths, you need to be explicitdf <- data.frame(  x = c("a","a","b","b"),  y = 2:5,  g = rep(1:2, 2))p <- ggplot(df, aes(x, y, group = g)) +  geom_col(position = "dodge", fill = "grey50", colour = "black")p# A line range has no width:p + geom_linerange(aes(ymin = y - 1, ymax = y + 1), position = "dodge")# So you must explicitly specify the widthp + geom_linerange(  aes(ymin = y - 1, ymax = y + 1),  position = position_dodge(width = 0.9))# The same principle applies to error bars, which are usually# narrower than the barsp + geom_errorbar(  aes(ymin = y - 1, ymax = y + 1),  width = 0.2,  position = "dodge")p + geom_errorbar(  aes(ymin = y - 1, ymax = y + 1),  width = 0.2,  position = position_dodge(width = 0.9))# Box plots use position_dodge2 by default, and bars can use it tooggplot(mpg, aes(factor(year), displ)) +  geom_boxplot(aes(colour = hwy < 30))ggplot(mpg, aes(factor(year), displ)) +  geom_boxplot(aes(colour = hwy < 30), varwidth = TRUE)ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +  geom_bar(position = position_dodge2(preserve = "single"))ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +  geom_bar(position = position_dodge2(preserve = "total"))

Don't adjust position

Description

Don't adjust position

Usage

position_identity()

See Also

Other position adjustments:position_dodge(),position_jitter(),position_jitterdodge(),position_nudge(),position_stack()


Jitter points to avoid overplotting

Description

Counterintuitively adding random noise to a plot can sometimes make iteasier to read. Jittering is particularly useful for small datasets withat least one discrete position.

Usage

position_jitter(width = NULL, height = NULL, seed = NA)

Arguments

width,height

Amount of vertical and horizontal jitter. The jitteris added in both positive and negative directions, so the total spreadis twice the value specified here.

If omitted, defaults to 40% of the resolution of the data: this means thejitter values will occupy 80% of the implied bins. Categorical datais aligned on the integers, so a width or height of 0.5 will spread thedata so it's not possible to see the distinction between the categories.

seed

A random seed to make the jitter reproducible.Useful if you need to apply the same jitter twice, e.g., for a point anda corresponding label.The random seed is reset after jittering.IfNA (the default value), the seed is initialised with a random value;this makes sure that two subsequent calls start with a different seed.UseNULL to use the current random seed and also avoid resetting(the behaviour ofggplot 2.2.1 and earlier).

See Also

Other position adjustments:position_dodge(),position_identity(),position_jitterdodge(),position_nudge(),position_stack()

Examples

# Jittering is useful when you have a discrete position, and a relatively# small number of points# take up as much space as a boxplot or a barggplot(mpg, aes(class, hwy)) +  geom_boxplot(colour = "grey50") +  geom_jitter()# If the default jittering is too much, as in this plot:ggplot(mtcars, aes(am, vs)) +  geom_jitter()# You can adjust it in two waysggplot(mtcars, aes(am, vs)) +  geom_jitter(width = 0.1, height = 0.1)ggplot(mtcars, aes(am, vs)) +  geom_jitter(position = position_jitter(width = 0.1, height = 0.1))# Create a jitter object for reproducible jitter:jitter <- position_jitter(width = 0.1, height = 0.1, seed = 0)ggplot(mtcars, aes(am, vs)) +  geom_point(position = jitter) +  geom_point(position = jitter, color = "red", aes(am + 0.2, vs + 0.2))

Simultaneously dodge and jitter

Description

This is primarily used for aligning points generated throughgeom_point() with dodged boxplots (e.g., ageom_boxplot() witha fill aesthetic supplied).

Usage

position_jitterdodge(  jitter.width = NULL,  jitter.height = 0,  dodge.width = 0.75,  reverse = FALSE,  seed = NA)

Arguments

jitter.width

degree of jitter in x direction. Defaults to 40% of theresolution of the data.

jitter.height

degree of jitter in y direction. Defaults to 0.

dodge.width

the amount to dodge in the x direction. Defaults to 0.75,the defaultposition_dodge() width.

reverse

IfTRUE, will reverse the default stacking order.This is useful if you're rotating both the plot and legend.

seed

A random seed to make the jitter reproducible.Useful if you need to apply the same jitter twice, e.g., for a point anda corresponding label.The random seed is reset after jittering.IfNA (the default value), the seed is initialised with a random value;this makes sure that two subsequent calls start with a different seed.UseNULL to use the current random seed and also avoid resetting(the behaviour ofggplot 2.2.1 and earlier).

See Also

Other position adjustments:position_dodge(),position_identity(),position_jitter(),position_nudge(),position_stack()

Examples

set.seed(596)dsub <- diamonds[sample(nrow(diamonds), 1000), ]ggplot(dsub, aes(x = cut, y = carat, fill = clarity)) +  geom_boxplot(outlier.size = 0) +  geom_point(pch = 21, position = position_jitterdodge())

Nudge points a fixed distance

Description

position_nudge() is generally useful for adjusting the position ofitems on discrete scales by a small amount. Nudging is built in togeom_text() because it's so useful for moving labels a smalldistance from what they're labelling.

Usage

position_nudge(x = NULL, y = NULL)

Arguments

x,y

Amount of vertical and horizontal distance to move.

Aesthetics

position_nudge() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

nudge_x0
nudge_y0

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

Other position adjustments:position_dodge(),position_identity(),position_jitter(),position_jitterdodge(),position_stack()

Examples

df <- data.frame(  x = c(1,3,2,5),  y = c("a","c","d","c"))ggplot(df, aes(x, y)) +  geom_point() +  geom_text(aes(label = y))ggplot(df, aes(x, y)) +  geom_point() +  geom_text(aes(label = y), position = position_nudge(y = -0.1))# Or, in briefggplot(df, aes(x, y)) +  geom_point() +  geom_text(aes(label = y), nudge_y = -0.1)# For each text individuallyggplot(df, aes(x, y)) +  geom_point() +  geom_text(aes(label = y, nudge_y = c(-0.1, 0.1, -0.1, 0.1)))

Stack overlapping objects on top of each another

Description

position_stack() stacks bars on top of each other;position_fill() stacks bars and standardises each stack to haveconstant height.

Usage

position_stack(vjust = 1, reverse = FALSE)position_fill(vjust = 1, reverse = FALSE)

Arguments

vjust

Vertical adjustment for geoms that have a position(like points or lines), not a dimension (like bars or areas). Set to0 to align with the bottom,0.5 for the middle,and1 (the default) for the top.

reverse

IfTRUE, will reverse the default stacking order.This is useful if you're rotating both the plot and legend.

Details

position_fill() andposition_stack() automatically stackvalues in reverse order of the group aesthetic, which for bar charts isusually defined by the fill aesthetic (the default group aesthetic is formedby the combination of all discrete aesthetics except for x and y). Thisdefault ensures that bar colours align with the default legend.

There are three ways to override the defaults depending on what you want:

  1. Change the order of the levels in the underlying factor. Thiswill change the stacking order, and the order of keys in the legend.

  2. Set the legendbreaks to change the order of the keyswithout affecting the stacking.

  3. Manually set the group aesthetic to change the stacking orderwithout affecting the legend.

Stacking of positive and negative values are performed separately so thatpositive values stack upwards from the x-axis and negative values stackdownward.

Because stacking is performed after scale transformations, stacking withnon-linear scales gives distortions that easily lead to misinterpretations ofthe data. It is thereforediscouraged to use these position adjustments incombination with scale transformations, such as logarithmic or square rootscales.

See Also

Seegeom_bar() andgeom_area() formore examples.

Other position adjustments:position_dodge(),position_identity(),position_jitter(),position_jitterdodge(),position_nudge()

Examples

# Stacking and filling ------------------------------------------------------# Stacking is the default behaviour for most area plots.# Fill makes it easier to compare proportionsggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +  geom_bar()ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +  geom_bar(position = "fill")ggplot(diamonds, aes(price, fill = cut)) +  geom_histogram(binwidth = 500)ggplot(diamonds, aes(price, fill = cut)) +  geom_histogram(binwidth = 500, position = "fill")# Stacking is also useful for time seriesset.seed(1)series <- data.frame(  time = c(rep(1, 4),rep(2, 4), rep(3, 4), rep(4, 4)),  type = rep(c('a', 'b', 'c', 'd'), 4),  value = rpois(16, 10))ggplot(series, aes(time, value)) +  geom_area(aes(fill = type))# Stacking order ------------------------------------------------------------# The stacking order is carefully designed so that the plot matches# the legend.# You control the stacking order by setting the levels of the underlying# factor. See the forcats package for convenient helpers.series$type2 <- factor(series$type, levels = c('c', 'b', 'd', 'a'))ggplot(series, aes(time, value)) +  geom_area(aes(fill = type2))# You can change the order of the levels in the legend using the scaleggplot(series, aes(time, value)) +  geom_area(aes(fill = type)) +  scale_fill_discrete(breaks = c('a', 'b', 'c', 'd'))# If you've flipped the plot, use reverse = TRUE so the levels# continue to matchggplot(series, aes(time, value)) +  geom_area(aes(fill = type2), position = position_stack(reverse = TRUE)) +  coord_flip() +  theme(legend.position = "top")# Non-area plots ------------------------------------------------------------# When stacking across multiple layers it's a good idea to always set# the `group` aesthetic in the ggplot() call. This ensures that all layers# are stacked in the same way.ggplot(series, aes(time, value, group = type)) +  geom_line(aes(colour = type), position = "stack") +  geom_point(aes(colour = type), position = "stack")ggplot(series, aes(time, value, group = type)) +  geom_area(aes(fill = type)) +  geom_line(aes(group = type), position = "stack")# You can also stack labels, but the default position is suboptimal.ggplot(series, aes(time, value, group = type)) +  geom_area(aes(fill = type)) +  geom_text(aes(label = type), position = "stack")# You can override this with the vjust parameter. A vjust of 0.5# will center the labels inside the corresponding areaggplot(series, aes(time, value, group = type)) +  geom_area(aes(fill = type)) +  geom_text(aes(label = type), position = position_stack(vjust = 0.5))# Negative values -----------------------------------------------------------df <- data.frame(  x = rep(c("a", "b"), 2:3),  y = c(1, 2, 1, 3, -1),  grp = c("x", "y", "x", "y", "y"))ggplot(data = df, aes(x, y, group = grp)) +  geom_col(aes(fill = grp), position = position_stack(reverse = TRUE)) +  geom_hline(yintercept = 0)ggplot(data = df, aes(x, y, group = grp)) +  geom_col(aes(fill = grp)) +  geom_hline(yintercept = 0) +  geom_text(aes(label = grp), position = position_stack(vjust = 0.5))

Terms of 12 presidents from Eisenhower to Trump

Description

The names of each president, the start and end date of their term, andtheir party of 12 US presidents from Eisenhower to Trump. This data isin the public domain.

Usage

presidential

Format

A data frame with 12 rows and 4 variables:

name

Last name of president

start

Presidency start date

end

Presidency end date

party

Party of president


Explicitly draw plot

Description

Generally, you do not need to print or plot a ggplot2 plot explicitly: thedefault top-level print method will do it for you. You will, however, needto callprint() explicitly if you want to draw a plot inside afunction or for loop.

Arguments

x

plot to display

newpage

draw new (empty) page first?

vp

viewport to draw plot in

...

other arguments not used by this method

Value

Invisibly returns the original plot.

Examples

colours <- c("class", "drv", "fl")# Doesn't seem to do anything!for (colour in colours) {  ggplot(mpg, aes(displ, hwy, colour = .data[[colour]])) +    geom_point()}for (colour in colours) {  print(ggplot(mpg, aes(displ, hwy, colour = .data[[colour]])) +          geom_point())}

Format or print a ggproto object

Description

If a ggproto object has a⁠$print⁠ method, this will call that method.Otherwise, it will print out the members of the object, and optionally, themembers of the inherited objects.

Usage

## S3 method for class 'ggproto'print(x, ..., flat = TRUE)## S3 method for class 'ggproto'format(x, ..., flat = TRUE)

Arguments

x

A ggproto object to print.

...

If the ggproto object has aprint method, further argumentswill be passed to it. Otherwise, these arguments are unused.

flat

IfTRUE (the default), show a flattened list of all localand inherited members. IfFALSE, show the inheritance hierarchy.

Examples

Dog <- ggproto(  print = function(self, n) {    cat("Woof!\n")  } )Dogcat(format(Dog), "\n")

Quick plot

Description

qplot() is now deprecated in order to encourage the users tolearnggplot() as it makes it easier to create complex graphics.

Usage

qplot(  x,  y,  ...,  data,  facets = NULL,  margins = FALSE,  geom = "auto",  xlim = c(NA, NA),  ylim = c(NA, NA),  log = "",  main = NULL,  xlab = NULL,  ylab = NULL,  asp = NA,  stat = deprecated(),  position = deprecated())quickplot(  x,  y,  ...,  data,  facets = NULL,  margins = FALSE,  geom = "auto",  xlim = c(NA, NA),  ylim = c(NA, NA),  log = "",  main = NULL,  xlab = NULL,  ylab = NULL,  asp = NA,  stat = deprecated(),  position = deprecated())

Arguments

x,y,...

Aesthetics passed into each layer

data

Data frame to use (optional). If not specified, will createone, extracting vectors from the current environment.

facets

faceting formula to use. Picksfacet_wrap() orfacet_grid() depending on whether the formula is one-or two-sided

margins

Seefacet_grid(): display marginal facets?

geom

Character vector specifying geom(s) to draw. Defaults to"point" if x and y are specified, and "histogram" if only x is specified.

xlim,ylim

X and y axis limits

log

Which variables to log transform ("x", "y", or "xy")

main,xlab,ylab

Character vector (or expression) giving plot title,x axis label, and y axis label respectively.

asp

The y/x aspect ratio

stat,position

[Deprecated]

Examples

# Use data from data.frameqplot(mpg, wt, data = mtcars)qplot(mpg, wt, data = mtcars, colour = cyl)qplot(mpg, wt, data = mtcars, size = cyl)qplot(mpg, wt, data = mtcars, facets = vs ~ am)set.seed(1)qplot(1:10, rnorm(10), colour = runif(10))qplot(1:10, letters[1:10])mod <- lm(mpg ~ wt, data = mtcars)qplot(resid(mod), fitted(mod))f <- function() {   a <- 1:10   b <- a ^ 2   qplot(a, b)}f()# To set aesthetics, wrap in I()qplot(mpg, wt, data = mtcars, colour = I("red"))# qplot will attempt to guess what geom you want depending on the input# both x and y supplied = scatterplotqplot(mpg, wt, data = mtcars)# just x supplied = histogramqplot(mpg, data = mtcars)# just y supplied = scatterplot, with x = seq_along(y)qplot(y = mpg, data = mtcars)# Use different geomsqplot(mpg, wt, data = mtcars, geom = "path")qplot(factor(cyl), wt, data = mtcars, geom = c("boxplot", "jitter"))qplot(mpg, data = mtcars, geom = "dotplot")

Objects exported from other packages

Description

These objects are imported from other packages. Follow the linksbelow to see their documentation.

grid

arrow,unit

scales

alpha

Examples

ggplot(mpg, aes(displ, hwy)) +  geom_point(alpha = 0.5, colour = "blue")ggplot(mpg, aes(displ, hwy)) +  geom_point(colour = alpha("blue", 0.5))

Define and register new theme elements

Description

The underlying structure of a ggplot2 theme is defined via the element tree, whichspecifies for each theme element what type it should have and whether it inherits froma parent element. In some use cases, it may be necessary to modify or extend thiselement tree and provide default settings for newly defined theme elements.

Usage

register_theme_elements(..., element_tree = NULL, complete = TRUE)reset_theme_settings(reset_current = TRUE)get_element_tree()el_def(class = NULL, inherit = NULL, description = NULL)

Arguments

...

Element specifications

element_tree

Addition of or modification to the element tree, which specifies theinheritance relationship of the theme elements. The element tree must be provided asa list of named element definitions created with el_def().

complete

IfTRUE (the default), elements are set to inherit from blank elements.

reset_current

IfTRUE (the default), the currently active theme isreset to the default theme.

class

The name of the element class. Examples areelement_line orelement_text or "unit", or one of the two reserved keywords "character" or"margin". The reserved keyword "character" implies a characteror numeric vector, not a class called "character". The keyword"margin" implies a unit vector of length 4, as created bymargin().

inherit

A vector of strings, naming the elements that thiselement inherits from.

description

An optional character vector providing a descriptionfor the element.

Details

The functionregister_theme_elements() provides the option to globally register newtheme elements with ggplot2. In general, for each new theme element both an elementdefinition and a corresponding entry in the element tree should be provided. Seeexamples for details. This function is meant primarily for developers of extensionpackages, who are strongly urged to adhere to the following best practices:

  1. Callregister_theme_elements() from the.onLoad() function of your package, sothat the new theme elements are available to anybody using functions from your package,irrespective of whether the package has been attached (withlibrary() orrequire())or not.

  2. For any new elements you create, prepend them with the name of your package, to avoidname clashes with other extension packages. For example, if you are working on a packageggxyz, and you want it to provide a new element for plot panel annotations (as demonstratedin the Examples below), name the new elementggxyz.panel.annotation.

The functionreset_theme_settings() restores the default element tree, discardsall new element definitions, and (unless turned off) resets the currently activetheme to the default.

The functionget_element_tree() returns the currently active element tree.

The functionel_def() is used to define new or modified element types andelement inheritance relationships for the element tree.

See Also

Thedefining theme elements section of the online ggplot2 book.

Examples

# Let's assume a package `ggxyz` wants to provide an easy way to add annotations to# plot panels. To do so, it registers a new theme element `ggxyz.panel.annotation`register_theme_elements(  ggxyz.panel.annotation = element_text(color = "blue", hjust = 0.95, vjust = 0.05),  element_tree = list(ggxyz.panel.annotation = el_def(element_text, "text")))# Now the package can define a new coord that includes a panel annotationcoord_annotate <- function(label = "panel annotation") {  ggproto(NULL, CoordCartesian,    limits = list(x = NULL, y = NULL),    expand = TRUE,    default = FALSE,    clip = "on",    render_fg = function(panel_params, theme) {      element_render(theme, "ggxyz.panel.annotation", label = label)    }  )}# Example plot with this new coorddf <- data.frame(x = 1:3, y = 1:3)ggplot(df, aes(x, y)) +  geom_point() +  coord_annotate("annotation in blue")# Revert to the original ggplot2 settingsreset_theme_settings()

Convenience function to remove missing values from a data.frame

Description

Remove all non-complete rows, with a warning ifna.rm = FALSE.ggplot is somewhat more accommodating of missing values than R generally.For those stats which require complete data, missing values will beautomatically removed with a warning. Ifna.rm = TRUE is suppliedto the statistic, the warning will be suppressed.

Usage

remove_missing(df, na.rm = FALSE, vars = names(df), name = "", finite = FALSE)

Arguments

df

data.frame

na.rm

If true, will suppress warning message.

vars

Character vector of variables to check for missings in

name

Optional function name to improve error message.

finite

IfTRUE, will also remove non-finite values.


Render panel axes

Description

These helpers facilitates generating theme compliant axes whenbuilding up the plot.

Usage

render_axes(x = NULL, y = NULL, coord, theme, transpose = FALSE)

Arguments

x,y

A list of ranges as available to the draw_panel method inFacet subclasses.

coord

ACoord object

theme

Atheme object

transpose

Should the output be transposed?

Value

A list with the element "x" and "y" each containing axisspecifications for the ranges passed in. Each axis specification is a listwith a "top" and "bottom" element for x-axes and "left" and "right" elementfor y-axis, holding the respective axis grobs. Depending on the content of xand y some of the grobs might be zeroGrobs. Iftranspose=TRUE thecontent of the x and y elements will be transposed so e.g. all left-axes arecollected in a left element as a list of grobs.


Render panel strips

Description

All positions are rendered and it is up to the facet to decide which to use

Usage

render_strips(x = NULL, y = NULL, labeller = identity, theme)

Arguments

x,y

A data.frame with a column for each variable and a row for eachcombination to draw

labeller

A labeller function

theme

atheme object

Value

A list with an "x" and a "y" element, each containing a "top" and"bottom" or "left" and "right" element respectively. These contains a list ofrendered strips as gtables.


Compute the "resolution" of a numeric vector

Description

The resolution is the smallest non-zero distance between adjacentvalues. If there is only one unique value, then the resolution is definedto be one. If x is an integer vector, then it is assumed to represent adiscrete variable, and the resolution is 1. If the differences are all smallerthan the tolerance, set resolution to 1.

Usage

resolution(x, zero = TRUE, discrete = FALSE)

Arguments

x

numeric vector

zero

should a zero value be automatically included in thecomputation of resolution

discrete

should vectors mapped with a discrete scale be treated ashaving a resolution of 1?

Examples

resolution(1:10)resolution((1:10) - 0.5)resolution((1:10) - 0.5, FALSE)# Note the difference between numeric and integer vectorsresolution(c(2, 10, 20, 50))resolution(c(2L, 10L, 20L, 50L))

Alpha transparency scales

Description

Alpha-transparency scales are not tremendously useful, but can be aconvenient way to visually down-weight less important observations.scale_alpha() is an alias forscale_alpha_continuous() sincethat is the most common use of alpha, and it saves a bit of typing.

Usage

scale_alpha(name = waiver(), ..., range = NULL, aesthetics = "alpha")scale_alpha_continuous(  name = waiver(),  ...,  range = NULL,  aesthetics = "alpha")scale_alpha_binned(name = waiver(), ..., range = NULL, aesthetics = "alpha")scale_alpha_discrete(...)scale_alpha_ordinal(name = waiver(), ..., range = NULL, aesthetics = "alpha")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Other arguments passed on tocontinuous_scale(),binned_scale(),ordiscrete_scale() as appropriate, to control name, limits,breaks, labels and so forth.

range

Output range of alpha values. Must lie between 0 and 1.

aesthetics

The names of the aesthetics that this scale works with.

See Also

The documentation oncolour aesthetics.

Other alpha scales:scale_alpha_manual(),scale_alpha_identity().

Thealpha scales section of the online ggplot2 book.

Other colour scales:scale_colour_brewer(),scale_colour_continuous(),scale_colour_discrete(),scale_colour_gradient(),scale_colour_grey(),scale_colour_hue(),scale_colour_identity(),scale_colour_manual(),scale_colour_steps(),scale_colour_viridis_d()

Examples

p <- ggplot(mpg, aes(displ, hwy)) +  geom_point(aes(alpha = year))# The default range of 0.1-1.0 leaves all data visiblep# Include 0 in the range to make data invisiblep + scale_alpha(range = c(0, 1))# Changing the titlep + scale_alpha("cylinders")

Positional scales for binning continuous data (x & y)

Description

scale_x_binned() andscale_y_binned() are scales that discretizecontinuous position data. You can use these scales to transform continuousinputs before using it with a geom that requires discrete positions. Anexample is usingscale_x_binned() withgeom_bar() to create a histogram.

Usage

scale_x_binned(  name = waiver(),  n.breaks = 10,  nice.breaks = TRUE,  breaks = waiver(),  labels = waiver(),  limits = NULL,  expand = waiver(),  oob = squish,  na.value = NA_real_,  right = TRUE,  show.limits = FALSE,  transform = "identity",  trans = deprecated(),  guide = waiver(),  position = "bottom")scale_y_binned(  name = waiver(),  n.breaks = 10,  nice.breaks = TRUE,  breaks = waiver(),  labels = waiver(),  limits = NULL,  expand = waiver(),  oob = squish,  na.value = NA_real_,  right = TRUE,  show.limits = FALSE,  transform = "identity",  trans = deprecated(),  guide = waiver(),  position = "left")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

n.breaks

The number of break points to create if breaks are not givendirectly.

nice.breaks

Logical. Should breaks be attempted placed at nice valuesinstead of exactly evenly spaced between the limits. IfTRUE (default)the scale will ask the transformation object to create breaks, and thismay result in a different number of breaks than requested. Ignored ifbreaks are given explicitly.

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by thetransformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaksas output (e.g., a function returned byscales::extended_breaks()).Note that for position scales, limits are provided after scale expansion.Also accepts rlanglambda function notation.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

expand

For position scales, a vector of range expansion constants used to add somepadding around the data to ensure that they are placed some distanceaway from the axes. Use the convenience functionexpansion()to generate the values for theexpand argument. The defaults are toexpand the scale by 5% on each side for continuous variables, and by0.6 units on each side for discrete variables.

oob

One of:

  • Function that handles limits outside of the scale limits(out of bounds). Also accepts rlanglambdafunction notation.

  • The default (scales::squish()) squishes out ofbounds values into range.

  • scales::censor for replacing out of bounds values withNA.

  • scales::squish_infinite() for squishing infinite values into range.

na.value

Missing values will be replaced with this value.

right

Should the intervals be closed on the right (TRUE, default) orshould the intervals be closed on the left (FALSE)? 'Closed on the right'means that values at break positions are part of the lower bin (open on theleft), whereas they are part of the upper bin when intervals are closed onthe left (open on the right).

show.limits

should the limits of the scale appear as ticks

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

trans

[Deprecated] Deprecated in favour oftransform.

guide

A function used to create a guide or its name. Seeguides() for more information.

position

For position scales, The position of the axis.left orright for y axes,top orbottom for x axes.

See Also

Theposition documentation.

Thebinned position scales section of the online ggplot2 book.

Other position scales:scale_x_continuous(),scale_x_date(),scale_x_discrete()

Examples

# Create a histogram by binning the x-axisggplot(mtcars) +  geom_bar(aes(mpg)) +  scale_x_binned()

Sequential, diverging and qualitative colour scales from ColorBrewer

Description

Thebrewer scales provide sequential, diverging and qualitativecolour schemes from ColorBrewer. These are particularly well suited todisplay discrete values on a map. Seehttps://colorbrewer2.org formore information.

Usage

scale_colour_brewer(  name = waiver(),  ...,  type = "seq",  palette = 1,  direction = 1,  aesthetics = "colour")scale_fill_brewer(  name = waiver(),  ...,  type = "seq",  palette = 1,  direction = 1,  aesthetics = "fill")scale_colour_distiller(  name = waiver(),  ...,  type = "seq",  palette = 1,  direction = -1,  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "colourbar",  aesthetics = "colour")scale_fill_distiller(  name = waiver(),  ...,  type = "seq",  palette = 1,  direction = -1,  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "colourbar",  aesthetics = "fill")scale_colour_fermenter(  name = waiver(),  ...,  type = "seq",  palette = 1,  direction = -1,  na.value = "grey50",  guide = "coloursteps",  aesthetics = "colour")scale_fill_fermenter(  name = waiver(),  ...,  type = "seq",  palette = 1,  direction = -1,  na.value = "grey50",  guide = "coloursteps",  aesthetics = "fill")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Other arguments passed on todiscrete_scale(),continuous_scale(),orbinned_scale(), forbrewer,distiller, andfermenter variantsrespectively, to control name, limits, breaks, labels and so forth.

type

One of "seq" (sequential), "div" (diverging) or "qual"(qualitative)

palette

If a string, will use that named palette. If a number, will index intothe list of palettes of appropriatetype. The list of available palettes can foundin the Palettes section.

direction

Sets the order of colours in the scale. If 1, the default,colours are as output byRColorBrewer::brewer.pal(). If -1, theorder of colours is reversed.

aesthetics

Character string or vector of character strings listing thename(s) of the aesthetic(s) that this scale works with. This can be useful, forexample, to apply colour settings to thecolour andfill aesthetics at thesame time, viaaesthetics = c("colour", "fill").

values

if colours should not be evenly positioned along the gradientthis vector gives the position (between 0 and 1) for each colour in thecolours vector. Seerescale() for a convenience functionto map an arbitrary range to between 0 and 1.

space

colour space in which to calculate gradient. Must be "Lab" -other values are deprecated.

na.value

Colour to use for missing values

guide

Type of legend. Use"colourbar" for continuouscolour bar, or"legend" for discrete colour legend.

Details

Thebrewer scales were carefully designed and tested on discrete data.They were not designed to be extended to continuous data, but results oftenlook good. Your mileage may vary.

Palettes

The following palettes are available for use with these scales:

Diverging

BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral

Qualitative

Accent, Dark2, Paired, Pastel1, Pastel2, Set1, Set2, Set3

Sequential

Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges,OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd

Modify the palette through thepalette argument.

Note

Thedistiller scales extendbrewer scales by smoothlyinterpolating 7 colours from any palette to a continuous scale.Thedistiller scales have a default direction = -1. To reverse, use direction = 1.Thefermenter scales provide binned versions of thebrewer scales.

See Also

The documentation oncolour aesthetics.

Thebrewer scales section of the online ggplot2 book.

Other colour scales:scale_alpha(),scale_colour_continuous(),scale_colour_discrete(),scale_colour_gradient(),scale_colour_grey(),scale_colour_hue(),scale_colour_identity(),scale_colour_manual(),scale_colour_steps(),scale_colour_viridis_d()

Examples

set.seed(596)dsamp <- diamonds[sample(nrow(diamonds), 1000), ](d <- ggplot(dsamp, aes(carat, price)) +  geom_point(aes(colour = clarity)))d + scale_colour_brewer()# Change scale labeld + scale_colour_brewer("Diamond\nclarity")# Select brewer palette to use, see ?scales::pal_brewer for more detailsd + scale_colour_brewer(palette = "Greens")d + scale_colour_brewer(palette = "Set1")# scale_fill_brewer works just the same as# scale_colour_brewer but for fill coloursp <- ggplot(diamonds, aes(x = price, fill = cut)) +  geom_histogram(position = "dodge", binwidth = 1000)p + scale_fill_brewer()# the order of colour can be reversedp + scale_fill_brewer(direction = -1)# the brewer scales look better on a darker backgroundp +  scale_fill_brewer(direction = -1) +  theme_dark()# Use distiller variant with continuous datav <- ggplot(faithfuld) +  geom_tile(aes(waiting, eruptions, fill = density))vv + scale_fill_distiller()v + scale_fill_distiller(palette = "Spectral")# the order of colour can be reversed, but with scale_*_distiller(),# the default direction = -1, so to reverse, use direction = 1.v + scale_fill_distiller(palette = "Spectral", direction = 1)# or use blender variants to discretise continuous datav + scale_fill_fermenter()

Continuous and binned colour scales

Description

The scalesscale_colour_continuous() andscale_fill_continuous() arethe default colour scales ggplot2 uses when continuous data values aremapped onto thecolour orfill aesthetics, respectively. The scalesscale_colour_binned() andscale_fill_binned() are equivalent scalefunctions that assign discrete color bins to the continuous valuesinstead of using a continuous color spectrum.

Usage

scale_colour_continuous(  ...,  palette = NULL,  aesthetics = "colour",  guide = "colourbar",  na.value = "grey50",  type = getOption("ggplot2.continuous.colour"))scale_fill_continuous(  ...,  palette = NULL,  aesthetics = "fill",  guide = "colourbar",  na.value = "grey50",  type = getOption("ggplot2.continuous.fill"))scale_colour_binned(  ...,  palette = NULL,  aesthetics = "colour",  guide = "coloursteps",  na.value = "grey50",  type = getOption("ggplot2.binned.colour"))scale_fill_binned(  ...,  palette = NULL,  aesthetics = "fill",  guide = "coloursteps",  na.value = "grey50",  type = getOption("ggplot2.binned.fill"))

Arguments

...

Arguments passed on tocontinuous_scale,binned_scale

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by thetransformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaksas output (e.g., a function returned byscales::extended_breaks()).Note that for position scales, limits are provided after scale expansion.Also accepts rlanglambda function notation.

n.breaks

An integer guiding the number of major breaks. The algorithmmay choose a slightly different number to ensure nice break labels. Willonly have an effect ifbreaks = waiver(). UseNULL to use the defaultnumber of breaks given by the transformation.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

rescaler

A function used to scale the input values to therange [0, 1]. This is alwaysscales::rescale(), except fordiverging and n colour gradients (i.e.,scale_colour_gradient2(),scale_colour_gradientn()). Therescaler is ignored by positionscales, which always usescales::rescale(). Also accepts rlanglambda function notation.

oob

One of:

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

position

For position scales, The position of the axis.left orright for y axes,top orbottom for x axes.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

nice.breaks

Logical. Should breaks be attempted placed at nice valuesinstead of exactly evenly spaced between the limits. IfTRUE (default)the scale will ask the transformation object to create breaks, and thismay result in a different number of breaks than requested. Ignored ifbreaks are given explicitly.

right

Should the intervals be closed on the right (TRUE, default) orshould the intervals be closed on the left (FALSE)? 'Closed on the right'means that values at break positions are part of the lower bin (open on theleft), whereas they are part of the upper bin when intervals are closed onthe left (open on the right).

show.limits

should the limits of the scale appear as ticks

palette

One of the following:

  • NULL for the default palette stored in the theme.

  • a character vector of colours.

  • a single string naming a palette.

  • a palette function that when called with a numeric vector with valuesbetween 0 and 1 returns the corresponding output values.

aesthetics

The names of the aesthetics that this scale works with.

guide

A function used to create a guide or its name. Seeguides() for more information.

na.value

Missing values will be replaced with this value.

type

[Superseded] The preferred mechanism forsetting the default palette is by using the theme. For example:theme(palette.colour.discrete = "viridis").

Details

[Superseded]: The mechanism of setting defaults viaoptions() is superseded by theme settings. The preferred method to changethe default palette of scales is via the theme, for example:theme(palette.colour.continuous = scales::pal_viridis()). Theggplot2.continuous.colour andggplot2.continuous.fill options could beused to set default continuous scales andggplot2.binned.colour andggplot2.binned.fill options to set default binned scales.

These scale functions are meant to provide simple defaults. Ifyou want to manually set the colors of a scale, consider usingscale_colour_gradient() orscale_colour_steps().

Color Blindness

Many color palettes derived from RGB combinations (like the "rainbow" colorpalette) are not suitable to support all viewers, especially those withcolor vision deficiencies. Usingviridis type, which is perceptuallyuniform in both colour and black-and-white display is an easy option toensure good perceptive properties of your visualizations.The colorspace package offers functionalities

For more information on color vision deficiencies and suitable color choicessee thepaper on the colorspace packageand references therein.

See Also

continuous_scale() andbinned_scale()

The documentation oncolour aesthetics.

Thecontinuous colour scales section of the online ggplot2 book.

Other colour scales:scale_alpha(),scale_colour_brewer(),scale_colour_discrete(),scale_colour_gradient(),scale_colour_grey(),scale_colour_hue(),scale_colour_identity(),scale_colour_manual(),scale_colour_steps(),scale_colour_viridis_d()

Examples

# A standard plotp <- ggplot(mpg, aes(displ, hwy, colour = cty)) +  geom_point()# You can use the scale to give a palette directlyp + scale_colour_continuous(palette = c("#FEE0D2", "#FC9272", "#DE2D26"))# The default colours are encoded into the themep + theme(palette.colour.continuous = c("#DEEBF7", "#9ECAE1", "#3182BD"))# You can globally set default colour palette via the themeold <- update_theme(palette.colour.continuous = c("#E5F5E0", "#A1D99B", "#31A354"))# Plot now shows new global defaultp# The default binned colour scale uses the continuous palettep + scale_colour_binned() +  theme(palette.colour.continuous = c("#EFEDF5", "#BCBDDC", "#756BB1"))# Restoring the previous themetheme_set(old)

Discrete colour scales

Description

The default discrete colour scale.

Usage

scale_colour_discrete(  ...,  palette = NULL,  aesthetics = "colour",  na.value = "grey50",  type = getOption("ggplot2.discrete.colour"))scale_fill_discrete(  ...,  palette = NULL,  aesthetics = "fill",  na.value = "grey50",  type = getOption("ggplot2.discrete.fill"))

Arguments

...

Arguments passed on todiscrete_scale

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks (the scale limits)

  • A character vector of breaks

  • A function that takes the limits as input and returns breaksas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale values

  • A character vector that defines possible values of the scale and theirorder

  • A function that accepts the existing (automatic) values and returnsnew ones. Also accepts rlanglambda functionnotation.

drop

Should unused factor levels be omitted from the scale?The default,TRUE, uses the levels that appear in the data;FALSE includes the levels in the factor. Please note that to displayevery level in a legend, the layer should useshow.legend = TRUE.

na.translate

Unlike continuous scales, discrete scales can easily showmissing values, and do so by default. If you want to remove missing valuesfrom a discrete scale, specifyna.translate = FALSE.

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

guide

A function used to create a guide or its name. Seeguides() for more information.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

palette

One of the following:

  • NULL for the default palette stored in the theme.

  • a character vector of colours.

  • a single string naming a palette.

  • a palette function that when called with a single integer argument (thenumber of levels in the scale) returns the values that they should take.

aesthetics

The names of the aesthetics that this scale works with.

na.value

Ifna.translate = TRUE, what aesthetic value should themissing values be displayed as? Does not apply to position scaleswhereNA is always placed at the far right.

type

[Superseded] The preferred mechanism forsetting the default palette is by using the theme. For example:theme(palette.colour.discrete = "Okabe-Ito").

See Also

discrete_scale()

Thediscrete colour scales section of the online ggplot2 book.

Other colour scales:scale_alpha(),scale_colour_brewer(),scale_colour_continuous(),scale_colour_gradient(),scale_colour_grey(),scale_colour_hue(),scale_colour_identity(),scale_colour_manual(),scale_colour_steps(),scale_colour_viridis_d()

Examples

# A standard plotp <- ggplot(mpg, aes(displ, hwy, colour = class)) +  geom_point()# You can use the scale to give a palette directlyp + scale_colour_discrete(palette = scales::pal_brewer(palette = "Dark2"))# The default colours are encoded into the themep + theme(palette.colour.discrete = scales::pal_grey())# You can globally set default colour palette via the themeold <- update_theme(palette.colour.discrete = scales::pal_viridis())# Plot now shows new global defaultp# Restoring the previous themetheme_set(old)

Gradient colour scales

Description

⁠scale_*_gradient⁠ creates a two colour gradient (low-high),⁠scale_*_gradient2⁠ creates a diverging colour gradient (low-mid-high),⁠scale_*_gradientn⁠ creates a n-colour gradient. For binned variants ofthese scales, see thecolor steps scales.

Usage

scale_colour_gradient(  name = waiver(),  ...,  low = "#132B43",  high = "#56B1F7",  space = "Lab",  na.value = "grey50",  guide = "colourbar",  aesthetics = "colour")scale_fill_gradient(  name = waiver(),  ...,  low = "#132B43",  high = "#56B1F7",  space = "Lab",  na.value = "grey50",  guide = "colourbar",  aesthetics = "fill")scale_colour_gradient2(  name = waiver(),  ...,  low = muted("red"),  mid = "white",  high = muted("blue"),  midpoint = 0,  space = "Lab",  na.value = "grey50",  transform = "identity",  guide = "colourbar",  aesthetics = "colour")scale_fill_gradient2(  name = waiver(),  ...,  low = muted("red"),  mid = "white",  high = muted("blue"),  midpoint = 0,  space = "Lab",  na.value = "grey50",  transform = "identity",  guide = "colourbar",  aesthetics = "fill")scale_colour_gradientn(  name = waiver(),  ...,  colours,  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "colourbar",  aesthetics = "colour",  colors)scale_fill_gradientn(  name = waiver(),  ...,  colours,  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "colourbar",  aesthetics = "fill",  colors)

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Arguments passed on tocontinuous_scale

scale_name

[Deprecated] The name of the scalethat should be used for error messages associated with this scale.

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by thetransformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaksas output (e.g., a function returned byscales::extended_breaks()).Note that for position scales, limits are provided after scale expansion.Also accepts rlanglambda function notation.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

n.breaks

An integer guiding the number of major breaks. The algorithmmay choose a slightly different number to ensure nice break labels. Willonly have an effect ifbreaks = waiver(). UseNULL to use the defaultnumber of breaks given by the transformation.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

rescaler

A function used to scale the input values to therange [0, 1]. This is alwaysscales::rescale(), except fordiverging and n colour gradients (i.e.,scale_colour_gradient2(),scale_colour_gradientn()). Therescaler is ignored by positionscales, which always usescales::rescale(). Also accepts rlanglambda function notation.

oob

One of:

trans

[Deprecated] Deprecated in favour oftransform.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

low,high

Colours for low and high ends of the gradient.

space

colour space in which to calculate gradient. Must be "Lab" -other values are deprecated.

na.value

Colour to use for missing values

guide

Type of legend. Use"colourbar" for continuouscolour bar, or"legend" for discrete colour legend.

aesthetics

Character string or vector of character strings listing thename(s) of the aesthetic(s) that this scale works with. This can be useful, forexample, to apply colour settings to thecolour andfill aesthetics at thesame time, viaaesthetics = c("colour", "fill").

mid

colour for mid point

midpoint

The midpoint (in data value) of the diverging scale.Defaults to 0.

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

colours,colors

Vector of colours to use for n-colour gradient.

values

if colours should not be evenly positioned along the gradientthis vector gives the position (between 0 and 1) for each colour in thecolours vector. Seerescale() for a convenience functionto map an arbitrary range to between 0 and 1.

Details

Default colours are generated withmunsell andmnsl(c("2.5PB 2/4", "2.5PB 7/10")). Generally, for continuouscolour scales you want to keep hue constant, but vary chroma andluminance. Themunsell package makes this easy to do using theMunsell colour system.

See Also

scales::pal_seq_gradient() for details on underlyingpalette,scale_colour_steps() for binned variants of these scales.

The documentation oncolour aesthetics.

Other colour scales:scale_alpha(),scale_colour_brewer(),scale_colour_continuous(),scale_colour_discrete(),scale_colour_grey(),scale_colour_hue(),scale_colour_identity(),scale_colour_manual(),scale_colour_steps(),scale_colour_viridis_d()

Examples

set.seed(1)df <- data.frame(  x = runif(100),  y = runif(100),  z1 = rnorm(100),  z2 = abs(rnorm(100)))df_na <- data.frame(  value = seq(1, 20),  x = runif(20),  y = runif(20),  z1 = c(rep(NA, 10), rnorm(10)))# Default colour scale colours from light blue to dark blueggplot(df, aes(x, y)) +  geom_point(aes(colour = z2))# For diverging colour scales use gradient2ggplot(df, aes(x, y)) +  geom_point(aes(colour = z1)) +  scale_colour_gradient2()# Use your own colour scale with gradientnggplot(df, aes(x, y)) +  geom_point(aes(colour = z1)) +  scale_colour_gradientn(colours = terrain.colors(10))# The gradientn scale can be centered by using a rescalerggplot(df, aes(x, y)) +  geom_point(aes(colour = z1)) +  scale_colour_gradientn(    colours = c("blue", "dodgerblue", "white", "orange", "red"),    rescaler = ~ scales::rescale_mid(.x, mid = 0)  )# Equivalent fill scales do the same job for the fill aestheticggplot(faithfuld, aes(waiting, eruptions)) +  geom_raster(aes(fill = density)) +  scale_fill_gradientn(colours = terrain.colors(10))# Adjust colour choices with low and highggplot(df, aes(x, y)) +  geom_point(aes(colour = z2)) +  scale_colour_gradient(low = "white", high = "black")# Avoid red-green colour contrasts because ~10% of men have difficulty# seeing them# Use `na.value = NA` to hide missing values but keep the original axis rangeggplot(df_na, aes(x = value, y)) +  geom_bar(aes(fill = z1), stat = "identity") +  scale_fill_gradient(low = "yellow", high = "red", na.value = NA) ggplot(df_na, aes(x, y)) +   geom_point(aes(colour = z1)) +   scale_colour_gradient(low = "yellow", high = "red", na.value = NA)

Sequential grey colour scales

Description

Based ongray.colors(). This is black and white equivalentofscale_colour_gradient().

Usage

scale_colour_grey(  name = waiver(),  ...,  start = 0.2,  end = 0.8,  na.value = "red",  aesthetics = "colour")scale_fill_grey(  name = waiver(),  ...,  start = 0.2,  end = 0.8,  na.value = "red",  aesthetics = "fill")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Arguments passed on todiscrete_scale

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks (the scale limits)

  • A character vector of breaks

  • A function that takes the limits as input and returns breaksas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale values

  • A character vector that defines possible values of the scale and theirorder

  • A function that accepts the existing (automatic) values and returnsnew ones. Also accepts rlanglambda functionnotation.

drop

Should unused factor levels be omitted from the scale?The default,TRUE, uses the levels that appear in the data;FALSE includes the levels in the factor. Please note that to displayevery level in a legend, the layer should useshow.legend = TRUE.

na.translate

Unlike continuous scales, discrete scales can easily showmissing values, and do so by default. If you want to remove missing valuesfrom a discrete scale, specifyna.translate = FALSE.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

guide

A function used to create a guide or its name. Seeguides() for more information.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

start

grey value at low end of palette

end

grey value at high end of palette

na.value

Colour to use for missing values

aesthetics

Character string or vector of character strings listing thename(s) of the aesthetic(s) that this scale works with. This can be useful, forexample, to apply colour settings to thecolour andfill aesthetics at thesame time, viaaesthetics = c("colour", "fill").

See Also

The documentation oncolour aesthetics.

Thehue and grey scales section of the online ggplot2 book.

Other colour scales:scale_alpha(),scale_colour_brewer(),scale_colour_continuous(),scale_colour_discrete(),scale_colour_gradient(),scale_colour_hue(),scale_colour_identity(),scale_colour_manual(),scale_colour_steps(),scale_colour_viridis_d()

Examples

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl)))p + scale_colour_grey()p + scale_colour_grey(end = 0)# You may want to turn off the pale grey background with this scalep + scale_colour_grey() + theme_bw()# Colour of missing values is controlled with na.value:miss <- factor(sample(c(NA, 1:5), nrow(mtcars), replace = TRUE))ggplot(mtcars, aes(mpg, wt)) +  geom_point(aes(colour = miss)) +  scale_colour_grey()ggplot(mtcars, aes(mpg, wt)) +  geom_point(aes(colour = miss)) +  scale_colour_grey(na.value = "green")

Evenly spaced colours for discrete data

Description

Maps each level to an evenly spaced hue on the colour wheel.It does not generate colour-blind safe palettes.

Usage

scale_colour_hue(  name = waiver(),  ...,  h = c(0, 360) + 15,  c = 100,  l = 65,  h.start = 0,  direction = 1,  na.value = "grey50",  aesthetics = "colour")scale_fill_hue(  name = waiver(),  ...,  h = c(0, 360) + 15,  c = 100,  l = 65,  h.start = 0,  direction = 1,  na.value = "grey50",  aesthetics = "fill")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Arguments passed on todiscrete_scale

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks (the scale limits)

  • A character vector of breaks

  • A function that takes the limits as input and returns breaksas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale values

  • A character vector that defines possible values of the scale and theirorder

  • A function that accepts the existing (automatic) values and returnsnew ones. Also accepts rlanglambda functionnotation.

drop

Should unused factor levels be omitted from the scale?The default,TRUE, uses the levels that appear in the data;FALSE includes the levels in the factor. Please note that to displayevery level in a legend, the layer should useshow.legend = TRUE.

na.translate

Unlike continuous scales, discrete scales can easily showmissing values, and do so by default. If you want to remove missing valuesfrom a discrete scale, specifyna.translate = FALSE.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

guide

A function used to create a guide or its name. Seeguides() for more information.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

h

range of hues to use, in [0, 360]

c

chroma (intensity of colour), maximum value varies depending oncombination of hue and luminance.

l

luminance (lightness), in [0, 100]

h.start

hue to start at

direction

direction to travel around the colour wheel,1 = clockwise, -1 = counter-clockwise

na.value

Colour to use for missing values

aesthetics

Character string or vector of character strings listing thename(s) of the aesthetic(s) that this scale works with. This can be useful, forexample, to apply colour settings to thecolour andfill aesthetics at thesame time, viaaesthetics = c("colour", "fill").

See Also

The documentation oncolour aesthetics.

Thehue and grey scales section of the online ggplot2 book.

Other colour scales:scale_alpha(),scale_colour_brewer(),scale_colour_continuous(),scale_colour_discrete(),scale_colour_gradient(),scale_colour_grey(),scale_colour_identity(),scale_colour_manual(),scale_colour_steps(),scale_colour_viridis_d()

Examples

set.seed(596)dsamp <- diamonds[sample(nrow(diamonds), 1000), ](d <- ggplot(dsamp, aes(carat, price)) + geom_point(aes(colour = clarity)))# Change scale labeld + scale_colour_hue()d + scale_colour_hue("clarity")d + scale_colour_hue(expression(clarity[beta]))# Adjust luminosity and chromad + scale_colour_hue(l = 40, c = 30)d + scale_colour_hue(l = 70, c = 30)d + scale_colour_hue(l = 70, c = 150)d + scale_colour_hue(l = 80, c = 150)# Change range of hues usedd + scale_colour_hue(h = c(0, 90))d + scale_colour_hue(h = c(90, 180))d + scale_colour_hue(h = c(180, 270))d + scale_colour_hue(h = c(270, 360))# Vary opacity# (only works with pdf, quartz and cairo devices)d <- ggplot(dsamp, aes(carat, price, colour = clarity))d + geom_point(alpha = 0.9)d + geom_point(alpha = 0.5)d + geom_point(alpha = 0.2)# Colour of missing values is controlled with na.value:miss <- factor(sample(c(NA, 1:5), nrow(mtcars), replace = TRUE))ggplot(mtcars, aes(mpg, wt)) +  geom_point(aes(colour = miss))ggplot(mtcars, aes(mpg, wt)) +  geom_point(aes(colour = miss)) +  scale_colour_hue(na.value = "black")

Binned gradient colour scales

Description

⁠scale_*_steps⁠ creates a two colour binned gradient (low-high),⁠scale_*_steps2⁠ creates a diverging binned colour gradient (low-mid-high),and⁠scale_*_stepsn⁠ creates a n-colour binned gradient. These scales arebinned variants of thegradient scale family andworks in the same way.

Usage

scale_colour_steps(  name = waiver(),  ...,  low = "#132B43",  high = "#56B1F7",  space = "Lab",  na.value = "grey50",  guide = "coloursteps",  aesthetics = "colour")scale_colour_steps2(  name = waiver(),  ...,  low = muted("red"),  mid = "white",  high = muted("blue"),  midpoint = 0,  space = "Lab",  na.value = "grey50",  transform = "identity",  guide = "coloursteps",  aesthetics = "colour")scale_colour_stepsn(  name = waiver(),  ...,  colours,  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "coloursteps",  aesthetics = "colour",  colors)scale_fill_steps(  name = waiver(),  ...,  low = "#132B43",  high = "#56B1F7",  space = "Lab",  na.value = "grey50",  guide = "coloursteps",  aesthetics = "fill")scale_fill_steps2(  name = waiver(),  ...,  low = muted("red"),  mid = "white",  high = muted("blue"),  midpoint = 0,  space = "Lab",  na.value = "grey50",  transform = "identity",  guide = "coloursteps",  aesthetics = "fill")scale_fill_stepsn(  name = waiver(),  ...,  colours,  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "coloursteps",  aesthetics = "fill",  colors)

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Arguments passed on tobinned_scale

n.breaks

The number of break points to create if breaks are not givendirectly.

nice.breaks

Logical. Should breaks be attempted placed at nice valuesinstead of exactly evenly spaced between the limits. IfTRUE (default)the scale will ask the transformation object to create breaks, and thismay result in a different number of breaks than requested. Ignored ifbreaks are given explicitly.

oob

One of:

  • Function that handles limits outside of the scale limits(out of bounds). Also accepts rlanglambdafunction notation.

  • The default (scales::squish()) squishes out ofbounds values into range.

  • scales::censor for replacing out of bounds values withNA.

  • scales::squish_infinite() for squishing infinite values into range.

right

Should the intervals be closed on the right (TRUE, default) orshould the intervals be closed on the left (FALSE)? 'Closed on the right'means that values at break positions are part of the lower bin (open on theleft), whereas they are part of the upper bin when intervals are closed onthe left (open on the right).

show.limits

should the limits of the scale appear as ticks

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by thetransformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaksas output (e.g., a function returned byscales::extended_breaks()).Note that for position scales, limits are provided after scale expansion.Also accepts rlanglambda function notation.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

trans

[Deprecated] Deprecated in favour oftransform.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

low,high

Colours for low and high ends of the gradient.

space

colour space in which to calculate gradient. Must be "Lab" -other values are deprecated.

na.value

Colour to use for missing values

guide

Type of legend. Use"colourbar" for continuouscolour bar, or"legend" for discrete colour legend.

aesthetics

Character string or vector of character strings listing thename(s) of the aesthetic(s) that this scale works with. This can be useful, forexample, to apply colour settings to thecolour andfill aesthetics at thesame time, viaaesthetics = c("colour", "fill").

mid

colour for mid point

midpoint

The midpoint (in data value) of the diverging scale.Defaults to 0.

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

colours,colors

Vector of colours to use for n-colour gradient.

values

if colours should not be evenly positioned along the gradientthis vector gives the position (between 0 and 1) for each colour in thecolours vector. Seerescale() for a convenience functionto map an arbitrary range to between 0 and 1.

Details

Default colours are generated withmunsell andmnsl(c("2.5PB 2/4", "2.5PB 7/10")). Generally, for continuouscolour scales you want to keep hue constant, but vary chroma andluminance. Themunsell package makes this easy to do using theMunsell colour system.

See Also

scales::pal_seq_gradient() for details on underlying palette,scale_colour_gradient() for continuous scales without binning.

The documentation oncolour aesthetics.

Thebinned colour scales section of the online ggplot2 book.

Other colour scales:scale_alpha(),scale_colour_brewer(),scale_colour_continuous(),scale_colour_discrete(),scale_colour_gradient(),scale_colour_grey(),scale_colour_hue(),scale_colour_identity(),scale_colour_manual(),scale_colour_viridis_d()

Examples

set.seed(1)df <- data.frame(  x = runif(100),  y = runif(100),  z1 = rnorm(100))# Use scale_colour_steps for a standard binned gradientggplot(df, aes(x, y)) +  geom_point(aes(colour = z1)) +  scale_colour_steps()# Get a divergent binned scale with the *2 variantggplot(df, aes(x, y)) +  geom_point(aes(colour = z1)) +  scale_colour_steps2()# Define your own colour ramp to extract binned colours fromggplot(df, aes(x, y)) +  geom_point(aes(colour = z1)) +  scale_colour_stepsn(colours = terrain.colors(10))

Viridis colour scales from viridisLite

Description

Theviridis scales provide colour maps that are perceptually uniform in bothcolour and black-and-white. They are also designed to be perceived by viewerswith common forms of colour blindness. See alsohttps://bids.github.io/colormap/.

Usage

scale_colour_viridis_d(  name = waiver(),  ...,  alpha = 1,  begin = 0,  end = 1,  direction = 1,  option = "D",  aesthetics = "colour")scale_fill_viridis_d(  name = waiver(),  ...,  alpha = 1,  begin = 0,  end = 1,  direction = 1,  option = "D",  aesthetics = "fill")scale_colour_viridis_c(  name = waiver(),  ...,  alpha = 1,  begin = 0,  end = 1,  direction = 1,  option = "D",  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "colourbar",  aesthetics = "colour")scale_fill_viridis_c(  name = waiver(),  ...,  alpha = 1,  begin = 0,  end = 1,  direction = 1,  option = "D",  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "colourbar",  aesthetics = "fill")scale_colour_viridis_b(  name = waiver(),  ...,  alpha = 1,  begin = 0,  end = 1,  direction = 1,  option = "D",  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "coloursteps",  aesthetics = "colour")scale_fill_viridis_b(  name = waiver(),  ...,  alpha = 1,  begin = 0,  end = 1,  direction = 1,  option = "D",  values = NULL,  space = "Lab",  na.value = "grey50",  guide = "coloursteps",  aesthetics = "fill")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Other arguments passed on todiscrete_scale(),continuous_scale(), orbinned_scale() to control name, limits, breaks,labels and so forth.

alpha

The alpha transparency, a number in [0,1], see argument alpha inhsv.

begin,end

The (corrected) hue in⁠[0,1]⁠ at which the color mapbegins and ends.

direction

Sets the order of colors in the scale. If 1, the default,colors are ordered from darkest to lightest. If -1, the order of colors isreversed.

option

A character string indicating the color map option to use.Eight options are available:

  • "magma" (or"A")

  • "inferno" (or"B")

  • "plasma" (or"C")

  • "viridis" (or"D")

  • "cividis" (or"E")

  • "rocket" (or"F")

  • "mako" (or"G")

  • "turbo" (or"H")

aesthetics

Character string or vector of character strings listing thename(s) of the aesthetic(s) that this scale works with. This can be useful, forexample, to apply colour settings to thecolour andfill aesthetics at thesame time, viaaesthetics = c("colour", "fill").

values

if colours should not be evenly positioned along the gradientthis vector gives the position (between 0 and 1) for each colour in thecolours vector. Seerescale() for a convenience functionto map an arbitrary range to between 0 and 1.

space

colour space in which to calculate gradient. Must be "Lab" -other values are deprecated.

na.value

Missing values will be replaced with this value.

guide

A function used to create a guide or its name. Seeguides() for more information.

See Also

The documentation oncolour aesthetics.

Other colour scales:scale_alpha(),scale_colour_brewer(),scale_colour_continuous(),scale_colour_discrete(),scale_colour_gradient(),scale_colour_grey(),scale_colour_hue(),scale_colour_identity(),scale_colour_manual(),scale_colour_steps()

Examples

# viridis is the default colour/fill scale for ordered factorsset.seed(596)dsamp <- diamonds[sample(nrow(diamonds), 1000), ]ggplot(dsamp, aes(carat, price)) +  geom_point(aes(colour = clarity))# Use viridis_d with discrete datatxsamp <- subset(txhousing, city %in%  c("Houston", "Fort Worth", "San Antonio", "Dallas", "Austin"))(d <- ggplot(data = txsamp, aes(x = sales, y = median)) +   geom_point(aes(colour = city)))d + scale_colour_viridis_d()# Change scale labeld + scale_colour_viridis_d("City\nCenter")# Select palette to use, see ?scales::pal_viridis for more detailsd + scale_colour_viridis_d(option = "plasma")d + scale_colour_viridis_d(option = "inferno")# scale_fill_viridis_d works just the same as# scale_colour_viridis_d but for fill coloursp <- ggplot(txsamp, aes(x = median, fill = city)) +  geom_histogram(position = "dodge", binwidth = 15000)p + scale_fill_viridis_d()# the order of colour can be reversedp + scale_fill_viridis_d(direction = -1)# Use viridis_c with continuous data(v <- ggplot(faithfuld) +  geom_tile(aes(waiting, eruptions, fill = density)))v + scale_fill_viridis_c()v + scale_fill_viridis_c(option = "plasma")# Use viridis_b to bin continuous data before mappingv + scale_fill_viridis_b()

Position scales for continuous data (x & y)

Description

scale_x_continuous() andscale_y_continuous() are the defaultscales for continuous x and y aesthetics. There are three variantsthat set thetransform argument for commonly used transformations:⁠scale_*_log10()⁠,⁠scale_*_sqrt()⁠ and⁠scale_*_reverse()⁠.

Usage

scale_x_continuous(  name = waiver(),  breaks = waiver(),  minor_breaks = waiver(),  n.breaks = NULL,  labels = waiver(),  limits = NULL,  expand = waiver(),  oob = censor,  na.value = NA_real_,  transform = "identity",  trans = deprecated(),  guide = waiver(),  position = "bottom",  sec.axis = waiver())scale_y_continuous(  name = waiver(),  breaks = waiver(),  minor_breaks = waiver(),  n.breaks = NULL,  labels = waiver(),  limits = NULL,  expand = waiver(),  oob = censor,  na.value = NA_real_,  transform = "identity",  trans = deprecated(),  guide = waiver(),  position = "left",  sec.axis = waiver())scale_x_log10(...)scale_y_log10(...)scale_x_reverse(...)scale_y_reverse(...)scale_x_sqrt(...)scale_y_sqrt(...)

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by thetransformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaksas output (e.g., a function returned byscales::extended_breaks()).Note that for position scales, limits are provided after scale expansion.Also accepts rlanglambda function notation.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

n.breaks

An integer guiding the number of major breaks. The algorithmmay choose a slightly different number to ensure nice break labels. Willonly have an effect ifbreaks = waiver(). UseNULL to use the defaultnumber of breaks given by the transformation.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

expand

For position scales, a vector of range expansion constants used to add somepadding around the data to ensure that they are placed some distanceaway from the axes. Use the convenience functionexpansion()to generate the values for theexpand argument. The defaults are toexpand the scale by 5% on each side for continuous variables, and by0.6 units on each side for discrete variables.

oob

One of:

na.value

Missing values will be replaced with this value.

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

trans

[Deprecated] Deprecated in favour oftransform.

guide

A function used to create a guide or its name. Seeguides() for more information.

position

For position scales, The position of the axis.left orright for y axes,top orbottom for x axes.

sec.axis

sec_axis() is used to specify a secondary axis.

...

Other arguments passed on to⁠scale_(x|y)_continuous()⁠

Details

For simple manipulation of labels and limits, you may wish to uselabs() andlims() instead.

See Also

Theposition documentation.

Thenumeric position scales section of the online ggplot2 book.

Other position scales:scale_x_binned(),scale_x_date(),scale_x_discrete()

Examples

p1 <- ggplot(mpg, aes(displ, hwy)) +  geom_point()p1# Manipulating the default position scales lets you:#  * change the axis labelsp1 +  scale_x_continuous("Engine displacement (L)") +  scale_y_continuous("Highway MPG")# You can also use the short-cut labs().# Use NULL to suppress axis labelsp1 + labs(x = NULL, y = NULL)#  * modify the axis limitsp1 + scale_x_continuous(limits = c(2, 6))p1 + scale_x_continuous(limits = c(0, 10))# you can also use the short hand functions `xlim()` and `ylim()`p1 + xlim(2, 6)#  * choose where the ticks appearp1 + scale_x_continuous(breaks = c(2, 4, 6))#  * choose your own labelsp1 + scale_x_continuous(  breaks = c(2, 4, 6),  label = c("two", "four", "six"))# Typically you'll pass a function to the `labels` argument.# Some common formats are built into the scales package:set.seed(1)df <- data.frame(  x = rnorm(10) * 100000,  y = seq(0, 1, length.out = 10))p2 <- ggplot(df, aes(x, y)) + geom_point()p2 + scale_y_continuous(labels = scales::label_percent())p2 + scale_y_continuous(labels = scales::label_dollar())p2 + scale_x_continuous(labels = scales::label_comma())# You can also override the default linear mapping by using a# transformation. There are three shortcuts:p1 + scale_y_log10()p1 + scale_y_sqrt()p1 + scale_y_reverse()# Or you can supply a transformation in the `trans` argument:p1 + scale_y_continuous(transform = scales::transform_reciprocal())# You can also create your own. See ?scales::new_transform

Position scales for date/time data

Description

These are the default scales for the three date/time class. These willusually be added automatically. To override manually, use⁠scale_*_date⁠ for dates (classDate),⁠scale_*_datetime⁠ for datetimes (classPOSIXct), and⁠scale_*_time⁠ for times (classhms).

Usage

scale_x_date(  name = waiver(),  breaks = waiver(),  date_breaks = waiver(),  labels = waiver(),  date_labels = waiver(),  minor_breaks = waiver(),  date_minor_breaks = waiver(),  limits = NULL,  expand = waiver(),  oob = censor,  guide = waiver(),  position = "bottom",  sec.axis = waiver())scale_y_date(  name = waiver(),  breaks = waiver(),  date_breaks = waiver(),  labels = waiver(),  date_labels = waiver(),  minor_breaks = waiver(),  date_minor_breaks = waiver(),  limits = NULL,  expand = waiver(),  oob = censor,  guide = waiver(),  position = "left",  sec.axis = waiver())scale_x_datetime(  name = waiver(),  breaks = waiver(),  date_breaks = waiver(),  labels = waiver(),  date_labels = waiver(),  minor_breaks = waiver(),  date_minor_breaks = waiver(),  timezone = NULL,  limits = NULL,  expand = waiver(),  oob = censor,  guide = waiver(),  position = "bottom",  sec.axis = waiver())scale_y_datetime(  name = waiver(),  breaks = waiver(),  date_breaks = waiver(),  labels = waiver(),  date_labels = waiver(),  minor_breaks = waiver(),  date_minor_breaks = waiver(),  timezone = NULL,  limits = NULL,  expand = waiver(),  oob = censor,  guide = waiver(),  position = "left",  sec.axis = waiver())scale_x_time(  name = waiver(),  breaks = waiver(),  date_breaks = waiver(),  minor_breaks = waiver(),  date_minor_breaks = waiver(),  labels = waiver(),  date_labels = waiver(),  limits = NULL,  expand = waiver(),  oob = censor,  na.value = NA_real_,  guide = waiver(),  position = "bottom",  sec.axis = waiver())scale_y_time(  name = waiver(),  breaks = waiver(),  date_breaks = waiver(),  minor_breaks = waiver(),  date_minor_breaks = waiver(),  labels = waiver(),  date_labels = waiver(),  limits = NULL,  expand = waiver(),  oob = censor,  na.value = NA_real_,  guide = waiver(),  position = "left",  sec.axis = waiver())

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

breaks

One of:

  • NULL for no breaks

  • waiver() for the breaks specified bydate_breaks

  • ADate/POSIXct vector giving positions of breaks

  • A function that takes the limits as input and returns breaks as output

date_breaks

A string giving the distance between breaks like "2weeks", or "10 years". If bothbreaks anddate_breaks arespecified,date_breaks wins. Valid specifications are 'sec', 'min','hour', 'day', 'week', 'month' or 'year', optionally followed by 's'.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

date_labels

A string giving the formatting specification for thelabels. Codes are defined instrftime(). If bothlabelsanddate_labels are specified,date_labels wins.

minor_breaks

One of:

  • NULL for no breaks

  • waiver() for the breaks specified bydate_minor_breaks

  • ADate/POSIXct vector giving positions of minor breaks

  • A function that takes the limits as input and returns minor breaks asoutput

date_minor_breaks

A string giving the distance between minor breakslike "2 weeks", or "10 years". If bothminor_breaks anddate_minor_breaks are specified,date_minor_breaks wins. Validspecifications are 'sec', 'min', 'hour', 'day', 'week', 'month' or 'year',optionally followed by 's'.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

expand

For position scales, a vector of range expansion constants used to add somepadding around the data to ensure that they are placed some distanceaway from the axes. Use the convenience functionexpansion()to generate the values for theexpand argument. The defaults are toexpand the scale by 5% on each side for continuous variables, and by0.6 units on each side for discrete variables.

oob

One of:

guide

A function used to create a guide or its name. Seeguides() for more information.

position

For position scales, The position of the axis.left orright for y axes,top orbottom for x axes.

sec.axis

sec_axis() is used to specify a secondary axis.

timezone

The timezone to use for display on the axes. The default(NULL) uses the timezone encoded in the data.

na.value

Missing values will be replaced with this value.

See Also

sec_axis() for how to specify secondary axes.

Thedate-time position scales section of the online ggplot2 book.

Theposition documentation.

Other position scales:scale_x_binned(),scale_x_continuous(),scale_x_discrete()

Examples

last_month <- Sys.Date() - 0:29set.seed(1)df <- data.frame(  date = last_month,  price = runif(30))base <- ggplot(df, aes(date, price)) +  geom_line()# The date scale will attempt to pick sensible defaults for# major and minor tick marks. Override with date_breaks, date_labels# date_minor_breaks arguments.base + scale_x_date(date_labels = "%b %d")base + scale_x_date(date_breaks = "1 week", date_labels = "%W")base + scale_x_date(date_minor_breaks = "1 day")# Set limitsbase + scale_x_date(limits = c(Sys.Date() - 7, NA))

Use values without scaling

Description

Use this set of scales when your data has already been scaled, i.e. italready represents aesthetic values that ggplot2 can handle directly.These scales will not produce a legend unless you also supply thebreaks,labels, and type ofguide you want.

Usage

scale_colour_identity(  name = waiver(),  ...,  guide = "none",  aesthetics = "colour")scale_fill_identity(name = waiver(), ..., guide = "none", aesthetics = "fill")scale_shape_identity(  name = waiver(),  ...,  guide = "none",  aesthetics = "shape")scale_linetype_identity(  name = waiver(),  ...,  guide = "none",  aesthetics = "linetype")scale_linewidth_identity(  name = waiver(),  ...,  guide = "none",  aesthetics = "linewidth")scale_alpha_identity(  name = waiver(),  ...,  guide = "none",  aesthetics = "alpha")scale_size_identity(name = waiver(), ..., guide = "none", aesthetics = "size")scale_discrete_identity(aesthetics, name = waiver(), ..., guide = "none")scale_continuous_identity(aesthetics, name = waiver(), ..., guide = "none")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Other arguments passed on todiscrete_scale() orcontinuous_scale()

guide

Guide to use for this scale. Defaults to"none".

aesthetics

Character string or vector of character strings listing thename(s) of the aesthetic(s) that this scale works with. This can be useful, forexample, to apply colour settings to thecolour andfill aesthetics at thesame time, viaaesthetics = c("colour", "fill").

Details

The functionsscale_colour_identity(),scale_fill_identity(),scale_size_identity(),etc. work on the aesthetics specified in the scale name:colour,fill,size,etc. However, the functionsscale_colour_identity() andscale_fill_identity() alsohave an optionalaesthetics argument that can be used to define bothcolour andfill aesthetic mappings via a single function call. The functionsscale_discrete_identity() andscale_continuous_identity() are generic scales thatcan work with any aesthetic or set of aesthetics provided via theaestheticsargument.

See Also

Theidentity scales section of the online ggplot2 book.

Other shape scales:scale_shape(),scale_shape_manual().

Other linetype scales:scale_linetype(),scale_linetype_manual().

Other alpha scales:scale_alpha(),scale_alpha_manual().

Other size scales:scale_size(),scale_size_manual().

Other colour scales:scale_alpha(),scale_colour_brewer(),scale_colour_continuous(),scale_colour_discrete(),scale_colour_gradient(),scale_colour_grey(),scale_colour_hue(),scale_colour_manual(),scale_colour_steps(),scale_colour_viridis_d()

Examples

ggplot(luv_colours, aes(u, v)) +  geom_point(aes(colour = col), size = 3) +  scale_color_identity() +  coord_fixed()df <- data.frame(  x = 1:4,  y = 1:4,  colour = c("red", "green", "blue", "yellow"))ggplot(df, aes(x, y)) + geom_tile(aes(fill = colour))ggplot(df, aes(x, y)) +  geom_tile(aes(fill = colour)) +  scale_fill_identity()# To get a legend guide, specify guide = "legend"ggplot(df, aes(x, y)) +  geom_tile(aes(fill = colour)) +  scale_fill_identity(guide = "legend")# But you'll typically also need to supply breaks and labels:ggplot(df, aes(x, y)) +  geom_tile(aes(fill = colour)) +  scale_fill_identity("trt", labels = letters[1:4], breaks = df$colour,  guide = "legend")# cyl scaled to appropriate sizeggplot(mtcars, aes(mpg, wt)) +  geom_point(aes(size = cyl))# cyl used as point sizeggplot(mtcars, aes(mpg, wt)) +  geom_point(aes(size = cyl)) +  scale_size_identity()

Scale for line patterns

Description

Default line types based on a set supplied by Richard Pearson,University of Manchester. Continuous values can not be mapped toline types unlessscale_linetype_binned() is used. Still, as linetypes hasno inherent order, this use is not advised.

Usage

scale_linetype(name = waiver(), ..., aesthetics = "linetype")scale_linetype_binned(name = waiver(), ..., aesthetics = "linetype")scale_linetype_continuous(...)scale_linetype_discrete(name = waiver(), ..., aesthetics = "linetype")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Arguments passed on todiscrete_scale

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks (the scale limits)

  • A character vector of breaks

  • A function that takes the limits as input and returns breaksas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale values

  • A character vector that defines possible values of the scale and theirorder

  • A function that accepts the existing (automatic) values and returnsnew ones. Also accepts rlanglambda functionnotation.

drop

Should unused factor levels be omitted from the scale?The default,TRUE, uses the levels that appear in the data;FALSE includes the levels in the factor. Please note that to displayevery level in a legend, the layer should useshow.legend = TRUE.

na.translate

Unlike continuous scales, discrete scales can easily showmissing values, and do so by default. If you want to remove missing valuesfrom a discrete scale, specifyna.translate = FALSE.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

guide

A function used to create a guide or its name. Seeguides() for more information.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

aesthetics

The names of the aesthetics that this scale works with.

Details

Lines can be referred to by number, name or hex code. Contrary to base Rgraphics,NAs are interpreted as blanks.

Named linetypes by number and name

See Also

The documentation fordifferentiation related aesthetics.

Other linetype scales:scale_linetype_manual(),scale_linetype_identity().

Theline type section of the online ggplot2 book.

Examples

base <- ggplot(economics_long, aes(date, value01))base + geom_line(aes(group = variable))base + geom_line(aes(linetype = variable))# See scale_manual for more flexibility# Common line types ----------------------------df_lines <- data.frame(  linetype = factor(    1:4,    labels = c("solid", "longdash", "dashed", "dotted")  ))ggplot(df_lines) +  geom_hline(aes(linetype = linetype, yintercept = 0), linewidth = 2) +  scale_linetype_identity() +  facet_grid(linetype ~ .) +  theme_void(20)

Scales for line width

Description

scale_linewidth scales the width of lines and polygon strokes. Due tohistorical reasons, it is also possible to control this with thesizeaesthetic, but usinglinewidth is encouraged to clearly differentiate areaaesthetics from stroke width aesthetics.

Usage

scale_linewidth(  name = waiver(),  breaks = waiver(),  labels = waiver(),  limits = NULL,  range = NULL,  transform = "identity",  trans = deprecated(),  guide = "legend",  aesthetics = "linewidth")scale_linewidth_binned(  name = waiver(),  breaks = waiver(),  labels = waiver(),  limits = NULL,  range = NULL,  n.breaks = NULL,  nice.breaks = TRUE,  transform = "identity",  trans = deprecated(),  guide = "bins",  aesthetics = "linewidth")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by thetransformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaksas output (e.g., a function returned byscales::extended_breaks()).Note that for position scales, limits are provided after scale expansion.Also accepts rlanglambda function notation.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

range

a numeric vector of length 2 that specifies the minimum andmaximum size of the plotting symbol after transformation.

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

trans

[Deprecated] Deprecated in favour oftransform.

guide

A function used to create a guide or its name. Seeguides() for more information.

aesthetics

The names of the aesthetics that this scale works with.

n.breaks

An integer guiding the number of major breaks. The algorithmmay choose a slightly different number to ensure nice break labels. Willonly have an effect ifbreaks = waiver(). UseNULL to use the defaultnumber of breaks given by the transformation.

nice.breaks

Logical. Should breaks be attempted placed at nice valuesinstead of exactly evenly spaced between the limits. IfTRUE (default)the scale will ask the transformation object to create breaks, and thismay result in a different number of breaks than requested. Ignored ifbreaks are given explicitly.

See Also

The documentation fordifferentiation related aesthetics.

Theline width section of the online ggplot2 book.

Examples

p <- ggplot(economics, aes(date, unemploy, linewidth = uempmed)) +  geom_line(lineend = "round")pp + scale_linewidth("Duration of\nunemployment")p + scale_linewidth(range = c(0, 4))# Binning can sometimes make it easier to match the scaled data to the legendp + scale_linewidth_binned()

Create your own discrete scale

Description

These functions allow you to specify your own set of mappings from levels in thedata to aesthetic values.

Usage

scale_colour_manual(  ...,  values,  aesthetics = "colour",  breaks = waiver(),  na.value = "grey50")scale_fill_manual(  ...,  values,  aesthetics = "fill",  breaks = waiver(),  na.value = "grey50")scale_size_manual(  ...,  values,  breaks = waiver(),  na.value = NA,  aesthetics = "size")scale_shape_manual(  ...,  values,  breaks = waiver(),  na.value = NA,  aesthetics = "shape")scale_linetype_manual(  ...,  values,  breaks = waiver(),  na.value = NA,  aesthetics = "linetype")scale_linewidth_manual(  ...,  values,  breaks = waiver(),  na.value = NA,  aesthetics = "linewidth")scale_alpha_manual(  ...,  values,  breaks = waiver(),  na.value = NA,  aesthetics = "alpha")scale_discrete_manual(aesthetics, ..., values, breaks = waiver())

Arguments

...

Arguments passed on todiscrete_scale

limits

One of:

  • NULL to use the default scale values

  • A character vector that defines possible values of the scale and theirorder

  • A function that accepts the existing (automatic) values and returnsnew ones. Also accepts rlanglambda functionnotation.

drop

Should unused factor levels be omitted from the scale?The default,TRUE, uses the levels that appear in the data;FALSE includes the levels in the factor. Please note that to displayevery level in a legend, the layer should useshow.legend = TRUE.

na.translate

Unlike continuous scales, discrete scales can easily showmissing values, and do so by default. If you want to remove missing valuesfrom a discrete scale, specifyna.translate = FALSE.

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

guide

A function used to create a guide or its name. Seeguides() for more information.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

values

a set of aesthetic values to map data values to. The valueswill be matched in order (usually alphabetical) with the limits of thescale, or withbreaks if provided. If this is a named vector, then thevalues will be matched based on the names instead. Data values that don'tmatch will be givenna.value.

aesthetics

Character string or vector of character strings listing thename(s) of the aesthetic(s) that this scale works with. This can be useful, forexample, to apply colour settings to thecolour andfill aesthetics at thesame time, viaaesthetics = c("colour", "fill").

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks (the scale limits)

  • A character vector of breaks

  • A function that takes the limits as input and returns breaksas output

na.value

The aesthetic value to use for missing (NA) values

Details

The functionsscale_colour_manual(),scale_fill_manual(),scale_size_manual(),etc. work on the aesthetics specified in the scale name:colour,fill,size,etc. However, the functionsscale_colour_manual() andscale_fill_manual() alsohave an optionalaesthetics argument that can be used to define bothcolour andfill aesthetic mappings via a single function call (see examples). The functionscale_discrete_manual() is a generic scale that can work with any aesthetic or setof aesthetics provided via theaesthetics argument.

Color Blindness

Many color palettes derived from RGB combinations (like the "rainbow" colorpalette) are not suitable to support all viewers, especially those withcolor vision deficiencies. Usingviridis type, which is perceptuallyuniform in both colour and black-and-white display is an easy option toensure good perceptive properties of your visualizations.The colorspace package offers functionalities

For more information on color vision deficiencies and suitable color choicessee thepaper on the colorspace packageand references therein.

See Also

The documentation fordifferentiation related aesthetics.

The documentation oncolour aesthetics.

Themanual scales andmanual colour scales sections of the online ggplot2 book.

Other size scales:scale_size(),scale_size_identity().

Other shape scales:scale_shape(),scale_shape_identity().

Other linetype scales:scale_linetype(),scale_linetype_identity().

Other alpha scales:scale_alpha(),scale_alpha_identity().

Other colour scales:scale_alpha(),scale_colour_brewer(),scale_colour_continuous(),scale_colour_discrete(),scale_colour_gradient(),scale_colour_grey(),scale_colour_hue(),scale_colour_identity(),scale_colour_steps(),scale_colour_viridis_d()

Examples

p <- ggplot(mtcars, aes(mpg, wt)) +  geom_point(aes(colour = factor(cyl)))p + scale_colour_manual(values = c("red", "blue", "green"))# It's recommended to use a named vectorcols <- c("8" = "red", "4" = "blue", "6" = "darkgreen", "10" = "orange")p + scale_colour_manual(values = cols)# You can set color and fill aesthetics at the same timeggplot(  mtcars,  aes(mpg, wt, colour = factor(cyl), fill = factor(cyl))) +  geom_point(shape = 21, alpha = 0.5, size = 2) +  scale_colour_manual(    values = cols,    aesthetics = c("colour", "fill")  )# As with other scales you can use breaks to control the appearance# of the legend.p + scale_colour_manual(values = cols)p + scale_colour_manual(  values = cols,  breaks = c("4", "6", "8"),  labels = c("four", "six", "eight"))# And limits to control the possible values of the scalep + scale_colour_manual(values = cols, limits = c("4", "8"))p + scale_colour_manual(values = cols, limits = c("4", "6", "8", "10"))

Scales for shapes, aka glyphs

Description

scale_shape() maps discrete variables to six easily discernible shapes.If you have more than six levels, you will get a warning message, and theseventh and subsequent levels will not appear on the plot. Usescale_shape_manual() to supply your own values. You can not mapa continuous variable to shape unlessscale_shape_binned() is used. Still,as shape has no inherent order, this use is not advised.

Usage

scale_shape(name = waiver(), ..., solid = NULL, aesthetics = "shape")scale_shape_binned(name = waiver(), ..., solid = TRUE, aesthetics = "shape")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Arguments passed on todiscrete_scale

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks (the scale limits)

  • A character vector of breaks

  • A function that takes the limits as input and returns breaksas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale values

  • A character vector that defines possible values of the scale and theirorder

  • A function that accepts the existing (automatic) values and returnsnew ones. Also accepts rlanglambda functionnotation.

drop

Should unused factor levels be omitted from the scale?The default,TRUE, uses the levels that appear in the data;FALSE includes the levels in the factor. Please note that to displayevery level in a legend, the layer should useshow.legend = TRUE.

na.translate

Unlike continuous scales, discrete scales can easily showmissing values, and do so by default. If you want to remove missing valuesfrom a discrete scale, specifyna.translate = FALSE.

na.value

Ifna.translate = TRUE, what aesthetic value should themissing values be displayed as? Does not apply to position scaleswhereNA is always placed at the far right.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

guide

A function used to create a guide or its name. Seeguides() for more information.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

solid

Should the shapes be solid,TRUE, or hollow,FALSE?

aesthetics

The names of the aesthetics that this scale works with.

Details

Shapes can be referred to by number or name. Shapes in [0, 20] do notsupport a fill aesthetic, whereas shapes in [21, 25] do.

All shapes by number and name

See Also

The documentation fordifferentiation related aesthetics.

Other shape scales:scale_shape_manual(),scale_shape_identity().

Theshape section of the online ggplot2 book.

Examples

set.seed(596)dsmall <- diamonds[sample(nrow(diamonds), 100), ](d <- ggplot(dsmall, aes(carat, price)) + geom_point(aes(shape = cut)))d + scale_shape(solid = TRUE) # the defaultd + scale_shape(solid = FALSE)d + scale_shape(name = "Cut of diamond")# To change order of levels, change order of# underlying factorlevels(dsmall$cut) <- c("Fair", "Good", "Very Good", "Premium", "Ideal")# Need to recreate plot to pick up new dataggplot(dsmall, aes(price, carat)) + geom_point(aes(shape = cut))# Show a list of available shapesdf_shapes <- data.frame(shape = 0:24)ggplot(df_shapes, aes(0, 0, shape = shape)) +  geom_point(aes(shape = shape), size = 5, fill = 'red') +  scale_shape_identity() +  facet_wrap(~shape) +  theme_void()

Scales for area or radius

Description

scale_size() scales area,scale_radius() scales radius. The sizeaesthetic is most commonly used for points and text, and humans perceivethe area of points (not their radius), so this provides for optimalperception.scale_size_area() ensures that a value of 0 is mappedto a size of 0.scale_size_binned() is a binned version ofscale_size() thatscales by area (but does not ensure 0 equals an area of zero). For a binnedequivalent ofscale_size_area() usescale_size_binned_area().

Usage

scale_size(  name = waiver(),  breaks = waiver(),  labels = waiver(),  limits = NULL,  range = NULL,  transform = "identity",  trans = deprecated(),  guide = "legend",  aesthetics = "size")scale_radius(  name = waiver(),  breaks = waiver(),  labels = waiver(),  limits = NULL,  range = c(1, 6),  transform = "identity",  trans = deprecated(),  guide = "legend",  aesthetics = "size")scale_size_binned(  name = waiver(),  breaks = waiver(),  labels = waiver(),  limits = NULL,  range = NULL,  n.breaks = NULL,  nice.breaks = TRUE,  transform = "identity",  trans = deprecated(),  guide = "bins",  aesthetics = "size")scale_size_area(name = waiver(), ..., max_size = 6, aesthetics = "size")scale_size_binned_area(name = waiver(), ..., max_size = 6, aesthetics = "size")

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by thetransformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaksas output (e.g., a function returned byscales::extended_breaks()).Note that for position scales, limits are provided after scale expansion.Also accepts rlanglambda function notation.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing limits of the scale.UseNA to refer to the existing minimum or maximum

  • A function that accepts the existing (automatic) limits and returnsnew limits. Also accepts rlanglambda functionnotation.Note that setting limits on positional scales willremove data outside of the limits.If the purpose is to zoom, use the limit argument in the coordinate system(seecoord_cartesian()).

range

a numeric vector of length 2 that specifies the minimum andmaximum size of the plotting symbol after transformation.

transform

For continuous scales, the name of a transformation objector the object itself. Built-in transformations include "asn", "atanh","boxcox", "date", "exp", "hms", "identity", "log", "log10", "log1p", "log2","logit", "modulus", "probability", "probit", "pseudo_log", "reciprocal","reverse", "sqrt" and "time".

A transformation object bundles together a transform, its inverse,and methods for generating breaks and labels. Transformation objectsare defined in the scales package, and are called⁠transform_<name>⁠. Iftransformations require arguments, you can call them from the scalespackage, e.g.scales::transform_boxcox(p = 2).You can create your own transformation withscales::new_transform().

trans

[Deprecated] Deprecated in favour oftransform.

guide

A function used to create a guide or its name. Seeguides() for more information.

aesthetics

The names of the aesthetics that this scale works with.

n.breaks

An integer guiding the number of major breaks. The algorithmmay choose a slightly different number to ensure nice break labels. Willonly have an effect ifbreaks = waiver(). UseNULL to use the defaultnumber of breaks given by the transformation.

nice.breaks

Logical. Should breaks be attempted placed at nice valuesinstead of exactly evenly spaced between the limits. IfTRUE (default)the scale will ask the transformation object to create breaks, and thismay result in a different number of breaks than requested. Ignored ifbreaks are given explicitly.

...

Arguments passed on tocontinuous_scale

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

oob

One of:

na.value

Missing values will be replaced with this value.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

max_size

Size of largest points.

Note

Historically the size aesthetic was used for two different things:Scaling the size of object (like points and glyphs) and scaling the widthof lines. From ggplot2 3.4.0 the latter has been moved to its own linewidthaesthetic. For backwards compatibility using size is still possible, but itis highly advised to switch to the new linewidth aesthetic for these cases.

See Also

scale_size_area() if you want 0 values to be mapped to points with size 0.scale_linewidth() if you want to scale the width of lines.

The documentation fordifferentiation related aesthetics.

Thesize section of the online ggplot2 book.

Examples

p <- ggplot(mpg, aes(displ, hwy, size = hwy)) +   geom_point()pp + scale_size("Highway mpg")p + scale_size(range = c(0, 10))# If you want zero value to have zero size, use scale_size_area:p + scale_size_area()# Binning can sometimes make it easier to match the scaled data to the legendp + scale_size_binned()# This is most useful when size is a countggplot(mpg, aes(class, cyl)) +  geom_count() +  scale_size_area()# If you want to map size to radius (usually bad idea), use scale_radiusp + scale_radius()

Determine default scale type

Description

You will need to define a method for this method if you want to extendggplot2 to handle new types of data. If you simply want to pass the vectorthrough as an additional aesthetic, return"identity".

Usage

scale_type(x)

Arguments

x

A vector

Value

A character vector of scale types. These will be tried in turnto find a default scale. For example, ifscale_type() returnsc("foo", "bar") and the vector is used with the colour aesthetic,ggplot2 will first look forscale_colour_foo thenscale_colour_bar.

Examples

scale_type(1:5)scale_type("test")scale_type(Sys.Date())

Position scales for discrete data

Description

scale_x_discrete() andscale_y_discrete() are used to set the values fordiscrete x and y scale aesthetics. For simple manipulation of scale labelsand limits, you may wish to uselabs() andlims() instead.

Usage

scale_x_discrete(  name = waiver(),  ...,  palette = seq_len,  expand = waiver(),  guide = waiver(),  position = "bottom",  sec.axis = waiver(),  continuous.limits = NULL)scale_y_discrete(  name = waiver(),  ...,  palette = seq_len,  expand = waiver(),  guide = waiver(),  position = "left",  sec.axis = waiver(),  continuous.limits = NULL)

Arguments

name

The name of the scale. Used as the axis or legend title. Ifwaiver(), the default, the name of the scale is taken from the firstmapping used for that aesthetic. IfNULL, the legend title will beomitted.

...

Arguments passed on todiscrete_scale

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks (the scale limits)

  • A character vector of breaks

  • A function that takes the limits as input and returns breaksas output. Also accepts rlanglambda functionnotation.

limits

One of:

  • NULL to use the default scale values

  • A character vector that defines possible values of the scale and theirorder

  • A function that accepts the existing (automatic) values and returnsnew ones. Also accepts rlanglambda functionnotation.

drop

Should unused factor levels be omitted from the scale?The default,TRUE, uses the levels that appear in the data;FALSE includes the levels in the factor. Please note that to displayevery level in a legend, the layer should useshow.legend = TRUE.

na.translate

Unlike continuous scales, discrete scales can easily showmissing values, and do so by default. If you want to remove missing valuesfrom a discrete scale, specifyna.translate = FALSE.

na.value

Ifna.translate = TRUE, what aesthetic value should themissing values be displayed as? Does not apply to position scaleswhereNA is always placed at the far right.

aesthetics

The names of the aesthetics that this scale works with.

minor_breaks

One of:

  • NULL for no minor breaks

  • waiver() for the default breaks (none for discrete, one minor breakbetween each major break for continuous)

  • A numeric vector of positions

  • A function that given the limits returns a vector of minor breaks. Alsoaccepts rlanglambda function notation. Whenthe function has two arguments, it will be given the limits and majorbreak positions.

labels

One of the options below. Please note that whenlabels is avector, it is highly recommended to also set thebreaks argument as avector to protect against unintended mismatches.

  • NULL for no labels

  • waiver() for the default labels computed by thetransformation object

  • A character vector giving labels (must be same length asbreaks)

  • An expression vector (must be the same length as breaks). See ?plotmath for details.

  • A function that takes the breaks as input and returns labelsas output. Also accepts rlanglambda functionnotation.

call

Thecall used to construct the scale for reporting messages.

super

The super class to use for the constructed scale

palette

A palette function that when called with a single integerargument (the number of levels in the scale) returns the numerical valuesthat they should take.

expand

For position scales, a vector of range expansion constants used to add somepadding around the data to ensure that they are placed some distanceaway from the axes. Use the convenience functionexpansion()to generate the values for theexpand argument. The defaults are toexpand the scale by 5% on each side for continuous variables, and by0.6 units on each side for discrete variables.

guide

A function used to create a guide or its name. Seeguides() for more information.

position

For position scales, The position of the axis.left orright for y axes,top orbottom for x axes.

sec.axis

dup_axis() is used to specify a secondary axis.

continuous.limits

One of:

  • NULL to use the default scale range

  • A numeric vector of length two providing a display range for the scale.UseNA to refer to the existing minimum or maximum.

  • A function that accepts the limits and returns a numeric vector oflength two.

Details

You can use continuous positions even with a discrete position scale -this allows you (e.g.) to place labels between bars in a bar chart.Continuous positions are numeric values starting at one for the firstlevel, and increasing by one for each level (i.e. the labels are placedat integer positions). This is what allows jittering to work.

See Also

Theposition documentation.

Thediscrete position scales section of the online ggplot2 book.

Other position scales:scale_x_binned(),scale_x_continuous(),scale_x_date()

Examples

ggplot(diamonds, aes(cut)) + geom_bar()# The discrete position scale is added automatically whenever you# have a discrete position.(d <- ggplot(subset(diamonds, carat > 1), aes(cut, clarity)) +      geom_jitter())d + scale_x_discrete("Cut")d +  scale_x_discrete(    "Cut",    labels = c(      "Fair" = "F",      "Good" = "G",      "Very Good" = "VG",      "Perfect" = "P",      "Ideal" = "I"    )  )# Use limits to adjust the which levels (and in what order)# are displayedd + scale_x_discrete(limits = c("Fair","Ideal"))# you can also use the short hand functions xlim and ylimd + xlim("Fair","Ideal", "Good")d + ylim("I1", "IF")# See ?reorder to reorder based on the values of another variableggplot(mpg, aes(manufacturer, cty)) +  geom_point()ggplot(mpg, aes(reorder(manufacturer, cty), cty)) +  geom_point()ggplot(mpg, aes(reorder(manufacturer, displ), cty)) +  geom_point()# Use abbreviate as a formatter to reduce long namesggplot(mpg, aes(reorder(manufacturer, displ), cty)) +  geom_point() +  scale_x_discrete(labels = abbreviate)

Vector field of seal movements

Description

This vector field was produced from the data described in Brillinger, D.R.,Preisler, H.K., Ager, A.A. and Kie, J.G. "An exploratory data analysis(EDA) of the paths of moving animals". J. Statistical Planning andInference 122 (2004), 43-63, using the methods of Brillinger, D.R.,"Learning a potential function from a trajectory", Signal ProcessingLetters. December (2007).

Usage

seals

Format

A data frame with 1155 rows and 4 variables

References

https://www.stat.berkeley.edu/~brill/Papers/jspifinal.pdf


Specify a secondary axis

Description

This function is used in conjunction with a position scale to create asecondary axis, positioned opposite of the primary axis. All secondaryaxes must be based on a one-to-one transformation of the primary axes.

Usage

sec_axis(  transform = NULL,  name = waiver(),  breaks = waiver(),  labels = waiver(),  guide = waiver(),  trans = deprecated())dup_axis(  transform = identity,  name = derive(),  breaks = derive(),  labels = derive(),  guide = derive(),  trans = deprecated())derive()

Arguments

transform

A formula or function of a strictly monotonic transformation

name

The name of the secondary axis

breaks

One of:

  • NULL for no breaks

  • waiver() for the default breaks computed by the transformation object

  • A numeric vector of positions

  • A function that takes the limits as input and returns breaks as output

labels

One of:

  • NULL for no labels

  • waiver() for the default labels computed by the transformation object

  • A character vector giving labels (must be same length asbreaks)

  • A function that takes the breaks as input and returns labels as output

guide

A position guide that will be used to renderthe axis on the plot. Usually this isguide_axis().

trans

[Deprecated]

Details

sec_axis() is used to create the specifications for a secondary axis.Except for thetrans argument any of the arguments can be set toderive() which would result in the secondary axis inheriting thesettings from the primary axis.

dup_axis() is provide as a shorthand for creating a secondary axis thatis a duplication of the primary axis, effectively mirroring the primary axis.

As of v3.1, date and datetime scales have limited secondary axis capabilities.Unlike other continuous scales, secondary axis transformations for date and datetime scalesmust respect their primary POSIX data structure.This means they may only be transformed via addition or subtraction, e.g.~ . + hms::hms(days = 8), or~ . - 8*60*60. Nonlinear transformations will return an error.To produce a time-since-event secondary axis in this context, usersmay consider adapting secondary axis labels.

Examples

p <- ggplot(mtcars, aes(cyl, mpg)) +  geom_point()# Create a simple secondary axisp + scale_y_continuous(sec.axis = sec_axis(~ . + 10))# Inherit the name from the primary axisp + scale_y_continuous("Miles/gallon", sec.axis = sec_axis(~ . + 10, name = derive()))# Duplicate the primary axisp + scale_y_continuous(sec.axis = dup_axis())# You can pass in a formula as a shorthandp + scale_y_continuous(sec.axis = ~ .^2)# Secondary axes work for date and datetime scales too:df <- data.frame(  dx = seq(    as.POSIXct("2012-02-29 12:00:00", tz = "UTC"),    length.out = 10,    by = "4 hour"  ),  price = seq(20, 200000, length.out = 10) )# This may useful for labelling different time scales in the same plotggplot(df, aes(x = dx, y = price)) +  geom_line() +  scale_x_datetime(    "Date",    date_labels = "%b %d",    date_breaks = "6 hour",    sec.axis = dup_axis(      name = "Time of Day",      labels = scales::label_time("%I %p")    )  )# or to transform axes for different timezonesggplot(df, aes(x = dx, y = price)) +  geom_line() +  scale_x_datetime("    GMT",    date_labels = "%b %d %I %p",    sec.axis = sec_axis(      ~ . + 8 * 3600,      name = "GMT+8",      labels = scales::label_time("%b %d %I %p")    )  )

Set the last plot to be fetched by lastplot()

Description

Set the last plot to be fetched by lastplot()

Usage

set_last_plot(value)

See Also

last_plot()


Transform spatial position data

Description

Helper function that can transform spatial position data (pairs of x, yvalues) among coordinate systems. This is implemented as a thin wrapperaroundsf::sf_project().

Usage

sf_transform_xy(data, target_crs, source_crs, authority_compliant = FALSE)

Arguments

data

Data frame or list containing numerical columnsx andy.

target_crs,source_crs

Target and source coordinate reference systems.IfNULL orNA, the data is not transformed.

authority_compliant

logical;TRUE means handle axis order authoritycompliant (e.g. EPSG:4326 implyingx = lat,y = lon),FALSE means usevisualisation order (i.e. alwaysx = lon,y = lat). Default isFALSE.

Value

A copy of the input data withx andy replaced by transformed values.

Examples

if (requireNamespace("sf", quietly = TRUE)) {# location of cities in NC by long (x) and lat (y)data <- data.frame(  city = c("Charlotte", "Raleigh", "Greensboro"),  x =  c(-80.843, -78.639, -79.792),  y = c(35.227, 35.772, 36.073))# transform to projected coordinatesdata_proj <- sf_transform_xy(data, 3347, 4326)data_proj# transform backsf_transform_xy(data_proj, 4326, 3347)}

Used in examples to illustrate when errors should occur.

Description

Used in examples to illustrate when errors should occur.

Usage

should_stop(expr)

Arguments

expr

code to evaluate.

Examples

should_stop(stop("Hi!"))should_stop(should_stop("Hi!"))

Standardise aesthetic names

Description

This function standardises aesthetic names by convertingcolor tocolour(also in substrings, e.g.point_color topoint_colour) and translating old styleR names to ggplot names (eg.pch toshape,cex tosize).

Usage

standardise_aes_names(x)

Arguments

x

Character vector of aesthetics names, such asc("colour", "size", "shape").

Value

Character vector of standardised names.


Connect observations

Description

Connect successive points with lines of different shapes.

Usage

stat_connect(  mapping = NULL,  data = NULL,  geom = "path",  position = "identity",  ...,  connection = "hv",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

connection

A specification of how two points are connected. Can be oneof the folloing:

  • A string giving a named connection. These options are:

    • "hv" to first jump horizontally, then vertically.

    • "vh" to first jump vertically, then horizontally.

    • "mid" to step half-way between adjacent x-values.

    • "linear" to use a straight segment.

  • A numeric matrix with two columns giving x and y coordinates respectively.The coordinates should describe points on a path that connect point Aat location (0, 0) and point B at location (1, 1). At least one of thesetwo points is expected to be included in the coordinates.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Aesthetics

stat_connect() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

xorxminorxmax
yoryminorymax
group → inferred

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

ggplot(head(economics, 20), aes(date, unemploy)) +  stat_connect(connection = "hv")# Setup custom connectionsx <- seq(0, 1, length.out = 20)[-1]smooth <- cbind(x, scales::rescale(1 / (1 + exp(-(x * 10 - 5)))))zigzag <- cbind(c(0.4, 0.6, 1), c(0.75, 0.25, 1))ggplot(head(economics, 10), aes(date, unemploy)) +  geom_point() +  stat_connect(aes(colour = "zigzag"), connection = zigzag) +  stat_connect(aes(colour = "smooth"), connection = smooth)

Compute empirical cumulative distribution

Description

The empirical cumulative distribution function (ECDF) provides an alternativevisualisation of distribution. Compared to other visualisations that rely ondensity (likegeom_histogram()), the ECDF doesn't require anytuning parameters and handles both continuous and categorical variables.The downside is that it requires more training to accurately interpret,and the underlying visual tasks are somewhat more challenging.

Usage

stat_ecdf(  mapping = NULL,  data = NULL,  geom = "step",  position = "identity",  ...,  n = NULL,  pad = TRUE,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

n

if NULL, do not interpolate. If not NULL, this is the numberof points to interpolate with.

pad

IfTRUE, pad the ecdf with additional points (-Inf, 0)and (Inf, 1)

na.rm

IfFALSE (the default), removes missing values witha warning. IfTRUE silently removes missing values.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Details

The statistic relies on the aesthetics assignment to guess which variable touse as the input and which to use as the output. Either x or y must be providedand one of them must be unused. The ECDF will be calculated on the given aestheticand will be output on the unused one.

If theweight aesthetic is provided, a weighted ECDF will be computed. Inthis case, the ECDF is incremented byweight / sum(weight) instead of1 / length(x) for each observation.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Dropped variables

weight

After calculation, weights of individual observations (ifsupplied), are no longer available.

Aesthetics

stat_ecdf() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

xory
group → inferred
weightNULL

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

set.seed(1)df <- data.frame(  x = c(rnorm(100, 0, 3), rnorm(100, 0, 10)),  g = gl(2, 100))ggplot(df, aes(x)) +  stat_ecdf(geom = "step")# Don't go to positive/negative infinityggplot(df, aes(x)) +  stat_ecdf(geom = "step", pad = FALSE)# Multiple ECDFsggplot(df, aes(x, colour = g)) +  stat_ecdf()# Using weighted eCDFweighted <- data.frame(x = 1:10, weights = c(1:5, 5:1))plain <- data.frame(x = rep(weighted$x, weighted$weights))ggplot(plain, aes(x)) +  stat_ecdf(linewidth = 1) +  stat_ecdf(    aes(weight = weights),    data = weighted, colour = "green"  )

Compute normal data ellipses

Description

The method for calculating the ellipses has been modified fromcar::dataEllipse (Fox and Weisberg 2011, Friendly and Monette 2013)

Usage

stat_ellipse(  mapping = NULL,  data = NULL,  geom = "path",  position = "identity",  ...,  type = "t",  level = 0.95,  segments = 51,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

type

The type of ellipse.The default"t" assumes a multivariate t-distribution, and"norm" assumes a multivariate normal distribution."euclid" draws a circle with the radius equal tolevel,representing the euclidean distance from the center.This ellipse probably won't appear circular unlesscoord_fixed() is applied.

level

The level at which to draw an ellipse,or, iftype="euclid", the radius of the circle to be drawn.

segments

The number of segments to be used in drawing the ellipse.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Aesthetics

stat_ellipse() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
group → inferred
weight

Learn more about setting these aesthetics invignette("ggplot2-specs").

References

John Fox and Sanford Weisberg (2011). AnR Companion toApplied Regression, Second Edition. Thousand Oaks CA: Sage. URL:https://uk.sagepub.com/en-gb/eur/an-r-companion-to-applied-regression/book246125

Michael Friendly. Georges Monette. John Fox. "Elliptical Insights: Understanding Statistical Methods through Elliptical Geometry."Statist. Sci. 28 (1) 1 - 39, February 2013. URL:https://projecteuclid.org/journals/statistical-science/volume-28/issue-1/Elliptical-Insights-Understanding-Statistical-Methods-through-Elliptical-Geometry/10.1214/12-STS402.full

Examples

ggplot(faithful, aes(waiting, eruptions)) +  geom_point() +  stat_ellipse()ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) +  geom_point() +  stat_ellipse()ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) +  geom_point() +  stat_ellipse(type = "norm", linetype = 2) +  stat_ellipse(type = "t")ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) +  geom_point() +  stat_ellipse(type = "norm", linetype = 2) +  stat_ellipse(type = "euclid", level = 3) +  coord_fixed()ggplot(faithful, aes(waiting, eruptions, fill = eruptions > 3)) +  stat_ellipse(geom = "polygon")

Leave data as is

Description

The identity statistic leaves the data unchanged.

Usage

stat_identity(  mapping = NULL,  data = NULL,  geom = "point",  position = "identity",  ...,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Examples

p <- ggplot(mtcars, aes(wt, mpg))p + stat_identity()

Manually compute transformations

Description

stat_manual() takes a function that computes a data transformation forevery group.

Usage

stat_manual(  mapping = NULL,  data = NULL,  geom = "point",  position = "identity",  ...,  fun = identity,  args = list(),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

fun

Function that takes a data frame as input and returns a dataframe or data frame-like list as output. The default (identity()) returnsthe data unchanged.

args

A list of arguments to pass to the function given infun.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Aesthetics

Input aesthetics are determined by thefun argument. Output aesthetics mustinclude those required bygeom. Any aesthetic that is constant within agroup will be preserved even if dropped byfun.

Aesthetics

stat_manual() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

group → inferred

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

# A standard scatterplotp <- ggplot(mtcars, aes(disp, mpg, colour = factor(cyl))) +  geom_point()# The default just displays points as-isp + stat_manual()# Using a custom functionmake_hull <- function(data) {  hull <- chull(x = data$x, y = data$y)  data.frame(x = data$x[hull], y = data$y[hull])}p + stat_manual(  geom = "polygon",  fun  = make_hull,  fill = NA)# Using the `with` function with quotingp + stat_manual(  fun  = with,  args = list(expr = quote({    hull <- chull(x, y)    list(x = x[hull], y = y[hull])  })),  geom = "polygon", fill = NA)# Using the `transform` function with quotingp + stat_manual(  geom = "segment",  fun  = transform,  args = list(    xend = quote(mean(x)),    yend = quote(mean(y))  ))# Using dplyr verbs with `vars()`if (requireNamespace("dplyr", quietly = TRUE)) {  # Get centroids with `summarise()`  p + stat_manual(    size = 10, shape = 21,    fun  = dplyr::summarise,    args = vars(x = mean(x), y = mean(y))  )  # Connect to centroid with `mutate`  p + stat_manual(    geom = "segment",    fun  = dplyr::mutate,    args = vars(xend = mean(x), yend = mean(y))  )  # Computing hull with `reframe()`  p + stat_manual(    geom = "polygon", fill = NA,    fun  = dplyr::reframe,    args = vars(hull = chull(x, y), x = x[hull], y = y[hull])  )}

Extract coordinates from 'sf' objects

Description

stat_sf_coordinates() extracts the coordinates from 'sf' objects andsummarises them to one pair of coordinates (x and y) per geometry. This isconvenient when you draw an sf object as geoms like text and labels (sogeom_sf_text() andgeom_sf_label() relies on this).

Usage

stat_sf_coordinates(  mapping = aes(),  data = NULL,  geom = "point",  position = "identity",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE,  fun.geometry = NULL,  ...)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

fun.geometry

A function that takes asfc object and returns asfc_POINT with thesame length as the input. IfNULL,function(x) sf::st_point_on_surface(sf::st_zm(x))will be used. Note that the function may warn about the incorrectness ofthe result if the data is not projected, but you can ignore this exceptwhen you really care about the exact locations.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

Details

coordinates of ansf object can be retrieved bysf::st_coordinates().But, we cannot simply usesf::st_coordinates() because, whereas text andlabels require exactly one coordinate per geometry, it returns multiple onesfor a polygon or a line. Thus, these two steps are needed:

  1. Choose one point per geometry by some function likesf::st_centroid()orsf::st_point_on_surface().

  2. Retrieve coordinates from the points bysf::st_coordinates().

For the first step, you can use an arbitrary function viafun.geometry.By default,function(x) sf::st_point_on_surface(sf::st_zm(x)) is used;sf::st_point_on_surface() seems more appropriate thansf::st_centroid()since labels and text usually are intended to be put within the polygon orthe line.sf::st_zm() is needed to drop Z and M dimension beforehand,otherwisesf::st_point_on_surface() may fail when the geometries have Mdimension.

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Examples

if (requireNamespace("sf", quietly = TRUE)) {nc <- sf::st_read(system.file("shape/nc.shp", package="sf"))ggplot(nc) +  stat_sf_coordinates()ggplot(nc) +  geom_errorbarh(    aes(geometry = geometry,        xmin = after_stat(x) - 0.1,        xmax = after_stat(x) + 0.1,        y = after_stat(y),        height = 0.04),    stat = "sf_coordinates"  )}

Bin and summarise in 2d (rectangle & hexagons)

Description

stat_summary_2d() is a 2d variation ofstat_summary().stat_summary_hex() is a hexagonal variation ofstat_summary_2d(). The data are divided into bins definedbyx andy, and then the values ofz in each cell isare summarised withfun.

Usage

stat_summary_2d(  mapping = NULL,  data = NULL,  geom = "tile",  position = "identity",  ...,  binwidth = NULL,  bins = 30,  breaks = NULL,  drop = TRUE,  fun = "mean",  fun.args = list(),  boundary = 0,  closed = NULL,  center = NULL,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)stat_summary_hex(  mapping = NULL,  data = NULL,  geom = "hex",  position = "identity",  ...,  binwidth = NULL,  bins = 30,  drop = TRUE,  fun = "mean",  fun.args = list(),  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

binwidth

The width of the bins. Can be specified as a numeric valueor as a function that takes x after scale transformation as input andreturns a single numeric value. When specifying a function along with agrouping structure, the function will be called once per group.The default is to use the number of bins inbins,covering the range of the data. You should always overridethis value, exploring multiple widths to find the best to illustrate thestories in your data.

The bin width of a date variable is the number of days in each time; thebin width of a time variable is the number of seconds.

bins

Number of bins. Overridden bybinwidth. Defaults to 30.

breaks

Alternatively, you can supply a numeric vector givingthe bin boundaries. Overridesbinwidth,bins,center,andboundary. Can also be a function that takes group-wise values as input and returns bin boundaries.

drop

drop if the output offun isNA.

fun

function for summary.

fun.args

A list of extra arguments to pass tofun

closed

One of"right" or"left" indicating whether rightor left edges of bins are included in the bin.

center,boundary

bin position specifiers. Only one,center orboundary, may be specified for a single plot.center specifies thecenter of one of the bins.boundary specifies the boundary between twobins. Note that if either is above or below the range of the data, thingswill be shifted by the appropriate integer multiple ofbinwidth.For example, to center on integers usebinwidth = 1 andcenter = 0, evenif0 is outside the range of the data. Alternatively, this same alignmentcan be specified withbinwidth = 1 andboundary = 0.5, even if0.5 isoutside the range of the data.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Aesthetics

Computed variables

These are calculated by the 'stat' part of layers and can be accessed withdelayed evaluation.

Dropped variables

z

After binning, the z values of individual data points are no longer available.

Controlling binning parameters for the x and y directions

The argumentsbins,binwidth,breaks,center, andboundary canbe set separately for the x and y directions. When given as a scalar, onevalue applies to both directions. When given as a vector of length two,the first is applied to the x direction and the second to the y direction.Alternatively, these can be a named list containingx andy elements,for examplelist(x = 10, y = 20).

See Also

stat_summary_hex() for hexagonal summarization.stat_bin_2d() for the binning options.

Examples

d <- ggplot(diamonds, aes(carat, depth, z = price))d + stat_summary_2d()# Specifying functiond + stat_summary_2d(fun = \(x) sum(x^2))d + stat_summary_2d(fun = ~ sum(.x^2))d + stat_summary_2d(fun = var)d + stat_summary_2d(fun = "quantile", fun.args = list(probs = 0.1))if (requireNamespace("hexbin")) {d + stat_summary_hex()d + stat_summary_hex(fun = ~ sum(.x^2))}

Summarise y values at unique/binned x

Description

stat_summary() operates on uniquex ory;stat_summary_bin()operates on binnedx ory. They are more flexible versions ofstat_bin(): instead of just counting, they can compute anyaggregate.

Usage

stat_summary_bin(  mapping = NULL,  data = NULL,  geom = "pointrange",  position = "identity",  ...,  fun.data = NULL,  fun = NULL,  fun.max = NULL,  fun.min = NULL,  fun.args = list(),  bins = 30,  binwidth = NULL,  breaks = NULL,  na.rm = FALSE,  orientation = NA,  show.legend = NA,  inherit.aes = TRUE,  fun.y = deprecated(),  fun.ymin = deprecated(),  fun.ymax = deprecated())stat_summary(  mapping = NULL,  data = NULL,  geom = "pointrange",  position = "identity",  ...,  fun.data = NULL,  fun = NULL,  fun.max = NULL,  fun.min = NULL,  fun.args = list(),  na.rm = FALSE,  orientation = NA,  show.legend = NA,  inherit.aes = TRUE,  fun.y = deprecated(),  fun.ymin = deprecated(),  fun.ymax = deprecated())

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

fun.data

A function that is given the complete data and shouldreturn a data frame with variablesymin,y, andymax.

fun.min,fun,fun.max

Alternatively, supply three individualfunctions that are each passed a vector of values and should return asingle number.

fun.args

Optional additional arguments passed on to the functions.

bins

Number of bins. Overridden bybinwidth. Defaults to 30.

binwidth

The width of the bins. Can be specified as a numeric valueor as a function that takes x after scale transformation as input andreturns a single numeric value. When specifying a function along with agrouping structure, the function will be called once per group.The default is to use the number of bins inbins,covering the range of the data. You should always overridethis value, exploring multiple widths to find the best to illustrate thestories in your data.

The bin width of a date variable is the number of days in each time; thebin width of a time variable is the number of seconds.

breaks

Alternatively, you can supply a numeric vector giving the binboundaries. Overridesbinwidth andbins.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by settingorientationto either"x" or"y". See theOrientation section for more detail.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

fun.ymin,fun.y,fun.ymax

[Deprecated] Use theversions specified above instead.

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using theorientation parameter, which can be either"x" or"y". The value gives the axis that the geom should run along,"x" being the default orientation you would expect for the geom.

Summary functions

You can either supply summary functions individually (fun,fun.max,fun.min), or as a single function (fun.data):

fun.data

Complete summary function. Should take numeric vector asinput and return data frame as output

fun.min

min summary function (should take numeric vector andreturn single number)

fun

main summary function (should take numeric vector and returnsingle number)

fun.max

max summary function (should take numeric vector andreturn single number)

A simple vector function is easiest to work with as you can return a singlenumber, but is somewhat less flexible. If your summary function computesmultiple values at once (e.g. min and max), usefun.data.

fun.data will receive data as if it was oriented along the x-axis andshould return a data.frame that corresponds to that orientation. The layerwill take care of flipping the input and output if it is oriented along they-axis.

If no aggregation functions are supplied, will default tomean_se().

Aesthetics

stat_summary() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

x
y
group → inferred

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

geom_errorbar(),geom_pointrange(),geom_linerange(),geom_crossbar() for geoms todisplay summarised data

Examples

d <- ggplot(mtcars, aes(cyl, mpg)) + geom_point()d + stat_summary(fun.data = "mean_cl_boot", colour = "red", linewidth = 2, size = 3)# Orientation follows the discrete axisggplot(mtcars, aes(mpg, factor(cyl))) +  geom_point() +  stat_summary(fun.data = "mean_cl_boot", colour = "red", linewidth = 2, size = 3)# You can supply individual functions to summarise the value at# each x:d + stat_summary(fun = "median", colour = "red", size = 2, geom = "point")d + stat_summary(fun = "mean", colour = "red", size = 2, geom = "point")d + aes(colour = factor(vs)) + stat_summary(fun = mean, geom="line")d + stat_summary(fun = mean, fun.min = min, fun.max = max, colour = "red")d <- ggplot(diamonds, aes(cut))d + geom_bar()d + stat_summary(aes(y = price), fun = "mean", geom = "bar")# Orientation of stat_summary_bin is ambiguous and must be specified directlyggplot(diamonds, aes(carat, price)) +  stat_summary_bin(fun = "mean", geom = "bar", orientation = 'y')# Don't use ylim to zoom into a summary plot - this throws the# data awayp <- ggplot(mtcars, aes(cyl, mpg)) +  stat_summary(fun = "mean", geom = "point")pp + ylim(15, 30)# Instead use coord_cartesianp + coord_cartesian(ylim = c(15, 30))# A set of useful summary functions is provided from the Hmisc package:stat_sum_df <- function(fun, geom="crossbar", ...) {  stat_summary(fun.data = fun, colour = "red", geom = geom, width = 0.2, ...)}d <- ggplot(mtcars, aes(cyl, mpg)) + geom_point()# The crossbar geom needs grouping to be specified when used with# a continuous x axis.d + stat_sum_df("mean_cl_boot", mapping = aes(group = cyl))d + stat_sum_df("mean_sdl", mapping = aes(group = cyl))d + stat_sum_df("mean_sdl", fun.args = list(mult = 1), mapping = aes(group = cyl))d + stat_sum_df("median_hilow", mapping = aes(group = cyl))# An example with highly skewed distributions:if (require("ggplot2movies")) {set.seed(596)mov <- movies[sample(nrow(movies), 1000), ] m2 <-   ggplot(mov, aes(x = factor(round(rating)), y = votes)) +   geom_point() m2 <-   m2 +   stat_summary(     fun.data = "mean_cl_boot",     geom = "crossbar",     colour = "red", width = 0.3   ) +   xlab("rating")m2# Notice how the overplotting skews off visual perception of the mean# supplementing the raw data with summary statistics is _very_ important# Next, we'll look at votes on a log scale.# Transforming the scale means the data are transformed# first, after which statistics are computed:m2 + scale_y_log10()# Transforming the coordinate system occurs after the# statistic has been computed. This means we're calculating the summary on the raw data# and stretching the geoms onto the log scale.  Compare the widths of the# standard errors.m2 + coord_transform(y="log10")}

Remove duplicates

Description

Remove duplicates

Usage

stat_unique(  mapping = NULL,  data = NULL,  geom = "point",  position = "identity",  ...,  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data for this layer.When using a⁠stat_*()⁠ function to construct a layer, thegeom argumentcan be used to override the default coupling between stats and geoms. Thegeom argument accepts the following:

  • AGeom ggproto subclass, for exampleGeomPoint.

  • A string naming the geom. To give the geom as a string, strip thefunction name of thegeom_ prefix. For example, to usegeom_point(),give the geom as"point".

  • For more information and other ways to specify the geom, see thelayer geom documentation.

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. Theposition argument accepts the following:

  • The result of calling a position function, such asposition_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of theposition_ prefix. For example,to useposition_jitter(), give the position as"jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on tolayer()'sparams argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to theposition argument, or aesthetics that are requiredcannot be passed through.... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example,colour = "red"orlinewidth = 3. The geom's documentation has anAestheticssection that lists the available options. The 'required' aestheticscannot be passed on to theparams. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga⁠stat_*()⁠ function, the... argument can be used to pass onparameters to thegeom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a⁠geom_*()⁠ function, the... argument can be used to pass on parametersto thestat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • Thekey_glyph argument oflayer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

na.rm

IfFALSE, the default, missing values are removed witha warning. IfTRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay. To include legend keys for all levels, evenwhen no data exists, useTRUE. IfNA, all levels are shown in legend,but unobserved levels are omitted.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.annotation_borders().

Aesthetics

stat_unique() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:

group → inferred

Learn more about setting these aesthetics invignette("ggplot2-specs").

Examples

ggplot(mtcars, aes(vs, am)) +  geom_point(alpha = 0.1)ggplot(mtcars, aes(vs, am)) +  geom_point(alpha = 0.1, stat = "unique")

Shortcuts for theme settings

Description

This collection of functions serves as a shortcut fortheme() withshorter argument names. Besides the shorter arguments, it also helps inkeeping theme declarations more organised.

Usage

theme_sub_axis(..., title, text, ticks, ticks.length, line, minor.ticks.length)theme_sub_axis_x(  ...,  title,  text,  ticks,  ticks.length,  line,  minor.ticks.length)theme_sub_axis_y(  ...,  title,  text,  ticks,  ticks.length,  line,  minor.ticks.length)theme_sub_axis_bottom(  ...,  title,  text,  ticks,  ticks.length,  line,  minor.ticks,  minor.ticks.length)theme_sub_axis_top(  ...,  title,  text,  ticks,  ticks.length,  line,  minor.ticks,  minor.ticks.length)theme_sub_axis_left(  ...,  title,  text,  ticks,  ticks.length,  line,  minor.ticks,  minor.ticks.length)theme_sub_axis_right(  ...,  title,  text,  ticks,  ticks.length,  line,  minor.ticks,  minor.ticks.length)theme_sub_legend(  ...,  text,  text.position,  title,  title.position,  background,  frame,  ticks,  ticks.length,  axis.line,  spacing,  spacing.x,  spacing.y,  margin,  key,  key.size,  key.height,  key.width,  key.spacing,  key.spacing.x,  key.spacing.y,  key.justification,  byrow,  position,  direction,  location,  position.inside,  justification,  justification.top,  justification.bottom,  justification.left,  justification.right,  justification.inside,  box,  box.just,  box.margin,  box.background,  box.spacing)theme_sub_panel(  ...,  background,  border,  widths,  heights,  spacing,  spacing.x,  spacing.y,  grid,  grid.major,  grid.minor,  grid.major.x,  grid.major.y,  grid.minor.x,  grid.minor.y,  ontop)theme_sub_plot(  ...,  background,  title,  title.position,  subtitle,  caption,  caption.position,  tag,  tag.position,  tag.location,  margin)theme_sub_strip(  ...,  background,  background.x,  background.y,  clip,  placement,  text,  text.x,  text.x.bottom,  text.x.top,  text.y,  text.y.left,  text.y.right,  switch.pad.grid,  switch.pad.wrap)

Arguments

...

Not in use, expected to be empty.

axis.line,background,background.x,background.y,border,box,box.background,box.just,box.margin,box.spacing,byrow,caption,caption.position,clip,direction,frame,grid,grid.major,grid.major.x,grid.major.y,grid.minor,grid.minor.x,grid.minor.y,heights,justification,justification.bottom,justification.inside,justification.left,justification.right,justification.top,key,key.height,key.justification,key.size,key.spacing,key.spacing.x,key.spacing.y,key.width,line,location,margin,minor.ticks,minor.ticks.length,ontop,placement,position,position.inside,spacing,spacing.x,spacing.y,subtitle,switch.pad.grid,switch.pad.wrap,tag,tag.location,tag.position,text,text.position,text.x,text.x.bottom,text.x.top,text.y,text.y.left,text.y.right,ticks,ticks.length,title,title.position,widths

Arguments that are renamed and passed on totheme().

Value

Atheme-class object that can be added to a plot.

Functions

Examples

# A standard plotp <- ggplot(mtcars, aes(disp, mpg, colour = drat)) +  geom_point()red_text <- element_text(colour = "red")red_line <- element_line(colour = "red")# The theme settings below:p + theme(  axis.title.x.bottom = red_text,  axis.text.x.bottom  = red_text,  axis.line.x.bottom  = red_line,  axis.ticks.x.bottom = red_line)# Are equivalent to these less verbose theme settingsp + theme_sub_axis_bottom(  title = red_text,  text  = red_text,  line  = red_line,  ticks = red_line)

Summarise built plot objects

Description

These functions provide summarised information about built ggplot objects.

Usage

summarise_layout(p)summarise_coord(p)summarise_layers(p)

Arguments

p

A ggplot_built object.

Details

There are three types of summary that can be obtained: A summary of the plot layout,a summary of the plot coord, and a summary of plot layers.

Layout summary

The functionsummarise_layout() returns a table that provides information aboutthe plot panel(s) in the built plot. The table has the following columns:

panel

A factor indicating the individual plot panels.

row

Row number in the grid of panels.

col

Column number in the grid of panels.

vars

A list of lists. For each panel, the respective listprovides the variables and their values that specify the panel.

xmin,xmax

The minimum and maximum values of the variable mapped tothe x aesthetic, in transformed coordinates.

ymin,ymax

The minimum and maximum values of the variable mapped tothe y aesthetic, in transformed coordinates.

xscale

The scale object applied to the x aesthetic.

yscale

The scale object applied to the y aesthetic.

Importantly, the values forxmin,xmax,ymin,ymax,xscale, andyscaleare determined by the variables that are mapped tox andy in theaes() call.So even if a coord changes how x and y are shown in the final plot (as is the caseforcoord_flip() orcoord_polar()), these changes have no effect on the resultsreturned bysummarise_plot().

Coord summary

The functionsummarise_coord() returns information about the log base forcoordinates that are log-transformed incoord_transform(), and it also indicateswhether the coord has flipped the x and y axes.

Layer summary

The functionsummarise_layers() returns a table with a single column,mapping, whichcontains information about aesthetic mapping for each layer.

Examples

p <-  ggplot(mpg, aes(displ, hwy)) +  geom_point() +  facet_wrap(~class)b <- ggplot_build(p)summarise_layout(b)summarise_coord(b)summarise_layers(b)

Modify components of a theme

Description

Themes are a powerful way to customize the non-data components of your plots:i.e. titles, labels, fonts, background, gridlines, and legends. Themes can beused to give plots a consistent customized look. Modify a single plot's themeusingtheme(); seetheme_update() if you want modify the active theme, toaffect all subsequent plots. Use the themes available incomplete themes if you would like to use a complete theme such astheme_bw(),theme_minimal(), and more. Theme elements are documentedtogether according to inheritance, read more about theme inheritance below.

Usage

theme(  ...,  line,  rect,  text,  title,  point,  polygon,  geom,  spacing,  margins,  aspect.ratio,  axis.title,  axis.title.x,  axis.title.x.top,  axis.title.x.bottom,  axis.title.y,  axis.title.y.left,  axis.title.y.right,  axis.text,  axis.text.x,  axis.text.x.top,  axis.text.x.bottom,  axis.text.y,  axis.text.y.left,  axis.text.y.right,  axis.text.theta,  axis.text.r,  axis.ticks,  axis.ticks.x,  axis.ticks.x.top,  axis.ticks.x.bottom,  axis.ticks.y,  axis.ticks.y.left,  axis.ticks.y.right,  axis.ticks.theta,  axis.ticks.r,  axis.minor.ticks.x.top,  axis.minor.ticks.x.bottom,  axis.minor.ticks.y.left,  axis.minor.ticks.y.right,  axis.minor.ticks.theta,  axis.minor.ticks.r,  axis.ticks.length,  axis.ticks.length.x,  axis.ticks.length.x.top,  axis.ticks.length.x.bottom,  axis.ticks.length.y,  axis.ticks.length.y.left,  axis.ticks.length.y.right,  axis.ticks.length.theta,  axis.ticks.length.r,  axis.minor.ticks.length,  axis.minor.ticks.length.x,  axis.minor.ticks.length.x.top,  axis.minor.ticks.length.x.bottom,  axis.minor.ticks.length.y,  axis.minor.ticks.length.y.left,  axis.minor.ticks.length.y.right,  axis.minor.ticks.length.theta,  axis.minor.ticks.length.r,  axis.line,  axis.line.x,  axis.line.x.top,  axis.line.x.bottom,  axis.line.y,  axis.line.y.left,  axis.line.y.right,  axis.line.theta,  axis.line.r,  legend.background,  legend.margin,  legend.spacing,  legend.spacing.x,  legend.spacing.y,  legend.key,  legend.key.size,  legend.key.height,  legend.key.width,  legend.key.spacing,  legend.key.spacing.x,  legend.key.spacing.y,  legend.key.justification,  legend.frame,  legend.ticks,  legend.ticks.length,  legend.axis.line,  legend.text,  legend.text.position,  legend.title,  legend.title.position,  legend.position,  legend.position.inside,  legend.direction,  legend.byrow,  legend.justification,  legend.justification.top,  legend.justification.bottom,  legend.justification.left,  legend.justification.right,  legend.justification.inside,  legend.location,  legend.box,  legend.box.just,  legend.box.margin,  legend.box.background,  legend.box.spacing,  panel.background,  panel.border,  panel.spacing,  panel.spacing.x,  panel.spacing.y,  panel.grid,  panel.grid.major,  panel.grid.minor,  panel.grid.major.x,  panel.grid.major.y,  panel.grid.minor.x,  panel.grid.minor.y,  panel.ontop,  panel.widths,  panel.heights,  plot.background,  plot.title,  plot.title.position,  plot.subtitle,  plot.caption,  plot.caption.position,  plot.tag,  plot.tag.position,  plot.tag.location,  plot.margin,  strip.background,  strip.background.x,  strip.background.y,  strip.clip,  strip.placement,  strip.text,  strip.text.x,  strip.text.x.bottom,  strip.text.x.top,  strip.text.y,  strip.text.y.left,  strip.text.y.right,  strip.switch.pad.grid,  strip.switch.pad.wrap,  complete = FALSE,  validate = TRUE)

Arguments

...

additional element specifications not part of base ggplot2. In general,these should also be defined in the⁠element tree⁠ argument.Splicing a list is also supported.

line

all line elements (element_line())

rect

all rectangular elements (element_rect())

text

all text elements (element_text())

title

all title elements: plot, axes, legends (element_text();inherits fromtext)

point

all point elements (element_point())

polygon

all polygon elements (element_polygon())

geom

defaults for geoms (element_geom())

spacing

all spacings (unit())

margins

all margins (margin())

aspect.ratio

aspect ratio of the panel

axis.title,axis.title.x,axis.title.y,axis.title.x.top,axis.title.x.bottom,axis.title.y.left,axis.title.y.right

labels of axes (element_text()). Specify all axes' labels (axis.title),labels by plane (usingaxis.title.x oraxis.title.y), or individuallyfor each axis (usingaxis.title.x.bottom,axis.title.x.top,axis.title.y.left,axis.title.y.right).⁠axis.title.*.*⁠ inherits from⁠axis.title.*⁠ which inherits fromaxis.title, which in turn inheritsfromtext

axis.text,axis.text.x,axis.text.y,axis.text.x.top,axis.text.x.bottom,axis.text.y.left,axis.text.y.right,axis.text.theta,axis.text.r

tick labels along axes (element_text()). Specify all axis tick labels (axis.text),tick labels by plane (usingaxis.text.x oraxis.text.y), or individuallyfor each axis (usingaxis.text.x.bottom,axis.text.x.top,axis.text.y.left,axis.text.y.right).⁠axis.text.*.*⁠ inherits from⁠axis.text.*⁠ which inherits fromaxis.text, which in turn inheritsfromtext

axis.ticks,axis.ticks.x,axis.ticks.x.top,axis.ticks.x.bottom,axis.ticks.y,axis.ticks.y.left,axis.ticks.y.right,axis.ticks.theta,axis.ticks.r

tick marks along axes (element_line()). Specify all tick marks (axis.ticks),ticks by plane (usingaxis.ticks.x oraxis.ticks.y), or individuallyfor each axis (usingaxis.ticks.x.bottom,axis.ticks.x.top,axis.ticks.y.left,axis.ticks.y.right).⁠axis.ticks.*.*⁠ inherits from⁠axis.ticks.*⁠ which inherits fromaxis.ticks, which in turn inheritsfromline

axis.minor.ticks.x.top,axis.minor.ticks.x.bottom,axis.minor.ticks.y.left,axis.minor.ticks.y.right,axis.minor.ticks.theta,axis.minor.ticks.r

minor tick marks along axes (element_line()).⁠axis.minor.ticks.*.*⁠inherit from the corresponding major ticks⁠axis.ticks.*.*⁠.

axis.ticks.length,axis.ticks.length.x,axis.ticks.length.x.top,axis.ticks.length.x.bottom,axis.ticks.length.y,axis.ticks.length.y.left,axis.ticks.length.y.right,axis.ticks.length.theta,axis.ticks.length.r

length of tick marks (unit).axis.ticks.length inherits fromspacing.

axis.minor.ticks.length,axis.minor.ticks.length.x,axis.minor.ticks.length.x.top,axis.minor.ticks.length.x.bottom,axis.minor.ticks.length.y,axis.minor.ticks.length.y.left,axis.minor.ticks.length.y.right,axis.minor.ticks.length.theta,axis.minor.ticks.length.r

length of minor tick marks (unit), or relative toaxis.ticks.length when provided withrel().

axis.line,axis.line.x,axis.line.x.top,axis.line.x.bottom,axis.line.y,axis.line.y.left,axis.line.y.right,axis.line.theta,axis.line.r

lines along axes (element_line()). Specify lines along all axes (axis.line),lines for each plane (usingaxis.line.x oraxis.line.y), or individuallyfor each axis (usingaxis.line.x.bottom,axis.line.x.top,axis.line.y.left,axis.line.y.right).⁠axis.line.*.*⁠ inherits from⁠axis.line.*⁠ which inherits fromaxis.line, which in turn inheritsfromline

legend.background

background of legend (element_rect(); inheritsfromrect)

legend.margin

the margin around each legend (margin()); inheritsfrommargins.

legend.spacing,legend.spacing.x,legend.spacing.y

the spacing between legends (unit).legend.spacing.x &legend.spacing.yinherit fromlegend.spacing or can be specified separately.legend.spacing inherits fromspacing.

legend.key

background underneath legend keys (element_rect();inherits fromrect)

legend.key.size,legend.key.height,legend.key.width

size of legend keys (unit); key background height & width inherit fromlegend.key.size or can be specified separately. In turnlegend.key.sizeinherits fromspacing.

legend.key.spacing,legend.key.spacing.x,legend.key.spacing.y

spacingbetween legend keys given as aunit. Spacing in the horizontal (x) andvertical (y) direction inherit fromlegend.key.spacing or can bespecified separately.legend.key.spacing inherits fromspacing.

legend.key.justification

Justification for positioning legend keyswhen more space is available than needed for display. The default,NULL,stretches keys into the available space. Can be a location like"center"or"top", or a two-element numeric vector.

legend.frame

frame drawn around the bar (element_rect()).

legend.ticks

tick marks shown along bars or axes (element_line())

legend.ticks.length

length of tick marks in legend(unit()); inherits fromlegend.key.size.

legend.axis.line

lines along axes in legends (element_line())

legend.text

legend item labels (element_text(); inherits fromtext)

legend.text.position

placement of legend text relative to legend keysor bars ("top", "right", "bottom" or "left"). The legend text placementmight be incompatible with the legend's direction for some guides.

legend.title

title of legend (element_text(); inherits fromtitle)

legend.title.position

placement of legend title relative to the mainlegend ("top", "right", "bottom" or "left").

legend.position

the default position of legends ("none", "left","right", "bottom", "top", "inside")

legend.position.inside

A numeric vector of length two setting theplacement of legends that have the"inside" position.

legend.direction

layout of items in legends ("horizontal" or"vertical")

legend.byrow

whether the legend-matrix is filled by columns(FALSE, the default) or by rows (TRUE).

legend.justification

anchor point for positioning legend inside plot("center" or two-element numeric vector) or the justification according tothe plot area when positioned outside the plot

legend.justification.top,legend.justification.bottom,legend.justification.left,legend.justification.right,legend.justification.inside

Same aslegend.justification but specified perlegend.position option.

legend.location

Relative placement of legends outside the plot as astring. Can be"panel" (default) to align legends to the panels or"plot" to align legends to the plot as a whole.

legend.box

arrangement of multiple legends ("horizontal" or"vertical")

legend.box.just

justification of each legend within the overallbounding box, when there are multiple legends ("top", "bottom", "left","right", "center" or "centre")

legend.box.margin

margins around the full legend area, as specifiedusingmargin(); inherits frommargins.

legend.box.background

background of legend area (element_rect();inherits fromrect)

legend.box.spacing

The spacing between the plotting area and thelegend box (unit); inherits fromspacing.

panel.background

background of plotting area, drawn underneath plot(element_rect(); inherits fromrect)

panel.border

border around plotting area, drawn on top of plot so thatit covers tick marks and grid lines. This should be used withfill = NA(element_rect(); inherits fromrect)

panel.spacing,panel.spacing.x,panel.spacing.y

spacing between facetpanels (unit).panel.spacing.x &panel.spacing.y inherit frompanel.spacingor can be specified separately.panel.spacing inherits fromspacing.

panel.grid,panel.grid.major,panel.grid.minor,panel.grid.major.x,panel.grid.major.y,panel.grid.minor.x,panel.grid.minor.y

grid lines (element_line()). Specify major grid lines,or minor grid lines separately (usingpanel.grid.major orpanel.grid.minor)or individually for each axis (usingpanel.grid.major.x,panel.grid.minor.x,panel.grid.major.y,panel.grid.minor.y). Y axis grid lines are horizontaland x axis grid lines are vertical.⁠panel.grid.*.*⁠ inherits from⁠panel.grid.*⁠ which inherits frompanel.grid, which in turn inheritsfromline

panel.ontop

option to place the panel (background, gridlines) overthe data layers (logical). Usually used with a transparent or blankpanel.background.

panel.widths,panel.heights

Sizes for panels (units). Can be asingle unit to set the total size for the panel area, or a unit vector toset the size of individual panels. Using this setting overrides theaspect ratio set by the theme, coord or facets. An exception is made whenthe plot has a single panel and exactly one of the widthor height isset, in which case an attempt is made to preserve the aspect ratio.

plot.background

background of the entire plot (element_rect();inherits fromrect)

plot.title

plot title (text appearance) (element_text(); inheritsfromtitle) left-aligned by default

plot.title.position,plot.caption.position

Alignment of the plot title/subtitleand caption. The setting forplot.title.position applies to boththe title and the subtitle. A value of "panel" (the default) means thattitles and/or caption are aligned to the plot panels. A value of "plot" meansthat titles and/or caption are aligned to the entire plot (minus any spacefor margins and plot tag).

plot.subtitle

plot subtitle (text appearance) (element_text();inherits fromtitle) left-aligned by default

plot.caption

caption below the plot (text appearance)(element_text(); inherits fromtitle) right-aligned by default

plot.tag

upper-left label to identify a plot (text appearance)(element_text(); inherits fromtitle) left-aligned by default

plot.tag.position

The position of the tag as a string ("topleft","top", "topright", "left", "right", "bottomleft", "bottom", "bottomright")or a coordinate. If a coordinate, can be a numeric vector of length 2 toset the x,y-coordinate relative to the whole plot. The coordinate optionis unavailable forplot.tag.location = "margin".

plot.tag.location

The placement of the tag as a string, one of"panel","plot" or"margin". Respectively, these will place the taginside the panel space, anywhere in the plot as a whole, or in the marginaround the panel space.

plot.margin

margin around entire plot (unit with the sizes ofthe top, right, bottom, and left margins); inherits frommargin.

strip.background,strip.background.x,strip.background.y

background of facet labels (element_rect();inherits fromrect). Horizontal facet background (strip.background.x)& vertical facet background (strip.background.y) inherit fromstrip.background or can be specified separately

strip.clip

should strip background edges and strip labels be clippedto the extend of the strip background? Options are"on" to clip,"off"to disable clipping or"inherit" (default) to take the clipping settingfrom the parent viewport.

strip.placement

placement of strip with respect to axes,either "inside" or "outside". Only important when axes and strips areon the same side of the plot.

strip.text,strip.text.x,strip.text.y,strip.text.x.top,strip.text.x.bottom,strip.text.y.left,strip.text.y.right

facet labels (element_text(); inherits fromtext). Horizontal facet labels (strip.text.x) & verticalfacet labels (strip.text.y) inherit fromstrip.text or can be specifiedseparately. Facet strips have dedicated position-dependent theme elements(strip.text.x.top,strip.text.x.bottom,strip.text.y.left,strip.text.y.right)that inherit fromstrip.text.x andstrip.text.y, respectively.As a consequence, some theme stylings need to be applied tothe position-dependent elements rather than to the parent elements

strip.switch.pad.grid,strip.switch.pad.wrap

space between strips andaxes when strips are switched (unit); inherits fromspacing.

complete

set this toTRUE if this is a complete theme, such asthe one returned bytheme_grey(). Complete themes behavedifferently when added to a ggplot object. Also, when settingcomplete = TRUE all elements will be set to inherit from blankelements.

validate

TRUE to runcheck_element(),FALSE to bypass checks.

Theme inheritance

Theme elements inherit properties from other theme elements hierarchically.For example,axis.title.x.bottom inherits fromaxis.title.x which inheritsfromaxis.title, which in turn inherits fromtext. All text elements inheritdirectly or indirectly fromtext; all lines inherit fromline, and all rectangular objects inherit fromrect.This means that you can modify the appearance of multiple elements bysetting a single high-level component.

Learn more about setting these aesthetics invignette("ggplot2-specs").

See Also

add_gg() and%+replace%,element_blank(),element_line(),element_rect(), andelement_text() fordetails of the specific theme elements.

Themodifying theme components andtheme elements sections of the online ggplot2 book.

Examples

p1 <- ggplot(mtcars, aes(wt, mpg)) +  geom_point() +  labs(title = "Fuel economy declines as weight increases")p1# Plot ---------------------------------------------------------------------p1 + theme(plot.title = element_text(size = rel(2)))p1 + theme(plot.background = element_rect(fill = "green"))# Panels --------------------------------------------------------------------p1 + theme(panel.background = element_rect(fill = "white", colour = "grey50"))p1 + theme(panel.border = element_rect(linetype = "dashed"))p1 + theme(panel.grid.major = element_line(colour = "black"))p1 + theme(  panel.grid.major.y = element_blank(),  panel.grid.minor.y = element_blank())# Put gridlines on top of datap1 + theme(  panel.background = element_rect(fill = NA),  panel.grid.major = element_line(colour = "grey50"),  panel.ontop = TRUE)# Axes ----------------------------------------------------------------------# Change styles of axes texts and linesp1 + theme(axis.line = element_line(linewidth = 3, colour = "grey80"))p1 + theme(axis.text = element_text(colour = "blue"))p1 + theme(axis.ticks = element_line(linewidth = 2))# Change the appearance of the y-axis titlep1 + theme(axis.title.y = element_text(size = rel(1.5), angle = 90))# Make ticks point outwards on y-axis and inwards on x-axisp1 + theme(  axis.ticks.length.y = unit(.25, "cm"),  axis.ticks.length.x = unit(-.25, "cm"),  axis.text.x = element_text(margin = margin(t = .3, unit = "cm")))# Legend --------------------------------------------------------------------p2 <- ggplot(mtcars, aes(wt, mpg)) +  geom_point(aes(colour = factor(cyl), shape = factor(vs))) +  labs(    x = "Weight (1000 lbs)",    y = "Fuel economy (mpg)",    colour = "Cylinders",    shape = "Transmission"   )p2# Positionp2 + theme(legend.position = "none")p2 + theme(legend.justification = "top")p2 + theme(legend.position = "bottom")# Or place legends inside the plot using relative coordinates between 0 and 1# legend.justification sets the corner that the position refers top2 + theme(  legend.position = "inside",  legend.position.inside = c(.95, .95),  legend.justification = c("right", "top"),  legend.box.just = "right",  legend.margin = margin_auto(6))# The legend.box properties work similarly for the space around# all the legendsp2 + theme(  legend.box.background = element_rect(),  legend.box.margin = margin_auto(6))# You can also control the display of the keys# and the justification related to the plot area can be setp2 + theme(legend.key = element_rect(fill = "white", colour = "black"))p2 + theme(legend.text = element_text(size = 8, colour = "red"))p2 + theme(legend.title = element_text(face = "bold"))# Strips --------------------------------------------------------------------p3 <- ggplot(mtcars, aes(wt, mpg)) +  geom_point() +  facet_wrap(~ cyl)p3p3 + theme(strip.background = element_rect(colour = "black", fill = "white"))p3 + theme(strip.text.x = element_text(colour = "white", face = "bold"))# More direct strip.text.x here for top# as in the facet_wrap the default strip.position is "top"p3 + theme(strip.text.x.top = element_text(colour = "white", face = "bold"))p3 + theme(panel.spacing = unit(1, "lines"))# Colours -------------------------------------------------------------------p4 <- ggplot(mtcars, aes(wt, mpg)) +  geom_point() +  annotate(label = "Text Annotation", x = 5, y = 30, geom = "text")# You can use the 'ink' setting to set colour defaults for all layersp4 + theme(geom = element_geom(ink = "dodgerblue"))# Alternate colours are derived from the 'accent' and 'paper' settingsp4 + geom_smooth(method = "lm", formula = y ~ x) +  theme(geom = element_geom(accent = "tomato", paper = "orchid"))# You can also set default palettes in the themep4 + aes(colour = drat) +  theme(palette.colour.continuous = c("white", "pink", "hotpink"))

Tidy eval helpers

Description

This page lists the tidy eval tools reexported in this package fromrlang. To learn about using tidy eval in scripts and packages at ahigh level, see thedplyr programming vignetteand theggplot2 in packages vignette.TheMetaprogramming section ofAdvanced R may also be useful for a deeper dive.


Convenience function to transform all position variables.

Description

Convenience function to transform all position variables.

Usage

transform_position(df, trans_x = NULL, trans_y = NULL, ...)

Arguments

trans_x,trans_y

Transformation functions for x and y aesthetics.(will transform x, xmin, xmax, xend etc)

...

Additional arguments passed totrans_x andtrans_y.


Translating shape strings

Description

translate_shape_string() is a helper function for translating point shapesgiven as a character vector into integers that are interpreted by thegrid system.

Usage

translate_shape_string(shape_string)

Arguments

shape_string

A character vector giving point shapes. Non-characterinput will be returned.

Value

An integer vector with translated shapes.

Examples

translate_shape_string(c("circle", "square", "triangle"))# Strings with 1 or less characters are interpreted as symbolstranslate_shape_string(c("a", "b", "?"))

Housing sales in TX

Description

Information about the housing market in Texas provided by the TAMUreal estate center,https://trerc.tamu.edu/.

Usage

txhousing

Format

A data frame with 8602 observations and 9 variables:

city

Name of multiple listing service (MLS) area

year,month,date

Date

sales

Number of sales

volume

Total value of sales

median

Median sale price

listings

Total active listings

inventory

"Months inventory": amount of time it would take to sellall current listings at current pace of sales.


Modify geom/stat aesthetic defaults for future plots

Description

Functions to update or reset the default aesthetics of geoms and stats.

Usage

update_geom_defaults(geom, new)update_stat_defaults(stat, new)reset_geom_defaults()reset_stat_defaults()

Arguments

new

One of the following:

  • A named list of aesthetics to serve as new defaults.

  • NULL to reset the defaults.

stat,geom

Name of geom/stat to modify (like"point" or"bin"), or a Geom/Stat object (likeGeomPoint orStatBin).

Note

Please note that geom defaults can be seten masse via thetheme(geom)argument. The guidelines for when to use which function are as follows:

Examples

# updating a geom's default aesthetic settings# example: change geom_point()'s default colorGeomPoint$default_aesupdate_geom_defaults("point", aes(color = "red"))GeomPoint$default_aesggplot(mtcars, aes(mpg, wt)) + geom_point()# reset single defaultupdate_geom_defaults("point", NULL)# reset all defaultsreset_geom_defaults()# updating a stat's default aesthetic settings# example: change stat_bin()'s default y-axis to the density scaleStatBin$default_aesupdate_stat_defaults("bin", aes(y = after_stat(density)))StatBin$default_aesggplot(data.frame(x = rnorm(1e3)), aes(x)) +  geom_histogram() +  geom_function(fun = dnorm, color = "red")# reset single defaultupdate_stat_defaults("bin", NULL)# reset all defaultsreset_stat_defaults()

Add custom objects to ggplot

Description

This generic allows you to add your own methods for adding custom objects toa ggplot with+.gg. Theggplot_add() function is vestigial andtheupdate_ggplot() function should be used instead.

Usage

update_ggplot(object, plot, ...)ggplot_add(object, plot, ...)

Arguments

object

An object to add to the plot

plot

The ggplot object to addobject to

Details

Custom methods forupdate_ggplot() are intended to update theplot variableusing information from a customobject. This can become convenient whenwriting extensions that don't build on the pre-existing grammar likelayers, facets, coords and themes. Theupdate_ggplot() function is neverintended to be used directly, but it is triggered when an object is addedto a plot via the+ operator. Please note that the fullplot object isexposed at this point, which comes with the responsibility of returningthe plot intact.

Value

A modified ggplot object

Examples

# making a new method for the generic# in this example, we enable adding text elementsS7::method(update_ggplot, list(element_text, class_ggplot)) <-  function(object, plot, ...) {    plot + theme(text = object)  }# we can now use `+` to add our object to a plotggplot(mpg, aes(displ, cty)) +  geom_point() +  element_text(colour = "red")# clean-up

Update axis/legend labels

Description

Update axis/legend labels

Usage

update_labels(p, labels)

Arguments

p

plot to modify

labels

named list of new labels

Examples

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()update_labels(p, list(x = "New x"))update_labels(p, list(x = expression(x / y ^ 2)))update_labels(p, list(x = "New x", y = "New Y"))update_labels(p, list(colour = "Fail silently"))

Quote faceting variables

Description

Just likeaes(),vars() is aquoting functionthat takes inputs to be evaluated in the context of a dataset.These inputs can be:

In both cases, the results (the vectors that the variablerepresents or the results of the expressions) are used to formfaceting groups.

Usage

vars(...)

Arguments

...

<data-masking> Variables orexpressions automatically quoted. These are evaluated in the context of thedata to form faceting groups. Can be named (the names are passed to alabeller).

See Also

aes(),facet_wrap(),facet_grid()

Examples

p <- ggplot(mtcars, aes(wt, disp)) + geom_point()p + facet_wrap(vars(vs, am))# vars() makes it easy to pass variables from wrapper functions:wrap_by <- function(...) {  facet_wrap(vars(...), labeller = label_both)}p + wrap_by(vs)p + wrap_by(vs, am)# You can also supply expressions to vars(). In this case it's often a# good idea to supply a name as well:p + wrap_by(drat = cut_number(drat, 3))# Let's create another function for cutting and wrapping a# variable. This time it will take a named argument instead of dots,# so we'll have to use the "enquote and unquote" pattern:wrap_cut <- function(var, n = 3) {  # Let's enquote the named argument `var` to make it auto-quoting:  var <- enquo(var)  # `as_label()` will create a nice default name:  nm <- as_label(var)  # Now let's unquote everything at the right place. Note that we also  # unquote `n` just in case the data frame has a column named  # `n`. The latter would have precedence over our local variable  # because the data is always masking the environment.  wrap_by(!!nm := cut_number(!!var, !!n))}# Thanks to tidy eval idioms we now have another useful wrapper:p + wrap_cut(drat)

A waiver object.

Description

A waiver is a "flag" object, similar toNULL, that indicates thecalling function should just use the default value. It is used in certainfunctions to distinguish between displaying nothing (NULL) anddisplaying a default value calculated elsewhere (waiver()).is_waiver() reports whether an object is a waiver.

Usage

waiver()is_waiver(x)

Arguments

x

An object to test


Arrange 1d structure into a grid

Description

Arrange 1d structure into a grid

Usage

wrap_dims(n, nrow = NULL, ncol = NULL)

Arguments

n

length of structure

nrow,ncol

desired dimensions for the grid

Value

the grid dimension as a vector with nrow and then ncol


The zero grob draws nothing and has zero size.

Description

The zero grob draws nothing and has zero size.

Usage

zeroGrob()

[8]ページ先頭

©2009-2025 Movatter.jp