This is a smaller patch release focussed on fixing regressions from4.0.0 and polishing the recent features.
geom_area() didn’t draw panelswith single groups whenstat = "align" (position_stack(vjust) wasignored when there are only single groups (#6692)NA handling ingeom_path()was ignoring panels (stat_bin(boundary) was ignored(#6682).geom_text() andgeom_label() acceptexpressions as thelabel aesthetic (draw_key_rect() stopped usingfill colours (scale_{x,y}_*() threw an errorwhen an expression object is set tolabels argument (name argument (arrow()s caused errors indrawing the legend glyphs (NULL-aesthetics contributed toplot labels too insistently. Now they contribute only as fallback labels(@teunbrand,#6616)coor_radial() when labelsare blank (stat ingeom_hline,geom_vline, andgeom_abline. (stat_boxplot() treatswidth as an optionalaesthetic (@Yunuuuu,#6575)theme(panel.widths, panel.heights) setting attemptsto preserve the plot’s aspect ratio when only one of the two settings isgiven, and the plot has a single panel (linetype = FALSE becomes 0/‘blank’ andlinetype = TRUE becomes 1/‘solid’ (stat_align() now get removed silently rather than verbosely(@teunbrand,#6667)geom_violin(quantiles) now has actualquantiles based on the data, rather than inferred quantiles based on thecomputed density. Thequantiles parameter that replacesdraw_quantiles now belongs tostat_ydensity()instead ofgeom_violin() (theme(geom) argument is used to track thesedefaults.element_geom() function can be used to populatethat argument.from_theme() function allows access to the themedefault fields from inside theaes() function.build_ggplot()(previouslyggplot_build()) rather than in the layer methodofupdate_ggplot() (previouslyggplot_add.Layer()). This may affect code that accessed theplot$labels property (boundary is now chosen tobetter adhere to thenbin argument. This may affect plotsthat use default binning (Deprecated functions and arguments prior to ggplot2 3.0.0 throwerrors instead of warnings.
Functions and arguments that were soft-deprecated up to ggplot23.4.0 now throw warnings.
annotation_borders() replaces the now-deprecatedborders() (
Turned off fallback forsize tolinewidth translation ingeom_bar()/geom_col() (#4848).
Thefatten argument has been deprecated ingeom_boxplot(),geom_crossbar() andgeom_pointrange() (
The following methods have been deprecated:fortify.lm(),fortify.glht(),fortify.confint.glht(),fortify.summary.glht()andfortify.cld(). It is recommend to usebroom::augment() andbroom::tidy() instead(@teunbrand,#3816).
geom_errorbarh() is deprecated in favour ofgeom_errorbar(orientation = "y") (
Special getter and setter functions have been renamed forconsistency, allowing for better tab-completion withget_*-andset_*-prefixes. The old names remain available forbackward compatibility (
| New name | Old name |
|---|---|
get_theme() | theme_get() |
set_theme() | theme_set() |
replace_theme() | theme_replace() |
update_theme() | theme_update() |
get_last_plot() | last_plot() |
get_layer_data() | layer_data() |
get_layer_grob() | layer_grob() |
get_panel_scales() | layer_scales() |
facet_wrap() has new options for thedir argument for additional control over panel directions.They absorb interactions with the now-deprecatedas.tableargument. Internallydir = "h" ordir = "v" isdeprecated (
coord_trans() was renamed tocoord_transform() (
theme() function offers new arguments:geom to set defaults for layer aesthetics (#2239).spacing/margins as root elements that areinherited by all other spacings and (non-text) margins (palette.{aes}.discrete andpalette.{aes}.continuous which determine the palettes usedwhen scales havepalette = NULL. This is the new defaultfor generic scales likescale_colour_discrete() orscale_fill_continuous(), see also the ‘Scales’ section(#4696).panel.widths andpanel.heights to controlthe (absolute) size of the panels (#5338,legend.key.justification to control the alignment oflegend keys (theme_*() functions have new arguments:ink/paper/accent to controlforeground, background and highlight colours respectively of the wholeplot (@teunbrand,#6063,@EvaMaeRey,#6438).header_family to easily set the font for headers andtitles (#5886)plot.subtitle,plot.caption andplot.tag now inherit from theroottext element instead of thetitleelement.theme_sub_axis(line, text, ticks, ticks.length, line) as asubstitute fortheme(axis.line, axis.text, axis.ticks, axis.ticks.length, axis.line).This should allow slightly terser and more organised theme declarations(@teunbrand,#5301).margin_part() function that comes pre-populatedwith NA-units, so you can change a single margin without worrying thatthe others look off.margin_auto() that recycles arguments in a CSS likefashion.fill of thepanel.border theme settingis ignored and forced to be transparent (#5782).theme_classic() has the following changes (ink-coloured) instead of darkgray."square".panel.grid hierarchylevel instead of thepanel.grid.major andpanel.grid.minor levels.theme(legend.spacing.{x/y}) setting now acceptsnull-units (paletteargument. The default,palette = NULL will retrievepalettes from the theme (see the Themes section). This replaces the oldoptions-basedtype system, with some limited backwardcompatibility (aesthetics parameter (xandy aesthetics. This lets uncommon aesthetics likexintercept expand scales as usual. (#3342, #4966,breaks is a function andn.breaks is set, then.breaks will be passedto thebreaks function. Previously,n.breaksonly applied to the default break calculation (palette argument, which can be used to customisespacings between levels (continuous.limits argument to control the displayrange (@teunbrand,#4174, #6259).minor_breaks argument. This only makes sense inposition scales, where it affects the placement of minor ticks and minorgridlines (#5434).sec.axis argument. Discrete scales don’t supporttransformations so it is recommended to usedup_axis() toset custom breaks or labels. Secondary discrete axes work with thecontinuous analogues of discrete breaks (breaks yields a named vector, the names will beused aslabels by default (date_breaks,date_minor_breaks anddate_labels arguments have been copied over toscale_{x/y}_time() (reverse argument incoord_cartesian(),coord_fixed(),coord_radial() andcoord_sf(). Incoord_radial(), this replacesthe olderdirection argument (#4021,coord_*(expand) can now take a logical vector tocontrol expansion at any side of the panel (top, right, bottom, left)(@teunbrand,#6020)coord_cartesian(ratio) argument that absorbs theaspect ratio functionality fromcoord_equal() andcoord_fixed(), which are now wrappers forcoord_cartesian().coord_sf(),coord_polar() andcoord_radial()), using‘AsIs’ variables escape transformation when bothx andy is an ‘AsIs’ variable (coord_sf(expand = TRUE) and graticule lines are straightbut do not meet the edge (coord_radial(clip = "on") clips to the panel area whenthe graphics device supports clipping paths (coord_radial(r.axis.inside) can now take a numericvalue to control placement of internally placed radius axes (coord_polar() andcoord_radial() now adds more detail, particularly fordata-points with a low radius near the center (position_nudge() gainsnudge_x andnudge_y aesthetics (#3026, #5445).position_dodge() gainsorder aesthetic(#3022, #3345)stat_connect() to connect points via steps or othershapes (@teunbrand,#6228)stat_manual() for arbitrary computations(@teunbrand,#3501)geom_boxplot() gains additional arguments to style thecolour, linetype and linewidths of the box, whiskers, median line andstaples (geom_violin() gains additional arguments to style thecolour, linetype and linewidths of the quantiles, which replace thenow-deprecateddraw_quantiles argument (#5912).geom_label() (linewidth aesthetic is now applied and replaces thelabel.size argument.linetype aesthetic is now applied.border.colour argument to set the colour ofborders.text.colour argument to set the colour oftext.layer(layout) argument to interact with facets(@teunbrand,#3062)geom_qq_line(geom = "abline") for betterclipping in the vertical direction. In addition,slope andintercept are new computed variables instat_qq_line() (stat_ecdf() now has an optionalweightaesthetic (stat_ellipse now has an optionalweight(@teunbrand,#5272)stat_density() has the new computed variable:wdensity, which is calculated as the density times the sumof weights (linetype = NA is now interpreted to mean ‘no line’instead of raising errors (position_dodge() andposition_jitterdodge() now have areverseargument (position_jitterdodge() now dodges bygroup(@teunbrand,#3656)geom_rect() can now derive the required cornerspositions fromx/width ory/height parameterisation (position_dodge(preserve = "single") now handlesmulti-row geoms better, such asgeom_violin() (geom_point() can be dodged vertically by usingposition_dodge(..., orientation = "y") (arrow.fill parameter is now applied to moreline-based functions:geom_path(),geom_line(),geom_step()geom_function(), line geometries ingeom_sf()andelement_line().geom_raster() now falls back to rendering asgeom_rect() when coordinates are not linear (#5503).geom_ribbon() can have varyingfill oralpha in linear coordinate systems (width, which are nowimplemented as aesthetics (boundary/center parametrisation rather thanorigin, following instat_bin()’s footsteps(@teunbrand).drop argument tostat_bin()(@teunbrand,#3449)stat_bin() now accepts functions for argumentbreaks (after_stat() andafter_scale() throwwarnings when the computed aesthetics are not of the correct length(#5901).geom_hline() andgeom_vline() now haveposition argument (geom_contour() should be able to recognise a rotatedgrid of points (guide_*() can now accept two inside legend themeelements:legend.position.inside andlegend.justification.inside, allowing inside legends to beplaced at different positions. Only inside legends with the sameposition and justification will be merged (guide_bins(),guide_colourbar() andguide_coloursteps() gain anangle argument tooverrule theme settings, similar toguide_axis(angle)(@teunbrand,#4594).labs(dictionary) to label based onvariable name rather than based on aesthetic (summary() method for ggplots is now more terseabout facets (facet_wrap() can havespace = "free_x"with 1-row layouts andspace = "free_y" with 1-columnlayouts (facet_grid(space = "free") can now be combined withcoord_fixed() (fortify(),get_alt_text(),labs() and several guides.(@teunbrand,#3196).ggsave() can write a multi-page pdf file when providedwith a list of plots (guide_custom(order) wasn’tworking (guide_custom() that would throw error withtheme_void() (guide_colourbar() now correctly hands offposition andavailable_aes parametersdownstream (guide_axis() no longer reserves space for blank ticks(@teunbrand, #4722,#6069).breaks = NULL caused theaxes to disappear instead of just rendering the axis line (guide_axis_logticks(negative.small) parameter when scalelimits have small maximum (guide_bins(reverse = TRUE) (date_breaks,date_minor_breaks ordate_labels are not strings (n.breaks setting in continuousscales (@teunbrand,#4483).draw_key_polygon() glyph now reflectsthelinewidth aesthetic which internally defaults to 0(#4852).draw_key_rect() replaces aNA fill by thecolour aesthetic (na.value was incorrectly mapped tonon-NA values (coord_flip() (coord_radial() now displays no axis instead of throwingan error when a scale has no breaks (coord_radial() displays minor gridlines now (coord_sf() can now usefunctions in thebreaks argument. In addition,n.breaks works as intended andbreaks = NULLremoves grid lines and axes (coord_sf() no longer errors when dealing with emptygraticules (position_fill() avoids stacking observations of zero(@teunbrand,#6338)position_jitterdodge() where differentjitters would be applied to different position aesthetics of the sameaxis (@teunbrand,#5818).position_dodge2()’s identification ofrange overlaps (geom_ribbon() now appropriately warns about, andremoves, missing values (geom_sf() now accepts shape names for point geometries(geom_step() now supports theorientationargument (geom_rug() prints a warning whenna.rm = FALSE, as per documentation (geom_curve() now appropriately removes missing datainstead of throwing errors (geom_curve()(@teunbrand,#5069).geom_abline() clips to the panel range in the verticaldirection too (se parameter in layers withgeom = "smooth" will beTRUE when the data hasymin andymax parameters andFALSE if these are absent. Note that this does not affectthe default ofgeom_smooth() orstat_smooth()(@teunbrand,#5572).stat_density() uses awider range to prevent discontinuities (#5641).stat_function() so x-axis title nowproduced automatically when no data added. (stat_summary_2d() andstat_bin_2d() nowdeal with zero-range data more elegantly (stat_summary_bin() no longer ignoreswidthparameter (ggplot2::-prefix did not work withstage() (theme(strip.clip) now defaults to"on" andis independent of Coord clipping (facet_grid(margins = TRUE) when usingexpresssions (facet_wrap(..., drop = FALSE) from throwingspurious errors when a character facetting variable containedNAs (gg_par() to translate ggplot2’sinterpretation of graphical parameters to {grid}’s interpretation (@aesthetics that takes a Geom, Stat orPosition class and generates an ‘Aesthetics’ section.make_constructor() function that builds a standardconstructor for Geom and Stat classes (element_point() andelement_polygon()that can be given totheme(point, polygon) as an extensionpoint (@teunbrand,#6248).is_waiver() is now exported to helpextensions to work withwaiver() objects (update_geom_defaults() andupdate_stat_defaults() have a reset mechanism when usingnew = NULL and invisible return the previous defaults(#4993).reset_geom_defaults() andreset_stat_defaults() to restore all geom or stat defaultaesthetics at once (complete_theme() to replicate how themesare handled during plot building (#5801).get_strip_labels() to retrieve facetlabels (@teunbrand,#4979)make_fixed_copy() method topermit copying trained position scales (#3441).setup_panel_params to interactwith the panel_params setted by Coord object (continuous_scale() andbinned_scale() sortthelimits argument internally (Scale$get_labels() format expressions as lists.after_scale() in theGeom*$default_aes field is now evaluated in the context ofdata (@teunbrand,#6135)pal_qualitative() (Coord$draw_panel() method.Facet$draw_panels() method(@teunbrand).gg class tolabs() (geom_sf() has moved from theinternalsf_grob() toGeomSf$use_defaults()(@teunbrand).Facet$draw_panel_content() method for delegatingpanel assembly (stat_align() skips computation when there is only 1group and therefore alignment is not necessary (#5788).position_stack() skips computation when allx values are unique and therefore stacking is not necessary(#5788).stat_summary() andstat_summary_bin() is setup once in total instead of onceper group (register_theme_elements(element_tree)(@teunbrand,#6162)legend.key.width andlegend.key.heightcalculations are no longer precomputed before guides are drawn (validate_subclass() fails to find a classdirectly, it tries to retrieve the class via constructor functions(@teunbrand).This is a small release focusing on providing infrastructure forother packages to gracefully prepare for changes in the next majorrelease.
is_ggproto(),is_ggplot(),is_mapping(),is_layer(),is_geom(),is_stat(),is_position(),is_coord(),is_facet(),is_scale(),is_guide(),is_guides(),is_margin(),is_theme_element() andis_theme().get_labs() function for retrieving completed plotlabels (@teunbrand,#6008).get_geom_defaults() for retrieving resolved defaultaesthetics.ggplot_build() S3 method forThis is a small release focusing on fixing regressions from 3.5.0 anddocumentation updates.
NAs (#5623)sec_axis() withbreaks = NULL (#5713).geom_sf() (resolution() has been revertedto pre-3.5.0 behaviour. Whether mapped discrete vectors should betreated as having resolution of 1 is controlled by the newdiscrete argument.guide_bins() andguide_coloursteps() where discrete breaks, such as thelevels produced bycut(), were ordered incorrectly (coord_map() andcoord_polar() throwinformative warnings when used with the guide system (#5707).stat_contour(breaks), thatfunction is used to calculate the breaks even ifbins andbinwidth are missing (geom_step() now supportslineend,linejoin andlinemitre parameters (.data pronoun is usedinaes() (#5730).stat_bin() deals with non-finite breaks better (coord_radial() don’t neatly fit thetop/right/bottom/left organisation, specifyingposition = "top" orposition = "right" in thescale will flip the placement of the radial axis (#5735)coord_radial() where full circles were nottreated as such (NA is now detected if the data contains values outside thegiven breaks (annotate() now warns aboutstat orposition arguments (guide_coloursteps(even.steps = FALSE) now works withdiscrete data that has been formatted bycut() (ggsave() now offers to install svglite if needed (This is a minor release that turned out quite beefy. It is focused onoverhauling the guide system: the system responsible for displayinginformation from scales in the guise of axes and legends. As part ofthat overhaul, new guides have been implemented and existing guides havebeen refined. The look and feel of guides has been mostly preserved, buttheir internals and styling options have changed drastically.
Briefly summarising other highlights, we also welcomecoord_radial() as a successor ofcoord_polar(). Initial support for newer graphicalfeatures, such as pattern fills has been added. The API has changed howI()/<AsIs> vectors interact with thescale system, namely: not at all.
The guide system. As a whole. See ‘new features’ for moreinformation. While the S3 guide generics are still in place, the S3methods forguide_train(),guide_merge(),guide_geom(),guide_transform(),guide_gengrob() have been superseded by the respectiveggproto methods. In practice, this will mean thatNextMethod() or sub-classing ggplot2’s guides with the S3system will no longer work.
By default,guide_legend() now only draws a keyglyph for a layer when the value is in the layer’s data. To revert tothe old behaviour, you can still setshow.legend = c({aesthetic} = TRUE) (
In thescale_{colour/fill}_gradient2() andscale_{colour/fill}_steps2() functions, themidpoint argument is transformed by the scaletransformation (#3198).
Thelegend.key theme element is set to inherit fromthepanel.background theme element. The default themes nolonger set thelegend.key element. This causes a visualchange with the defaulttheme_gray() (#5549).
Thescale_name argument incontinuous_scale(),discrete_scale() andbinned_scale() is soft-deprecated. If you have implementedcustom scales, be advised to double-check that unnamed arguments ends upwhere they should (
Thelegend.text.align andlegend.title.align arguments intheme() aredeprecated. Thehjust setting of thelegend.text andlegend.title elementscontinues to fulfill the role of text alignment (
‘lines’ units ingeom_label(), often used in thelabel.padding argument, are now are relative to the textsize. This causes a visual change, but fixes a misalignment issuebetween the textbox and text (
coord_flip() has been marked as superseded. Therecommended alternative is to swap thex andyaesthetic and/or using theorientation argument in a layer(@teunbrand,#5130).
Thetrans argument in scales and secondary axes hasbeen renamed totransform. Thetrans argumentitself is deprecated. To access the transformation from the scale, a newget_transformation() method is added to Scale-classes(#5558).
Providing a numeric vector totheme(legend.position)has been deprecated. To set the default legend position inside the plotusetheme(legend.position = "inside", legend.position.inside = c(...))instead.
Plot scales now ignoreAsIs objects constructed withI(x), instead of invoking the identity scale. This allowsthese columns to co-exist with other layers that need a non-identityscale for the same aesthetic. Also, it makes it easy to specify relativepositions (
Thefill aesthetic in many geoms now accepts grid’spatterns and gradients. For developers of layer extensions, this featurecan be enabled by switching fromfill = alpha(fill, alpha)tofill = fill_alpha(fill, alpha) when providing fills togrid::gpar() (
New functioncheck_device() for testing theavailability of advanced graphics features introduced in R 4.1.0 onward(@teunbrand,#5332).
coord_radial() is a successor tocoord_polar() with more customisation options.coord_radial() can:
guide_axis_theta() to display the angle coordinate.end argument.donut argument.angle aesthetic of layers, such asgeom_text(), to align with the coordinate system using therotate_angle argument.The guide system encompassing axes and legends, as the last remainingchunk of ggplot2, has been rewritten to use the<ggproto> system instead of the S3 system. Thischange was a necessary step to officially break open the guide systemfor extension package developers. The axes and legends now inherit froma<Guide> class, which makes them extensible in thesame manner as geoms, stats, facets and coords (#3329,
The most user-facing change is that the styling of guides isrewired through the theme system. Guides now have athemeargument that can style individual guides, whiletheme()has gained additional arguments to style guides. Theme elements declaredin the guide override theme elements set through the plot. The new themeelements for guides are:legend.key.spacing{.x/.y},legend.frame,legend.axis.line,legend.ticks,legend.ticks.length,legend.text.position andlegend.title.position. Previous style options in thearguments ofguide_*() functions aresoft-deprecated.
Unfortunately, we could not fully preserve the function ofpre-existing guide extensions written in the S3 system. A fallback forthese old guides is encapsulated in the<GuideOld>class, which calls the old S3 generics. The S3 methods have been removedas part of cleaning up, so the old guides will still work if the S3methods are reimplemented, but we encourage to switch to the new system(#2728).
Theorder argument of guides now strictly needs tobe a length-1 integer (#4958).
Newguide_axis_stack() to combine other axis guideson top of one another.
Newguide_axis_theta() to draw an axis in a circulararc incoord_radial(). The guide can be controlled byaddingguides(theta = guide_axis_theta(...)) to aplot.
Newguide_axis_logticks() can be used to drawlogarithmic tick marks as an axis. It supersedes theannotation_logticks() function (
guide_axis() gains aminor.ticksargument to draw minor ticks (#4387).
guide_axis() gains acap argument thatcan be used to trim the axis line to extreme breaks (#4907).
Primary axis titles are now placed at the primary guide, so thatguides(x = guide_axis(position = "top")) will display thetitle at the top by default (#4650).
The defaultvjust for theaxis.title.y.right element is now 1 instead of
Unknown secondary axis guide positions are now inferred as theopposite of the primary axis guide when the latter has a knownposition (#4650).
Newguide_custom() function for drawing customgraphical objects (grobs) unrelated to scales in legend positions(#5416).
All legends have acquired aposition argument, thatallows individual guides to deviate from thelegend.position set in thetheme() function.This means that legends can now be placed at multiple sides of the plot(#5488).
The spacing between legend keys and their labels, in addition tolegends and their titles, is now controlled by the text’smargin setting. Not specifying margins will automaticallyadd appropriate text margins. To control the spacing within a legendbetween keys, the newlegend.key.spacing.{x/y} argument canbe used intheme(). This leaves thelegend.spacing theme setting dedicated to solelycontrolling the spacing between different guides (#5455).
guide_colourbar() andguide_coloursteps() gain analpha argument toset the transparency of the bar (#5085).
Newdisplay argument inguide_colourbar() supplants therasterargument. In R 4.1.0 and above,display = "gradient" willdraw a gradient.
Legend keys that can draw arrows have their size adjusted forarrows.
When legend titles are larger than the legend, titlejustification extends to the placement of keys and labels(#1903).
Glyph drawing functions of thedraw_key_*() familycan now set"width" and"height" attributes(in centimetres) to the produced keys to control their displayed size inthe legend.
coord_sf() now uses customisable guides provided inthe scales orguides() function (
guide_coloursteps(even.steps = FALSE) now draws onerectangle per interval instead of many small ones (#5481).
draw_key_label() now better reflects the appearanceof labels (#5561).
position_stack() no longer silently removes missingdata, which is now handled by the geom instead of position(#3532).
Theminor_breaks function argument in scales can nowalso take a function with two arguments: the scale’s limits and thescale’s major breaks (#3583).
Failing to fit or predict instat_smooth() now givesa warning and omits the failed group, instead of throwing an error(@teunbrand,#5352).
labeller() now handles unspecified entries fromlookup tables (
fortify.default() now accepts a data-frame-likeobject granted the object exhibits healthydim(),colnames(), andas.data.frame() behaviours(@hpages,#5390).
geom_violin() gains abounds argumentanalogous togeom_density()s (
To apply dodging more consistently in violin plots,stat_ydensity() now has adrop argument tokeep or discard groups with 1 observation.
geom_boxplot() gains a new argument,staplewidth that can draw staples at the ends of whiskers(@teunbrand,#5126)
geom_boxplot() gains anoutliersargument to switch outliers on or off, in a manner that does affects thescale range. For hiding outliers that does not affect the scale range,you can continue to useoutlier.shape = NA (
Nicer error messages for xlim/ylim arguments in coord-* functions(@92amartins,#4601, #5297).
You can now omit eitherxend oryendfromgeom_segment() as only one of these is now required.If one is missing, it will be filled from thex andy aesthetics respectively. This makes drawing horizontal orvertical segments a little bit more convenient (
Whengeom_path() has aesthetics varying withingroups, thearrow() is applied to groups instead ofindividual segments (
geom_text() andgeom_label() gained asize.unit parameter that set the text size to millimetres,points, centimetres, inches or picas (
geom_label() now uses theangleaesthetic (
Thelabel.padding argument ingeom_label() now supports inputs created with themargin() function (#5030).
ScaleContinuous$get_breaks() now only callsscales::zero_range() on limits in transformed space, ratherthan in data space (#5304).
Scales throw more informative messages (
scale_*_manual() with a namedvaluesargument now emits a warning when none of those names match the valuesfound in the data (
Thename argument in most scales is now explicitlythe first argument (#5535)
Thetranslate_shape_string() internal function isnow exported for use in extensions of point layers (
To improvewidth calculation in bar plots with emptyfactor levels,resolution() considersmapped_discrete values as having resolution 1 (
Intheme(), some elements can be specified withrel() to inherit fromunit-class objects in arelative fashion (
theme() now supports splicing a list of arguments(#5542).
In the theme element hierarchy, parent elements that are a strictsubclass of child elements now confer their subclass upon the children(#5457).
Newplot.tag.location intheme() cancontrol placement of the plot tag in the"margin","plot" or the new"panel" option(#4297).
coord_munch() can now close polygon shapes (
Aesthetics listed ingeom_*() andstat_*() layers now point to relevant documentation (
The new argumentaxes infacet_grid()andfacet_wrap() controls the display of axes at interiorpanel positions. Additionally, theaxis.labels argument canbe used to only draw tick marks or fully labelled axes (
coord_polar() can have free scales in facets (
Theget_guide_data() function can be used to extractposition and label information from the plot (#5004).
Improve performance of layers without positional scales (
More informative error for mismatcheddirection/theme(legend.direction = ...)arguments (#4364, #4930).
Fixed regression inguide_legend() where thelinewidth key size wasn’t adapted to the width of the lines(#5160).
Inguide_bins(), the title no longer arbitrarilybecomes offset from the guide when it has long labels.
guide_colourbar() andguide_coloursteps() merge properly when one of theaesthetics is dropped (#5324).
When usinggeom_dotplot(binaxis = "x") with adiscrete y-variable, dots are now stacked from the y-position ratherthan from 0 (
stat_count() treatsx as unique in thesame mannerunique() does (#4609).
The plot’s title, subtitle and caption now obey horizontal textmargins (#5533).
Contour functions will not fail whenoptions("OutDec") is not. (
Lines wherelinewidth = NA are now dropped ingeom_sf() (#5204).
ggsave() no longer sometimes creates newdirectories, which is now controlled by the newcreate.dirargument (#5489).
Legend titles no longer take up space if they’ve been removed bysettinglegend.title = element_blank() (
resolution() has a small tolerance, preventingspuriously small resolutions due to rounding errors (
stage() now works correctly, even with aestheticsthat do not have scales (#5408)
stat_ydensity() with incomplete groups calculatesthe defaultwidth parameter more stably (
Thesize argument inannotation_logticks() has been deprecated in favour of thelinewidth argument (#5292).
Binned scales now treatNAs in limits the same waycontinuous scales do (#5355).
Binned scales work better withtrans = "reverse"(#5355).
Integers are once again valid input to theme arguments thatexpect numeric input (
Legends inscale_*_manual() can showNAvalues again when thevalues is a named vector (
Fixed bug incoord_sf() where graticule lines didn’tobeypanel.grid.major’s linewidth setting (
Fixed bug inannotation_logticks() when no suitabletick positions could be found (
The default width ofgeom_bar() is now based onpanel-wise resolution of the data, rather than global resolution (
stat_align() is now applied per panel instead ofglobally, preventing issues when facets have different ranges (
A stacking bug instat_align() was fixed (
stat_contour() andstat_contour_filled() now warn about and remove duplicatedcoordinates (
guide_coloursteps() andguide_bins()sort breaks (#5152).
TheScaleContinuous$get_breaks() method no longercensors the computed breaks.
The ggplot object now contains$layout which pointsto theLayout ggproto object and will be used by theggplot_build.ggplot method. This was exposed so thatpackage developers may extend the behaviour of theLayoutggproto object without needing to develop an entirely newggplot_build method (
Guide building is now part ofggplot_build() insteadofggplot_gtable() to allow guides to observe unmapped data(#5483).
ThetitleGrob() function has been refactored to befaster and less complicated.
Thescales_*() functions related to managing the<ScalesList> class have been implemented as methodsin the<ScalesList> class, rather than strayfunctions (#1310).
This hotfix release adapts to a change in r-devel’sbase::is.atomic() and the upcoming retirement ofmaptools.
fortify() for sp objects (e.g.,SpatialPolygonsDataFrame) is now deprecated and will beremoved soon in support ofthe upcomingretirement of rgdal, rgeos, and maptools. In advance of the wholeremoval,fortify(<SpatialPolygonsDataFrame>, region = ...) nolonger works as of this version (This hotfix release addresses a version comparison change in r-devel.There are no user-facing or breaking changes.
This is a hotfix release anticipating changes in r-devel, but foldsin upkeep changes and a few bug fixes as well.
Various type checks and their messages have been standardised(@teunbrand,#4834).
ggplot2 now usesscales::DiscreteRange andscales::ContinuousRange, which are available to write scaleextensions from scratch (
Thelayer_data(),layer_scales() andlayer_grob() now have the defaultplot = last_plot() (
Thedatetime_scale() scale constructor is nowexported for use in extension packages (
update_geom_defaults() andupdate_stat_defaults() now return properly classed objectsand have updated docs (
For the purposes of checking required or non-missing aesthetics,character vectors are no longer considered non-finite (
annotation_logticks() skips drawing ticks when thescale range is non-finite instead of throwing an error (
Fixed spurious warnings when theweight was used instat_bin_2d(),stat_boxplot(),stat_contour(),stat_bin_hex() andstat_quantile() (
To prevent changing the plotting order,stat_sf() isnow computed per panel instead of per group (
Fixed bug incoord_sf() where graticule lines didn’tobeypanel.grid.major’s linewidth setting (
geom_text() drops observations whereangle = NA instead of throwing an error (
This is a small release focusing on fixing regressions in the 3.4.0release and minor polishes.
y instat_ecdf() hasbeen superseded byecdf to prevent incorrect scaletransformations (Addedscale_linewidth_manual() andscale_linewidth_identity() to support thelinewidth aesthetic (
ggsave() warns when multiplefilenamesare given, and only writes to the first file (
Fixed a regression ingeom_hex() where aestheticswere replicated across bins (
Using two ordered factors as facetting variables infacet_grid(..., as.table = FALSE) now throws a warninginstead of an error (
Fixed misbehaviour ofdraw_key_boxplot() anddraw_key_crossbar() with skewed key aspect ratio (
Fixed spurious warning whenweight aesthetic wasused instat_smooth() (
Thelwd alias is now correctly replaced bylinewidth instead ofsize (
Fixed a regression inCoord$train_panel_guides()where names of guides were dropped (
In binned scales:
Automatic breaks should no longer be out-of-bounds, and automaticlimits are adjusted to include breaks (
Zero-range limits no longer throw an error and are treated akinto continuous scales with zero-range limits (
Thetrans = "date" andtrans = "time"transformations were made compatible (
This is a minor release focusing on tightening up the internals andironing out some inconsistencies in the API. The biggest change is theaddition of thelinewidth aesthetic that takes of sizingthe width of any line fromsize. This change, whileattempting to be as non-breaking as possible, has the potential tochange the look of some of your plots.
Other notable changes is a complete redo of the error and warningmessaging in ggplot2 using the cli package. Messaging is now bettercontextualised and it should be easier to identify which layer an erroris coming from. Last, we have now made the switch to using the vctrspackage internally which means that support for vctrs classes asvariables should improve, along with some small gains in renderingspeed.
Alinewidth aesthetic has been introduced andsupersedes thesize aesthetic for scaling the width oflines in line based geoms.size will remain functioning butdeprecated for these geoms and it is recommended to update all code toreflect the new aesthetic. For geoms that haveboth pointsizing and linewidth sizing (geom_pointrange() andgeom_sf)size nowonly refersto sizing of points which can leads to a visual change in old code(@thomasp85,#3672)
The default line width for polygons ingeom_sf()have been decreased to 0.2 to reflect that this is usually used fordemarking borders where a thinner line is better suited. This change wasmade since we already induced a visual change ingeom_sf()with the introduction of thelinewidth aesthetic.
The dot-dot notation (..var..) andstat(), which have been superseded byafter_stat(), are now formally deprecated (
qplot() is now formally deprecated (
stage() now properly refers to the values withoutscale transformations for the stage ofafter_stat. If yourcode requires the scaled version of the values for some reason, you haveto apply the same transformation by yourself, e.g. sqrt()forscale_{x,y}_sqrt() (
Userlang::hash() instead ofdigest::digest(). This update may lead to changes in theautomatic sorting of legends. In order to enforce a specific legendorder use theorder argument in the guide. (
referring tox in backquoted expressions withlabel_bquote() is no longer possible.
Theticks.linewidth andframe.linewidthparameters ofguide_colourbar() are now multiplied with.pt like elsewhere in ggplot2. It can cause visual changeswhen these arguments are not the defaults and these changes can berestored to their previous behaviour by adding/ .pt (
scale_*_viridis_b() now uses the full range of theviridis scales (
geom_col() andgeom_bar() gain a newjust argument. This is set to0.5 by default;usejust = 0/just = 1 to place columns on theleft/right of the axis breaks. (
geom_density() andstat_density() nowsupportbounds argument to estimate density with boundarycorrection (
ggplot now checks during statistical transformations whether anydata columns were dropped and warns about this. If stats intend to dropdata columns they can declare them in the new fielddropped_aes. (
... supportsrlang::list2 dynamic dotsin all public functions. (
theme() now has astrip.clip argument,that can be set to"off" to prevent the clipping of striptext and background borders (
geom_contour() now accepts a function in thebreaks argument (
Fix a bug inposition_jitter() where infinity valueswere dropped (@javlon,#4790).
geom_linerange() now respects thena.rmargument (#4927,
Improve the support forguide_axis() oncoord_trans() (
Addedstat_align() to align data without commonx-coordinates prior to stacking. This is now the default stat forgeom_area() (
Fix a bug instat_contour_filled() where break valuedifferences below a certain number of digits would cause thecomputations to fail (
Secondary axis ticks are now positioned more precisely, removingsmall visual artefacts with alignment between grid and ticks (
Improvestat_function documentation regardingxlim argument. (
Fix various issues with howlabels,breaks,limits, andshow.limitsinteract in the different binning guides (
Automatic break calculation now squishes the scale limits to thedomain of the transformation. This allowsscale_{x/y}_sqrt() to find breaks at 0 when appropriate(@teunbrand,#980).
Using multiple modified aesthetics correctly will no longertrigger warnings. If used incorrectly, the warning will now report theduplicated aesthetic instead ofNA (
aes() now supports the!!! operator inits first two arguments (#2675). Thanks to
Require rlang >= 1.0.0 (
geom_violin() no longer issues “collapsing to unique‘x’ values” warning (
annotate() now documents unsupported geoms(geom_abline(),geom_hline() andgeom_vline()), and warns when they are requested (
presidential dataset now includes Trump’s presidency(@bkmgit,#4703).
position_stack() now works fully withgeom_text() (
geom_tile() now correctly recognises missing data inxmin,xmax,ymin, andymax (
geom_hex() will now use the binwidth fromstat_bin_hex() if present, instead of deriving it (
geom_hex() now works on non-linear coordinatesystems (
Fixed a bug throwing errors when trying to render an empty plotwith secondary axes (
Axes are now added correctly infacet_wrap() whenas.table = FALSE (
Better compatibility of custom device functions inggsave() (
Binning scales are now more resilient to calculated limits thatends up beingNaN after transformations (
Strip padding infacet_grid() is now only in effectifstrip.placement = "outside"and an axis ispresent between the strip and the panel (
Aesthetics of length 1 are now recycled to 0 if the length of thedata is 0 (
Settingsize = NA will no longer causeguide_legend() to error (
Settingstroke toNA ingeom_point() will no longer impair the sizing of the points(@thomasp85,#4624)
stat_bin_2d() now correctly recognises theweight aesthetic (
All geoms now have consistent exposure of linejoin and lineendparameters, and the guide keys will now respect these settings (
geom_sf() now respectsarrow parameterfor lines (
Updated documentation forprint.ggplot to reflectthat it returns the original plot, not the result ofggplot_build(). (
scale_*_manual() no longer displays extra legendkeys, or changes their order, when a namedvalues argumenthas more items than the data. To display allvalues on thelegend instead, usescale_*_manual(values = vals, limits = names(vals)). (
Updated documentation forgeom_contour() tocorrectly reflect argument precedence betweenbins andbinwidth. (
Dots ingeom_dotplot() are now correctly aligned tothe baseline whenstackratio != 1 andstackdir != "up" (
Key glyphs forgeom_boxplot(),geom_crossbar(),geom_pointrange(), andgeom_linerange() are now orientation-aware (
Updated documentation forgeom_smooth() to moreclearly describe effects of thefullrange parameter (
This is a very small release only applying an internal change tocomply with R 4.2 and its deprecation ofdefault.stringsAsFactors(). There are no user facingchanges and no breaking changes.
This is a very small release focusing on fixing a couple of untenableissues that surfaced with the 3.3.4 release
geom_abline()) as it introduced undesirable issues farworse than the bug it fixed (ggsave() when producing emf/wmf files(coord_sf() was reporting that it isnon-linear even when data is provided in projected coordinates (This is a larger patch release fixing a huge number of bugs andintroduces a small selection of feature refinements.
Alt-text can now be added to a plot using thealtlabel, i.e+ labs(alt = ...). Currently this alt text isnot automatically propagated, but we plan to integrate into Shiny,RMarkdown, and other tools in the future. (
Add support for the BrailleR package for creating descriptions ofthe plot when rendered (
coord_sf() now has an argumentdefault_crs that specifies the coordinate reference system(CRS) for non-sf layers and scale/coord limits. This argument defaultstoNULL, which means non-sf layers are assumed to be inprojected coordinates, as in prior ggplot2 versions. Settingdefault_crs = sf::st_crs(4326) provides a simple way tointerpret x and y positions as longitude and latitude, regardless of theCRS used bycoord_sf(). Authors of extension packagesimplementingstat_sf()-like functionality are encouraged tolook at the source code ofstat_sf()’scompute_group() function to see how to provide scale-limithints tocoord_sf() (
ggsave() now uses ragg to render raster output ifragg is available. It also handles custom devices that sets a defaultunit (e.g. ragg::agg_png) correctly (
ggsave() now returns the saved file locationinvisibly (#3379,<ggplot object> + ggsave() no longerworks (#4513).
The scale argumentslimits,breaks,minor_breaks,labels,rescalerandoob now accept purrr style lambda notation (as_labeller() (and therefore alsolabeller()) (
Manual scales now allow named vectors passed tovalues to contain fewer elements than existing in the data.Elements not present in values will be set toNA (
Date and datetime position scales support out-of-bounds (oob)arguments to control how limits affect data outside those limits (
Fix a bug thatafter_stat() andafter_scale() cannot refer to aesthetics if it’s specifiedin the plot-global mapping (
Fix bug inannotate_logticks() that would cause anerror when used together withcoord_flip() (
Fix a bug ingeom_abline() that resulted inintercept not being subjected to the transformation of they scale (
Extent the range of the line created bygeom_abline() so that line ending is not visible for largelinewidths (
Fix bug ingeom_dotplot() where dots would bepositioned wrong withstackgroups = TRUE (
Fix calculation of confidence interval for locfit smoothing ingeom_smooth() (
Fix bug ingeom_text() where"outward"and"inward" justification for someanglevalues was reversed (
ggsave() now sets the default background to matchthe fill value of theplot.background theme element (
It is now deprecated to specifyguides(<scale> = FALSE) orscale_*(guide = FALSE) to remove a guide. Please useguides(<scale> = "none") orscale_*(guide = "none") instead (
Fix a bug inguide_bins() where keys would disappearif the guide was reversed (
Fix bug inguide_coloursteps() that would repeat theterminal bins if the breaks coincided with the limits of the scale(@thomasp85,#4019)
Make sure that default labels from default mappings doesn’toverwrite default labels from explicit mappings (
Fix bug inlabeller() where parsing was turned offif.multiline = FALSE (
Make surelabel_bquote() has access to the callingenvironment when evaluating the labels (
Fix a bug in the layer implementation that introduced a new stateafter the first render which could lead to a different look whenrendered the second time (
Fix a bug in legend justification where justification was lost ofthe legend dimensions exceeded the available size (
Fix a bug inposition_dodge2() whereNAvalues in thee data would cause an error (
Make sureposition_jitter() creates the samejittering independent of whether it is called by name or withconstructor (
Fix a bug inposition_jitter() where differentjitters would be applied to different position aesthetics of the sameaxis (@thomasp85,#2941)
Fix a bug inqplot() when supplyingc(NA, NA) as axis limits (
Remove cross-inheritance of default discrete colour/fill scalesand check the type and aesthetic of function output iftypeis a function (
Fix bug inscale_[x|y]_date() where custom breaksfunctions that resulted in fractional dates would get misaligned (
Fix bug inscale_[x|y]_datetime() where a specifiedtimezone would be ignored by the scale (
Fix issue insec_axis() that would throw warnings inthe absence of any secondary breaks (
stat_bin()’s computed variablewidth isnow documented (#3522).
stat_count() now computes width based on the fulldataset instead of per group (
Extendedstat_ecdf() to calculate the cdf fromeither x or y instead from y only (
Fix a bug instat_summary_bin() where one more thanthe requested number of bins would be created (
Only drop groups instat_ydensity() when there arefewer than two data points and throw a warning (
Fixed a bug in strip assembly when theme hasstrip.text = element_blank() and plots are faceted withmulti-layered strips (
Usingtheme(aspect.ratio = ...) together with freespace infacet_grid() now correctly throws an error (
Fixed a bug inlabeller() so that.default is passed toas_labeller() whenlabellers are specified by naming faceting variables. (
Updated style for example code (
ggplot2 now requires R >= 3.3 (#4247).
ggplot2 now usesrlang::check_installed() to checkif a suggested package is installed, which will offer to install thepackage before continuing (#4375,
Improved error with hint when piping aggplot objectinto a facet function (#4379,
This is a small patch release mainly intended to address changes in Rand CRAN. It further changes the licensing model of ggplot2 to an MITlicense.
Update the ggplot2 licence to an MIT license (#4231, #4232,#4233, and #4281)
Use vdiffr conditionally so ggplot2 can be tested on systemswithout vdiffr
Update tests to work with the newall.equal()defaults in R >4.0.3
Fixed a bug thatguide_bins() mistakenly ignoreoverride.aes argument (
This is a small release focusing on fixing regressions introduced in3.3.1.
Added anoutside option toannotation_logticks() that places tick marks outside of theplot bounds. (#3783,
annotation_raster() adds support for native rasters.For large rasters, native rasters render significantly faster thanarrays (@kent37,#3388)
Facet strips now have dedicated position-dependent theme elements(strip.text.x.top,strip.text.x.bottom,strip.text.y.left,strip.text.y.right) thatinherit fromstrip.text.x andstrip.text.y,respectively. As a consequence, some theme stylings now need to beapplied to the position-dependent elements rather than to the parentelements. This change was already introduced in ggplot2 3.3.0 but notlisted in the changelog. (
Facets now handle layers containing no data (
A newly added geomgeom_density_2d_filled() andassociated statstat_density_2d_filled() can draw filleddensity contours (
A newly addedgeom_function() is now recommended touse in conjunction with/instead ofstat_function(). Inaddition,stat_function() now works with transformed yaxes, e.g. scale_y_log10(), and in plots containing noother data or layers (
Fixed a bug ingeom_sf() that caused problems withlegend-type autodetection (
Support graphics devices that use thefile argumentinstead offileneame inggsave() (
Default discrete color scales are now configurable through theoptions() ofggplot2.discrete.colour andggplot2.discrete.fill. When set to a character vector ofcolour codes (or list of character vectors) with sufficient length,these colours are used for the default scale. Seehelp(scale_colour_discrete) for more details and examples(@cpsievert,#3833).
Default continuous colour scales (i.e., theoptions()ggplot2.continuous.colour andggplot2.continuous.fill, which inform thetypeargument ofscale_fill_continuous() andscale_colour_continuous()) now accept a function, whichallows more control over these defaultcontinuous_scale()s(@cpsievert,#3827).
A bug was fixed instat_contour() when calculatingbreaks based on thebins argument (
Data columns can now containVector S4 objects,which are widely used in the Bioconductor project. (
This is a small release with no code change. It removes all maliciouslinks to a site that got hijacked from the readme and pkgdown site.
This is a minor release but does contain a range of substantial newfeatures, along with the standard bug fixes. The release contains a fewvisual breaking changes, along with breaking changes for extensiondevelopers due to a shift in internal representation of the positionscales and their axes. No user breaking changes are included.
This release also adds Dewey Dunnington (
There are no user-facing breaking changes, but a change in someinternal representations that extension developers may have relied on,along with a few breaking visual changes which may cause visual tests indownstream packages to fail.
Thepanel_params field in theLayoutnow contains a list of list ofViewScale objects,describing the trained coordinate system scales, instead of the listobject used before. Any extensions that use this field will likelybreak, as will unit tests that checks aspects of this.
element_text() now issues a warning when vectorizedarguments are provided, as incolour = c("red", "green", "blue"). Such use is discouragedand not officially supported (
Changedtheme_grey() setting for legend key so thatit creates no border (NA) rather than drawing a white one.(@annennenne,#3180)
geom_ribbon() now draws separate lines for the upperand lower intervals ifcolour is mapped. Similarly,geom_area() andgeom_density() now draw theupper lines only in the same case by default. If you want old-style fullstroking, useoutline.type = "full" (
The evaluation time of aesthetics can now be controlled to afiner degree.after_stat() supersedes the use ofstat() and..var..-notation, and is joined byafter_scale() to allow for mapping to scaled aestheticvalues. Remapping of the same aesthetic is now supported withstage(), so you can map a data variable to a stataesthetic, and remap the same aesthetic to something else afterstatistical transformation (
Allcoord_*() functions withxlim andylim arguments now accept vectors withNA as aplaceholder for the minimum or maximum value (e.g.,ylim = c(0, NA) would zoom the y-axis from 0 to the maximumvalue observed in the data). This mimics the behaviour of thelimits argument in continuous scale functions (
Allowed reversing of discrete scales by re-writingget_limits() (
All geoms and stats that had a direction (i.e. where the x and yaxes had different interpretation), can now freely choose theirdirection, instead of relying oncoord_flip(). Thedirection is deduced from the aesthetic mapping, but can also bespecified directly with the neworientation argument (
Position guides can now be customized using the newguide_axis(), which can be passed to positionscale_*() functions or viaguides(). The newaxis guide (guide_axis()) comes with argumentscheck.overlap (automatic removal of overlapping labels),angle (easy rotation of axis labels), andn.dodge (dodge labels into multiple rows/columns) (
A new scale type has been added, that allows binning ofaesthetics at the scale level. It has versions for both position andnon-position aesthetics and comes with two new guides(guide_bins andguide_coloursteps) (
scale_x_continuous() andscale_y_continuous() gains ann.breaksargument guiding the number of automatic generated breaks (
Addedstat_contour_filled() andgeom_contour_filled(), which compute and draw filledcontours of gridded data (geom_contour() andstat_contour() now use theisoband package to compute contour lines. Thecompleteparameter (which was undocumented and has been unused for at least fouryears) was removed (
Themes have gained two new parameters,plot.title.position andplot.caption.position,that can be used to customize how plot title/subtitle and plot captionare positioned relative to the overall plot (
Geom now gains asetup_params() methodin line with the other ggproto classes (
The newly added functionregister_theme_elements()now allows developers of extension packages to define their own newtheme elements and place them into the ggplot2 element tree (
coord_trans() now draws second axes and acceptsxlim,ylim, andexpand argumentsto bring it up to feature parity withcoord_cartesian().Thextrans andytrans arguments that weredeprecated in version 1.0.1 in favour ofx andy were removed (
coord_trans() now calculates breaks using theexpanded range (previously these were calculated using the unexpandedrange, which resulted in differences between plots made withcoord_trans() and those made withcoord_cartesian()). The expansion for discrete axes incoord_trans() was also updated such that it behavesidentically to that incoord_cartesian() (
expand_scale() was deprecated in favour ofexpansion() for setting theexpand argument ofx andy scales (
geom_abline(),geom_hline(), andgeom_vline() now issue more informative warnings whensupplied with set aesthetics (i.e.,slope,intercept,yintercept, and/orxintercept) and mapped aesthetics (i.e.,dataand/ormapping).
Fix a bug ingeom_raster() that squeezed the imagewhen it went outside scale limits (#3539,
geom_sf() now determines the legend typeautomatically (
geom_sf() now removes rows that can’t be plotted duetoNA aesthetics (#3546,
geom_sf() now applies alpha to linestring geometries(#3589,
gg_dep() was deprecated (
Added functionggplot_add.by() for lists createdwithby(), allowing such lists to be added to ggplotobjects (#2734,
ggplot2 no longer depends on reshape2, which means that it nolonger (recursively) needs plyr, stringr, or stringi packages.
Increase the defaultnbin ofguide_colourbar() to place the ticks more precisely (#3508,
manual_scale() now matchesvalues withthe order ofbreaks whenevervalues is anunnamed vector. Previously, unnamedvalues would match withthe limits of the scale and ignore the order of anybreaksprovided. Note that this may change the appearance of plots thatpreviously relied on the unordered behaviour (#2429,
scale_manual_*(limits = ...) now actually limits thescale (#3262,
Fix a bug whenshow.legend is a named logical vector(#3461,
Added weight aesthetic option tostat_density() andmade scaling of weights the default (
stat_density2d() can now take anadjustparameter to scale the default bandwidth. (#2860,
stat_smooth() usesREML by default, ifmethod = "gam" andgam’s method is notspecified (
stacking text when calculating the labels and the y axis withstat_summary() now works (
stat_summary() and related functions now supportrlang-style lambda functions (#3568,
The data mask pronoun,.data, is now stripped fromdefault labels.
Addition of partial themes to plots has been made morepredictable; stepwise addition of individual partial themes is nowequivalent to addition of multple theme elements at once (
Facets now don’t fail even when some variable in the spec are notavailable in all layers (
This is a patch release fixing a few regressions introduced in 3.2.0as well as fixing some unit tests that broke due to upstreamchanges.
position_stack() no longer changes the order of theinput data. Changes to the internal behaviour ofgeom_ribbon() made this reordering problematic with ribbonsthat spannedy = 0 (#3471)qplot() with a single positional aesthetic willno longer title the non-specified scale as"NULL"(#3473)This is a minor release with an emphasis on internal changes to makeggplot2 faster and more consistent. The few interface changes will onlyaffect the aesthetics of the plot in minor ways, and will onlypotentially break code of extension developers if they have relied oninternals that have been changed. This release also sees the addition ofHiroaki Yutani (
With the release of R 3.6, ggplot2 now requires the R version to beat least 3.2, as the tidyverse is committed to support 5 major versionsof R.
Two patches (#2996 and #3050) fixed minor rendering problems. Inmost cases, the visual changes are so subtle that they are difficult tosee with the naked eye. However, these changes are detected by thevdiffr package, and therefore any package developers who use vdiffr totest for visual correctness of ggplot2 plots will have to regenerate allreference images.
In some cases, ggplot2 now produces a warning or an error forcode that previously produced plot output. In all these cases, theprevious plot output was accidental, and the plotting code uses theggplot2 API in a way that would lead to undefined behavior. Examplesinclude a missinggroup aesthetic ingeom_boxplot() (#3316), annotations across multiple facets(#3305), and not using aesthetic mappings when drawing ribbons withgeom_ribbon() (#3318).
This release includes a range of internal changes that speeds upplot generation. None of the changes are user facing and will not breakany code, but in general ggplot2 should feel much faster. The changesincludes, but are not limited to:
Caching ascent and descent dimensions of text to avoidrecalculating it for every title.
Using a faster data.frame constructor as well as faster indexinginto data.frames
Removing the plyr dependency, replacing plyr functions withfaster equivalents.
geom_polygon() can now draw polygons with holesusing the newsubgroup aesthetic. This functionalityrequires R 3.6.0 (
Aesthetic mappings now accept functions that returnNULL (
stat_function() now accepts rlang/purrr styleanonymous functions for thefun parameter (
geom_rug() gains an “outside” option to allow formoving the rug tassels to outside the plot area (length option to allow for changing the length of the ruglines (
All geoms now take akey_glyph paramter that allowsusers to customize how legend keys are drawn (timeseries is provided to draw nice legends fortime series (
Layers now have a new member functionsetup_layer()which is called at the very beginning of the plot building process andwhich has access to the original input data and the plot object beingbuilt. This function allows the creation of custom layers thatautogenerate aesthetic mappings based on the input data or that filterthe input data in some form. For the time being, this feature is notexported, but it has enabled the development of a new layer type,layer_sf() (see next item). Other special-purpose layertypes may be added in the future (
A new layer typelayer_sf() can auto-detect andauto-map sf geometry columns in the data. It should be used by extensiondevelopers who are writing new sf-based geoms or stats (
x0 andy0 are now recognized positionalaesthetics so they will get scaled if used in extension geoms and stats(@thomasp85,#3168)
Continuous scale limits now accept functions which accept thedefault limits and return adjusted limits. This makes it possible towrite a function that e.g. ensures the limits are always a multiple of100, regardless of the data (
cut_width() now accepts... to passfurther arguments tobase::cut.default() likecut_number() andcut_interval() already did(@cderv,#3055)
coord_map() now can have axes on the top and right(@karawoo,#3042).
coord_polar() now correctly rescales the secondaryaxis (@linzi-sg,#3278)
coord_sf(),coord_map(), andcoord_polar() now squash-Inf andInf into the min and max of the plot (
coord_sf() graticule lines are now drawn in the samethickness as panel grid lines incoord_cartesian(), andseting panel grid lines toelement_blank() now also worksincoord_sf() (
economics data has been regenerated. This leads tosome changes in the values of all columns (especially inpsavert), but more importantly, strips the groupingattributes fromeconomics_long.
element_line() now fills closed arrows (
Facet strips on the left side of plots now have clipping turnedon, preventing text from running out of the strip and borders fromlooking thicker than for other strips (
ggplot2 now works in Turkish locale (
Clearer error messages for inappropriate aesthetics (
ggplot2 no longer attaches any external packages when usingfunctions that depend on packages that are suggested but not imported byggplot2. The affected functions includegeom_hex(),stat_binhex(),stat_summary_hex(),geom_quantile(),stat_quantile(), andmap_data() (
geom_area() andgeom_ribbon() now sortthe data along the x-axis in thesetup_data() method ratherthan as part ofdraw_group() (
geom_hline(),geom_vline(), andgeom_abline() now throw a warning if the user supplies bothanxintercept,yintercept, orslope value and a mapping (
geom_rug() now works withcoord_flip()(@has2k1,#2987).
geom_violin() no longer throws an error whenquantile lines fall outside the violin polygon (
guide_legend() andguide_colorbar() nowuse appropriate spacing between legend key glyphs and legend text evenif the legend title is missing (
Default labels are now generated more consistently; e.g., symbolsno longer get backticks, and long expressions are abbreviated with... (
All-Inf layers are now ignored for picking the scale(
Diverging Brewer colour palette now use the correct mid-pointcolour (
scale_color_continuous() now points toscale_colour_continuous() so that it will handletype = "viridis" as the documentation states (
scale_shape_identity() now works correctly withguide = "legend" (1, #3029)
scale_continuous will now draw axis line even if thelength of breaks is 0 (
stat_bin() will now error when the number of binsexceeds 1e6 to avoid accidentally freezing the user session (
sec_axis() now places ticks accurately when usingnonlinear transformations (
facet_wrap() andfacet_grid() nowautomatically remove NULL from facet specs, and accept empty specs(
stat_bin() now handles data with only one uniquevalue (
sec_axis() now accepts functions as well as formulas(
New theme elements allowing different ticks lengths for eachaxis. For instance, this can be used to have inwards ticks on the x-axis(axis.ticks.length.x) and outwards ticks on the y-axis(axis.ticks.length.y) (
The arguments ofStat*$compute_layer() andPosition*$compute_layer() are now renamed to always matchthe ones ofStat$compute_layer() andPosition$compute_layer() (
geom_*() andstat_*() now acceptspurrr-style lambda notation (
geom_tile() andgeom_rect() now drawrectangles without notches at the corners. The style of the corner canbe controlled bylinejoin parameters (
This is a minor release and breaking changes have been kept to aminimum. End users of ggplot2 are unlikely to encounter any issues.However, there are a few items that developers of ggplot2 extensionsshould be aware of. For additional details, see also the discussionaccompanying issue #2890.
In non-user-facing internal code (specifically in theaes() function and in theaesthetics argumentof scale functions), ggplot2 now always uses the British spelling foraesthetics containing the word “colour”. When users specify a “color”aesthetic it is automatically renamed to “colour”. This renaming is alsoapplied to non-standard aesthetics that contain the word “color”. Forexample, “point_color” is renamed to “point_colour”. This conventionmakes it easier to support both British and American spelling for novel,non-standard aesthetics, but it may require some adjustment for packagesthat have previously introduced non-standard color aesthetics usingAmerican spelling. A new functionstandardise_aes_names()is provided in case extension writers need to perform this renaming intheir own code (
Functions that generate other functions (closures) now force thearguments that are used from the generated functions, to avoidhard-to-catch errors. This may affect some users of manual scales (suchasscale_colour_manual(),scale_fill_manual(),etc.) who depend on incorrect behavior (
Coord objects now have a functionbacktransform_range() that returns the panel range in datacoordinates. This change may affect developers of custom coords, who nowshould implement this function. It may also affect developers of customgeoms that use therange() function. In some applications,backtransform_range() may be more appropriate (
coord_sf() has much improved customization of axistick labels. Labels can now be set manually, and there are two newparameters,label_graticule andlabel_axes,that can be used to specify which graticules to label on which side ofthe plot (
Two new geomsgeom_sf_label() andgeom_sf_text() can draw labels and text on sf objects.Under the hood, a newstat_sf_coordinates() calculates thex and y coordinates from the coordinates of the sf geometries. You cancustomize the calculation method viafun.geometry argument(
benchplot() now uses tidy evaluation (
The error message incompute_aesthetics() now onlyprovides the names of aesthetics with mismatched lengths, rather thanall aesthetics (
For faceted plots, data is no longer internally reordered. Thismakes it safer to feed data columns intoaes() or intoparameters of geoms or stats. However, doing so remains discouraged(@clauswilke,#2694).
coord_sf() now also understands theclip argument, just like the other coords (
fortify() now displays a more informative errormessage forgrouped_df() objects when dplyr is notinstalled (
Allgeom_*() now display an informative errormessage when required aesthetics are missing (
geom_boxplot() now understands thewidth parameter even when used with a non-standard stat,such asstat_identity() (
geom_hex() now understands thesize andlinetype aesthetics (
geom_hline(),geom_vline(), andgeom_abline() now work properly withcoord_trans() (
geom_text(..., parse = TRUE) now correctly rendersthe expected number of items instead of silently dropping items that areempty expressions, e.g. the empty string ““. If an expression spansmultiple lines, we take just the first line and drop the rest. This sameissue is also fixed forgeom_label() and the axis labelsforgeom_sf() (
geom_sf() now respectslineend,linejoin, andlinemitre parameters for linesand polygons (
ggsave() now exits without creating a new graphicsdevice if previously none was open (
labs() now has named argumentstitle,subtitle,caption, andtag. Also,labs() now accepts tidyeval (
position_nudge() is now more robust and nudges onlyin the direction requested. This enables, for example, the horizontalnudging of boxplots (
sec_axis() anddup_axis() now returnappropriate breaks for the secondary axis when applied to logtransformed scales (
sec_axis() now works as expected when used incombination with tidy eval (
scale_*_date(),scale_*_time() andscale_*_datetime() can now display a secondary axis that isaone-to-one transformation of the primary axis,implemented using thesec.axis argument to the scaleconstructor (
stat_contour(),stat_density2d(),stat_bin2d(),stat_binhex() now calculatenormalized statistics includingnlevel,ndensity, andncount. Also,stat_density() now includes the calculated statisticnlevel, an alias forscaled, to better matchthe syntax ofstat_bin() (
ggplot2 now supports/uses tidy evaluation (as described below).This is a major change and breaks a number of packages; we made thisbreaking change because it is important to make ggplot2 moreprogrammable, and to be more consistent with the rest of the tidyverse.The best general (and detailed) introduction to tidy evaluation can befound in the meta programming chapters inAdvanced R.
The primary developer facing change is thataes() nowcontains quosures (expression + environment pairs) rather than symbols,and you’ll need to take a different approach to extracting theinformation you need. A common symptom of this change are errors“undefined columns selected” or “invalid ‘type’ (list) of argument”(#2610). As in the previous version, constants (likeaes(x = 1) oraes(colour = "smoothed")) arestored as is.
In this version of ggplot2, if you need to describe a mapping in astring, usequo_name() (to generate single-line strings;longer expressions may be abbreviated) orquo_text() (togenerate non-abbreviated strings that may span multiple lines). If youdo need to extract the value of a variable instead userlang::eval_tidy(). You may want to condition on(packageVersion("ggplot2") <= "2.2.1") so that your codecan work with both released and development versions of ggplot2.
We recognise that this is a big change and if you’re not alreadyfamiliar with rlang, there’s a lot to learn. If you are stuck, or needany help, please reach out onhttps://forum.posit.co/.
Error: Columny must be a 1d atomic vector or alist
Internally, ggplot2 now usesas.data.frame(tibble::as_tibble(x)) to convert a list intoa data frame. This improves ggplot2’s support for list-columns (neededfor sf support), at a small cost: you can no longer use matrix-columns.Note that unlike tibble we still allow column vectors such as returnedbybase::scale() because of their widespread use.
Error: More than one expression parsed
Previouslyaes_string(x = c("a", "b", "c")) silentlyreturnedaes(x = a). Now this is a clear error.
Error:data must be uniquely named but has duplicatecolumns
If layer data contains columns with identical names an error will bethrown. In earlier versions the first occurring column was chosensilently, potentially masking that the wrong data was chosen.
Error: Aesthetics must be either length 1 or the same as thedata
Layers are stricter about the columns they will combine into a singledata frame. Each aesthetic now must be either the same length as thedata frame or a single value. This makes silent recycling errors muchless likely.
Error:coord_* doesn’t support free scales
Free scales only work with selected coordinate systems; previouslyyou’d get an incorrect plot.
Error in f(…) : unused argument (range = c(0, 1))
This is because theoob argument to scale has been setto a function that only takes a single argument; it needs to take twoarguments (x, andrange).
Error: unused argument (output)
The functionguide_train() now has an optional parameteraesthetic that allows you to override theaesthetic setting in the scale. To make your code work withthe both released and development versions of ggplot2 appropriate, addaesthetic = NULL to theguide_train() methodsignature.
# oldguide_train.legend<-function(guide, scale) {...}# newguide_train.legend<-function(guide, scale,aesthetic =NULL) {...}Then, inside the function, replacescale$aesthetics[1],aesthetic %||% scale$aesthetics[1]. (The %||% operator isdefined in the rlang package).
# oldsetNames(list(scale$map(breaks)), scale$aesthetics[1])# newsetNames(list(scale$map(breaks)), aesthetic%||% scale$aesthetics[1])The long-deprecatedsubset argument tolayer() has been removed.
aes() now supports quasiquotation so that you canuse!!,!!!, and:=. Thisreplacesaes_() andaes_string() which are nowsoft-deprecated (but will remain around for a long time).
facet_wrap() andfacet_grid() nowsupportvars() inputs. Likedplyr::vars(),this helper quotes its inputs and supports quasiquotation. For instance,you can now supply faceting variables like this:facet_wrap(vars(am, cyl)) instead offacet_wrap(~am + cyl). Note that the formula interface isnot going away and will not be deprecated.vars() is simplymeant to make it easier to create functions aroundfacet_wrap() andfacet_grid().
The first two arguments offacet_grid() becomerows andcols and now supportvars() inputs. Note however that we took special care toensure complete backward compatibility. With this changefacet_grid(vars(cyl), vars(am, vs)) is equivalent tofacet_grid(cyl ~ am + vs), andfacet_grid(cols = vars(am, vs)) is equivalent tofacet_grid(. ~ am + vs).
One nice aspect of the new interface is that you can now easilysupply names:facet_grid(vars(Cylinder = cyl), labeller = label_both)will give nice label titles to the facets. Of course, those names can beunquoted with the usual tidy eval syntax.
ggplot2 now has full support for sf withgeom_sf()andcoord_sf():
nc<- sf::st_read(system.file("shape/nc.shp",package ="sf"),quiet =TRUE)ggplot(nc)+geom_sf(aes(fill = AREA))It supports all simple features, automatically aligns CRS acrosslayers, sets up the correct aspect ratio, and draws agraticule.
ggplot2 now works on R 3.1 onwards, and uses thevdiffr package for visualtesting.
In most cases, accidentally using%>% instead of+ will generate an informative error (#2400).
New syntax for calculated aesthetics. Instead of usingaes(y = ..count..) you can (and should!) useaes(y = stat(count)).stat() is a realfunction with documentation which hopefully will make this part ofggplot2 less confusing (#2059).
stat() is particularly nice for more complexcalculations because you only need to specify it once:aes(y = stat(count / max(count))), rather thanaes(y = ..count.. / max(..count..))
Newtag label for adding identification tags toplots, typically used for labelling a subplot with a letter. Add a tagwithlabs(tag = "A"), style it with theplot.tag theme element, and control position with theplot.tag.position theme setting (
geom_segment() andgeom_curve() have anewarrow.fill parameter which allows you to specify aseparate fill colour for closed arrowheads (
geom_point() and friends can now take shapes asstrings instead of integers,e.g. geom_point(shape = "diamond") (
position_dodge() gains apreserveargument that allows you to control whether thetotal widthat eachx value is preserved (the current default), orensure that the width of asingle element is preserved(what many people want) (#1935).
Newposition_dodge2() provides enhanced dodging forboxplots. Compared toposition_dodge(),position_dodge2() comparesxmin andxmax values to determine which elements overlap, andspreads overlapping elements evenly within the region of overlap.position_dodge2() is now the default position adjustmentforgeom_boxplot(), because it handlesvarwidth = TRUE, and will be considered for other geoms inthe future.
Thepadding parameter adds a small amount of paddingbetween elements (reverseparameter allows you to reverse the order of placement (
Newstat_qq_line() makes it easy to add a simpleline to a Q-Q plot, which makes it easier to judge the fit of thetheoretical distribution (
Improved support for mapping date/time variables toalpha,size,colour, andfill aesthetics, includingdate_breaks anddate_labels arguments (scale_alpha() variants (
Improved support for ordered factors. Ordered factors throw awarning when mapped to shape (unordered factors do not), and do notthrow warnings when mapped to size or alpha (unordered factors do).Viridis is used as the default colour and fill scale for ordered factors(@karawoo,#1526).
Theexpand argument ofscale_*_continuous() andscale_*_discrete()now accepts separate expansion values for the lower and upper rangelimits. The expansion limits can be specified using the conveniencefunctionexpand_scale().
Separate expansion limits may be useful for bar charts, e.g. if onewants the bottom of the bars to be flush with the x axis but still leavesome (automatically calculated amount of) space above them:
ggplot(mtcars)+geom_bar(aes(x =factor(cyl)))+scale_y_continuous(expand =expand_scale(mult =c(0, .1)))It can also be useful for line charts, e.g. for counts over time,where one wants to have a ’hard’ lower limit of y = 0 but leave theupper limit unspecified (and perhaps differing between panels), withsome extra space above the highest point on the line (with symmetricallimits, the extra space above the highest point could in some casescause the lower limit to be negative).
The old syntax for theexpand argument will, of course,continue to work (
scale_colour_continuous() andscale_colour_gradient() are now controlled by globaloptionsggplot2.continuous.colour andggplot2.continuous.fill. These can be set to"gradient" (the default) or"viridis" (
Newscale_colour_viridis_c()/scale_fill_viridis_c()(continuous) andscale_colour_viridis_d()/scale_fill_viridis_d()(discrete) make it easy to use Viridis colour scales (
Guides forgeom_text() now accept custom labels withguide_legend(override.aes = list(label = "foo")) (
Strips gain margins on all sides by default. This means that tofully justify text to the edge of a strip, you will need to also set themargins to 0 (
Rotated strip labels now correctly understandhjustandvjust parameters at all angles (
Strip labels now understand justification relative to thedirection of the text, meaning that in y facets, the strip text can beplaced at either end of the strip usinghjust (
Legend titles and labels get a little extra space around them,which prevents legend titles from overlapping the legend at large fontsizes (@karawoo,#1881).
Newautolayer() S3 generic (autoplot() but produces layers rather thancomplete plots.
Custom objects can now be added using+ if aggplot_add method has been defined for the class of theobject (
Theme elements can now be subclassed. Add amerge_element method to control how properties areinherited from the parent element. Add anelement_grobmethod to define how elements are rendered into grobs (
Coords have gained new extension mechanisms.
If you have an existing coord extension, you will need to revise thespecification of thetrain() method. It is now calledsetup_panel_params() (better reflecting what it actuallydoes) and now has argumentsscale_x, andscale_y (the x and y scales respectively) andparam, a list of plot specific parameters generated bysetup_params().
What was formerly calledscale_details (in coords),panel_ranges (in layout) andpanel_scales (ingeoms) are now consistently calledpanel_params (#1311).These are parameters of the coord that vary from panel topanel.
ggplot_build() andggplot_gtable() arenow generics, so ggplot-subclasses can define additional behavior duringthe build stage.
guide_train(),guide_merge(),guide_geom(), andguide_gengrob() are nowexported as they are needed if you want to design your own guide. Theyare not currently documented; use at your own risk (#2528).
scale_type() generic is now exported and documented.Use this if you want to extend ggplot2 to work with a new type ofvector.
facet_grid() gives a more informative error messageif you try to use a variable in both rows and cols (#1928).
facet_grid() andfacet_wrap() both givebetter error messages if you attempt to use an unsupported coord withfree scales (#2049).
label_parsed() works once again (#2279).
You can now style the background of horizontal and verticalstrips independently withstrip.background.x andstrip.background.y theme settings (#2249).
discrete_scale() documentation now inherits shareddefinitions fromcontinuous_scale() (
guide_colorbar() shows all colours of the scale(@has2k1,#2343).
scale_identity() once again produces legends bydefault (#2112).
Tick marks for secondary axes with strong transformations aremore accurately placed (
Missing line types now reliably generate missing lines (withstandard warning) (#2206).
Legends now ignore set aesthetics that are not length one(#1932).
All colour and fill scales now have anaestheticsargument that can be used to set the aesthetic(s) the scale works with.This makes it possible to apply a colour scale to both colour and fillaesthetics at the same time, viaaesthetics = c("colour", "fill") (
Three new generic scales work with any aesthetic or set ofaesthetics:scale_continuous_identity(),scale_discrete_identity(), andscale_discrete_manual() (
scale_*_gradient2() now consistently omits pointsoutside limits by rescaling after the limits are enforced (
geom_label() now correctly produces unborderedlabels whenlabel.size is 0, even when saving to PDF (
layer() gives considerably better error messages forincorrectly specifiedgeom,stat, orposition (#2401).
In all layers that use it,linemitre now defaults to10 (instead of 1) to better match base R.
geom_boxplot() now supplies a default value if nox aesthetic is present (
geom_density() drops groups with fewer than two datapoints and throws a warning. For groups with two data points, densityvalues are now calculated withstats::density (
geom_segment() now also takes alinejoin parameter. This allows more control over theappearance of the segments, which is especially useful for plottingthick arrows (@Ax3man,#774).
geom_smooth() now reports the formula used whenmethod = "auto" (geom_smooth() now orders by thex aesthetic,making it easier to pass pre-computed values without manual ordering(@izahn, #2028). Italso now knows it hasymin andymax aesthetics(#1939). The legend correctly reflects the status of theseargument when used with stats other than the default (
geom_tile() now once again interpretswidth andheight correctly (1,#2510).
position_jitter() andposition_jitterdodge() gain aseed argumentthat allows the specification of a random seed for reproduciblejittering (@krlmlr,#1996 and@slowkow,#2445).
stat_density() has better behaviour if all groupsare dropped because they are too small (#2282).
stat_summary_bin() now understands thebreaks parameter (
stat_bin() now accepts functions forbinwidth. This allows better binning when faceting alongvariables with different ranges (
stat_bin() andgeom_histogram() now sumcorrectly when using theweight aesthetic (
stat_bin() again uses correct scaling for thecomputed variablendensity (
stat_bin() andstat_bin_2d() nowproperly handle thebreaks parameter when the scales aretransformed (@has2k1,#2366).
update_geom_defaults() andupdate_stat_defaults() allow American spelling of aestheticparameters (
Theshow.legend parameter now accepts a namedlogical vector to hide/show only some aesthetics in the legend (
Layers now silently ignore unknown aesthetics with valueNULL (#1909).
Clipping to the plot panel is now configurable, through aclip argument to coordinate systems,e.g. coord_cartesian(clip = "off") (
Like scales, coordinate systems now give you a message whenyou’re replacing an existing coordinate system (#2264).
coord_polar() now draws secondary axis ticks andlabels (
coord_trans() now generates a warning when atransformation generates non-finite values (
Complete themes now always override all elements of the defaulttheme (@has2k1, #2058,#2079).
Themes now set default grid colour inpanel.gridrather than individually inpanel.grid.major andpanel.grid.minor individually. This makes it slightlyeasier to customise the theme (#2352).
Fixed bug when setting strips toelement_blank()(
Axes positioned on the top and to the right can now customizetheir ticks and lines separately (
Built-in themes gain parametersbase_line_size andbase_rect_size which control the default sizes of line andrectangle elements (
Default themes userel() to set line widths (
Themes were tweaked for visual consistency and more gracefulbehavior when changing the base font size. All absolute heights orwidths were replaced with heights or widths that are proportional to thebase font size. One relative font size was eliminated (
The height of descenders is now calculated solely on font metricsand doesn’t change with the specific letters in the string. This fixesminor alignment issues with plot titles, subtitles, and legend titles(#2288,
guide_colorbar() is more configurable: tick marksand color bar frame can now by styled with argumentsticks.colour,ticks.linewidth,frame.colour,frame.linewidth, andframe.linetype (
guide_colorbar() now useslegend.spacing.x andlegend.spacing.ycorrectly, and it can handle multi-line titles. Minor tweaks were madetoguide_legend() to make sure the two legend functionsbehave as similarly as possible (
The theme elementslegend.title andlegend.text now respect the settings ofmargin,hjust, andvjust (
Non-angle parameters oflabel.theme ortitle.theme can now be set inguide_legend()andguide_colorbar() (
fortify() gains a method for tbls (
ggplot gains a method forgrouped_dfsthat adds a.group variable, which computes a unique valuefor each group. Use it withaes(group = .group)(#2351).
ggproto() produces objects with classc("ggproto", "gg"), allowing for a more informative errormessage when adding layers, scales, or other ggproto objects (
ggsave()’s DPI argument now supports 3 stringoptions: “retina” (320 DPI), “print” (300 DPI), and “screen” (72 DPI)(ggsave() now uses full argument names to avoid partialmatch warnings (#2355), and correctly restores the previous graphicsdevice when several graphics devices are open (#2363).
print.ggplot() now returns the original ggplotobject, instead of the output fromggplot_build(). Also,the object returned fromggplot_build() now has the class"ggplot_built" (#2034).
map_data() now works even when purrr is loaded(tidyverse#66).
New functionssummarise_layout(),summarise_coord(), andsummarise_layers()summarise the layout, coordinate systems, and layers of a built ggplotobject (#2034,@wch).This provides a tested API that (e.g.) shiny can depend on.
Updated startup messages reflect new resources (#2410,
structure(NULL) for R-devel compatibility(#1968).Thanks tosubtitle andcaption arguments toggtitle() andlabs(). You can control their appearance with the themesettingsplot.caption andplot.subtitle. Themain plot title is now left-aligned to better work better with asubtitle. The caption is right-aligned (
position_stack() andposition_fill() nowsort the stacking order to match grouping order. This allows you tocontrol the order through grouping, and ensures that the default legendmatches the plot (#1552, #1593). If you want the opposite order (usefulif you have horizontal bars and horizontal legend), you can requestreverse stacking by usingposition = position_stack(reverse = TRUE) (#1837).
position_stack() andposition_fill() nowaccepts negative values which will create stacks extending below thex-axis (#1691).
position_stack() andposition_fill() gain avjust argument which makes it easy to (e.g.) display labelsin the middle of stacked bars (#1821).
geom_col() was added to complementgeom_bar() (stat="identity" by default, making theyaesthetic mandatory. It does not support any otherstat_()and does not provide fallback support for thebinwidthparameter. Examples and references in other functions were updated todemonstrategeom_col() usage.
When creating a layer, ggplot2 will warn if you use an unknownaesthetic or an unknown parameter. Compared to the previous version,this is stricter for aesthetics (previously there was no message), andless strict for parameters (previously this threw an error) (#1585).
The facet system, as well as the internal panel class, has beenrewritten in ggproto. Facets are now extendable in the same manner asgeoms and stats, as described invignette("extending-ggplot2").
We have also added the following new features.
facet_grid() andfacet_wrap() now allowexpressions in their faceting formulas (
Whenfacet_wrap() results in an uneven number ofpanels, axes will now be drawn underneath the hanging panels (fixes#1607)
Strips can now be freely positioned infacet_wrap()using thestrip.position argument (deprecatesswitch).
The relative order of panel, strip, and axis can now becontrolled with the theme settingstrip.placement thattakes eitherinside (strip between panel and axis) oroutside (strip after axis).
The theme optionpanel.margin has been deprecated infavour ofpanel.spacing to more clearly communicateintent.
Unfortunately there was a major oversight in the construction ofggproto which lead to extensions capturing the super object at packagebuild time, instead of at package run time (#1826). This problem hasbeen fixed, but requires re-installation of all extension packages.
position argument inscale_x_*andscale_y_* which can taketop andbottom, andleft andrightrespectively. The themes of top and right axes can be modified using the.top and.right modifiers toaxis.text.* andaxis.title.*.scale_x_continuous() andscale_y_continuous() can now display a secondary axis thatis aone-to-one transformation of the primary axis(e.g. degrees Celcius to degrees Fahrenheit). The secondary axis will bepositioned opposite to the primary axis and can be controlled with thesec.axis argument to the scale constructor.
Scales worry less about having breaks. If no breaks can becomputed, the plot will work instead of throwing an uninformative error(#791). This is particularly helpful when you have facets with freescales, and not all panels contain data.
Scales now warn when transformation introduces infinite values(#1696).
scale_*_datetime() now supports time zones. It willuse the timezone attached to the variable by default, but can beoverridden with thetimezone argument.
Newscale_x_time() andscale_y_time()generate reasonable default breaks and labels for hms vectors(#1752).
The treatment of missing values by discrete scales has beenthoroughly overhauled (#1584). The underlying principle is that we cannaturally represent missing values on discrete variables (by treatingjust like another level), so by default we should.
This principle applies to:
And to all scales (both position and non-position.)
Compared to the previous version of ggplot2, there are three mainchanges:
scale_x_discrete() andscale_y_discrete() always show discrete NA, regardless oftheir source
If present,NAs are shown in discretelegends.
All discrete scales gain ana.translate argumentthat allows you to control whetherNAs are translated tosomething that can be visualised, or should be left as missing. Notethat if you don’t translate (i.e.na.translate = FALSE) themissing values will passed on to the layer, which will warning that it’sdropping missing values. To suppress the warnings, you’ll also need toaddna.rm = TRUE to the layer call.
There were also a number of other smaller changes
Thetheme() constructor now has named argumentsrather than ellipses. This should make autocomplete substantially moreuseful. The documentation (including examples) has been considerablyimproved.
Built-in themes are more visually homogeneous, and matchtheme_grey better. (
When computing the height of titles, ggplot2 now includes theheight of the descenders (i.e. the bits ofg andy that hang beneath the baseline). This improves themargins around titles, particularly the y axis label (#1712). I havealso very slightly increased the inner margins of axis titles, andremoved the outer margins.
Theme element inheritance is now easier to work with asmodification now overrides defaultelement_blank elements(#1555, #1557, #1565, #1567)
Horizontal legends (i.e. legends on the top or bottom) arehorizontally aligned by default (#1842). Uselegend.box = "vertical" to switch back to the previousbehaviour.
element_line() now takes anarrowargument to specify arrows at the end of lines (#1740)
There were a number of tweaks to the theme elements that controllegends:
legend.justification now controls appearance willplotting the legend outside of the plot area. For example, you can usetheme(legend.justification = "top") to make the legendalign with the top of the plot.
panel.margin andlegend.margin havebeen renamed topanel.spacing andlegend.spacing respectively, to better communicate intent(they only affect spacing between legends and panels, not the marginsaround them)
legend.margin now controls margin around individuallegends.
Newlegend.box.background,legend.box.spacing, andlegend.box.margincontrol the background, spacing, and margin of the legend box (theregion that contains all legends).
ggplot2 now imports tibble. This ensures that all built-indatasets print compactly even if you haven’t explicitly loaded tibble ordplyr (#1677).
Class of aesthetic mapping is preserved when addingaes() objects (#1624).
+.gg now works for lists that include dataframes.
annotation_x() now works in the absense of globaldata (#1655)
geom_*(show.legend = FALSE) now works forguide_colorbar.
geom_boxplot() gains newoutlier.alpha(@jonathan-g) andoutlier.fill (
position_jitter() (and hencegeom_jitter()) now correctly computes the jitterwidth/jitter when supplied by the user (#1775,
geom_contour() more clearly describes what inputs itneeds (#1577).
geom_curve() respects thelineendparameter (#1852).
geom_histogram() andstat_bin()understand thebreaks parameter once more. (#1665). Thefloating point adjustment for histogram bins is now actually used - itwas previously inadvertently ignored (#1651).
geom_violin() no longer transforms quantile lineswith the alpha aesthetic (trim = FALSE it once again has a nice range that allows thedensity to reach zero (by extending the range 3 bandwidths to eitherside of the data) (#1700).
geom_dotplot() works better when faceting andbinning on the y-axis. (#1618,
geom_hexbin() once again supports..density.. (
geom_step() gives useful warning if only one datapoint in layer (#1645).
layer() gains newcheck.aes andcheck.param arguments. These allow geom/stat authors tooptional suppress checks for known aesthetics/parameters. Currently thisis used only ingeom_blank() which powersexpand_limits() (#1795).
Allstat_*() display a better error message whenrequired aesthetics are missing.
stat_bin() andstat_summary_hex() nowaccept length 1binwidth (#1610)
stat_density() gains new argumentn,which is passed to underlying functionstats::density(“number of equally spaced points at which the density is to beestimated”). (
stat_binhex() now again returnscountrather thanvalue (#1747)
stat_ecdf() respectspad argument(#1646).
stat_smooth() once again informs you about themethod it has chosen. It also correctly calculates the size of thelargest group within facets.
x andy scales are now symmetricregarding the list of aesthetics they accept:xmin_final,xmax_final,xlower,xmiddle andxupper are now validx aesthetics.
Scale extensions can now override themake_title andmake_sec_title methods to letthe scale modify the axis/legend titles.
The random stream is now reset after calling.onAttach() (#2409).
When mapping an aesthetic to a constant (e.g.geom_smooth(aes(colour = "loess")))), the default guidetitle is the name of the aesthetic (i.e. “colour”), not the value(i.e. “loess”) (#1431).
layer() now accepts a function as the data argument.The function will be applied to the data passed to theggplot() function and must return a data.frame (#1527,@thomasp85). Thisis a more general version of the deprecatedsubsetargument.
theme_update() now uses the+ operatorinstead of%+replace%, so that unspecified values will nolonger beNULLed out.theme_replace()preserves the old behaviour if desired (
stat_bin() has been overhauled to use the samealgorithm as ggvis, which has been considerably improved thanks to theadvice of Randy Prium (
Better arguments and a better algorithm for determining theorigin. You can now specify eitherboundary or thecenter of a bin.origin has been deprecated infavour of these arguments.
drop is deprecated in favour ofpad,which adds extra 0-count bins at either end (needed for frequencypolygons).geom_histogram() defaults topad = FALSE which considerably improves the default limitsfor the histogram, especially when the bins are big (#1477).
The default algorithm does a (somewhat) better job at pickingnice widths and origins across a wider range of input data.
bins = n now gives a histogram withnbins, notn + 1 (#1487).
All\donttest{} examples run.
Allgeom_() andstat_() functions nowhave consistent argument order: data + mapping, then geom/stat/position,then..., then specific arguments, then arguments common toall layers (#1305). This may break code if you were previously relyingon partial name matching, but in the long-term should make ggplot2easier to use. In particular, you can now set thenparameter ingeom_density2d() without it partially matchingna.rm (#1485).
For geoms with bothcolour andfill,alpha once again only affects fill (Reverts #1371, #1523).This was causing problems for people.
facet_wrap()/facet_grid() works withmultiple empty panels of data (#1445).
facet_wrap() correctly swapsnrow andncol when faceting vertically (#1417).
ggsave("x.svg") now uses svglite to produce the svg(#1432).
geom_boxplot() now understandsoutlier.color (#1455).
geom_path() knows that “solid” (not just 1)represents a solid line (#1534).
geom_ribbon() preserves missing values so theycorrectly generate a gap in the ribbon (#1549).
geom_tile() once again acceptswidthandheight parameters (#1513). It usesdraw_key_polygon() for better a legend, including acoloured outline (#1484).
layer() now automatically adds ana.rmparameter if none is explicitly supplied.
position_jitterdodge() now works on all possibledodge aesthetics, e.g. color,linetype etc.instead of only based onfill (
position = "nudge" now works (although it doesn’t doanything useful) (#1428).
The default scale for columns of class “AsIs” is now “identity”(#1518).
scale_*_discrete() has better defaults when usedwith purely continuous data (#1542).
scale_size() warns when used with categoricaldata.
scale_size(),scale_colour(), andscale_fill() gain date and date-time variants(#1526).
stat_bin_hex() andstat_bin_summary()now use the same underlying algorithm so results are consistent (#1383).stat_bin_hex() now accepts aweight aesthetic.To be consistent with related stats, the output variable fromstat_bin_hex() is now value instead of count.
stat_density() gains abw parameterwhich makes it easy to get consistent smoothing between facets (
stat-density-2d() no longer ignores theh parameter, and now acceptsbins andbinwidth parameters to control the number of contours(#1448,
stat_ecdf() does a better job of adding padding to-Inf/Inf, and gains an argumentpad to suppress the paddingif not needed (#1467).
stat_function() gains anxlim parameter(#1528). It once again works with discrete x values (#1509).
stat_summary() preserves sorted x order which avoidsartefacts when display results withgeom_smooth()(#1520).
All elements should now inherit correctly for all themes excepttheme_void(). (
theme_void() was completely void of text but facetsand legends still need labels. They are now visible (
You can once again set legend key and height width to unitarithmetic objects (like2 * unit(1, "cm"))(#1437).
Eliminate spurious warning if you have a layer with no data andno aesthetics (#1451).
Removed a superfluous comma intheme-defaults.r code(
Fixed a compatibility issue withggproto and Rversions prior to 3.1.2. (#1444)
Fixed issue wherecoord_map() fails when given anexplicitparameters argument (
Fixed issue wheregeom_errorbarh() had a requiredx aesthetic (#1933)
ggplot no longer throws an error if your plot has no layers.Instead it automatically addsgeom_blank()(#1246).
Newcut_width() is a convenient replacement for theverboseplyr::round_any(), with the additional benefit ofoffering finer control.
Newgeom_count() is a convenient alias tostat_sum(). Use it when you have overlapping points on ascatterplot.stat_sum() now defaults to using countsinstead of proportions.
Newgeom_curve() adds curved lines, with a similarspecification togeom_segment() (
Date and datetime scales now havedate_breaks,date_minor_breaks anddate_labels arguments sothat you never need to use the longscales::date_breaks()orscales::date_format().
geom_bar() now has it’s own stat, distinct fromstat_bin() which was also used bygeom_histogram().geom_bar() now usesstat_count() which counts values at each distinct value ofx (i.e. it does not bin the data first). This can be useful when youwant to show exactly which values are used in a continuousvariable.
geom_point() gains astroke aestheticwhich controls the border width of shapes 21-25 (#1133,size andstroke are additive so a point withsize = 5 andstroke = 5 will have a diameterof 10mm. (#1142)
Newposition_nudge() allows you to slightly offsetlabels (or other geoms) from their corresponding points(#1109).
scale_size() now maps values toarea, notradius. Usescale_radius() if you want the old behaviour(not recommended, except perhaps for lines).
Newstat_summary_bin() works likestat_summary() but on binned data. It’s a generalisation ofstat_bin() that can compute any aggregate, not just counts(#1274). Both default tomean_se() if no aggregationfunctions are supplied (#1386).
Layers are now much stricter about their arguments - you will getan error if you’ve supplied an argument that isn’t an aesthetic or aparameter. This is likely to cause some short-term pain but in thelong-term it will make it much easier to spot spelling mistakes andother errors (#1293).
This change does break a handful of geoms/stats that used... to pass additional arguments on to the underlyingcomputation. Nowgeom_smooth()/stat_smooth()andgeom_quantile()/stat_quantile() usemethod.args instead (#1245, #1289); andstat_summary() (#1242),stat_summary_hex(),andstat_summary2d() usefun.args.
There is now an official mechanism for defining Stats, Geoms, andPositions in other packages. Seevignette("extending-ggplot2") for details.
All Geoms, Stats and Positions are now exported, so you caninherit from them when making your own objects (#989).
ggplot2 no longer uses proto or reference classes. Instead, wenow use ggproto, a new OO system designed specifically for ggplot2.Unlike proto and RC, ggproto supports clean cross-package inheritance.Creating a new OO system isn’t usually the right way to solve a problem,but I’m pretty sure it was necessary here. Read more about it in thevignette.
aes_() replacesaes_q(). It alsosupports formulas, so the most concise SE version ofaes(carat, price) is nowaes_(~carat, ~price).You may want to use this form in packages, as it will avoid spuriousR CMD check warnings about undefined globalvariables.
geom_text() has been overhauled to make labellingyour data a little easier. It:
nudge_x andnudge_y arguments let youoffset labels from their corresponding points (#1120).
check_overlap = TRUE provides a simple way to avoidoverplotting of labels: labels that would otherwise overlap are omitted(#1039).
hjust andvjust can now be charactervectors: “left”, “center”, “right”, “bottom”, “middle”, “top”. Newoptions include “inward” and “outward” which align text towards and awayfrom the center of the plot respectively.
geom_label() works likegeom_text() butdraws a rounded rectangle underneath each label (#1039). This is usefulwhen you want to label plots that are dense with data.
The little usedaes_auto() has beendeprecated.
aes_q() has been replaced withaes_()to be consistent with SE versions of NSE functions in otherpackages.
Theorder aesthetic is officially deprecated. Itnever really worked, and was poorly documented.
Thestat andposition arguments toqplot() have been deprecated.qplot() isdesigned for quick plots - if you need to specify position or stat, useggplot() instead.
The theme settingaxis.ticks.margin has beendeprecated: now use the margin property ofaxis.text.
stat_abline(),stat_hline() andstat_vline() have been removed: these were never suitablefor use other than withgeom_abline() etc and were notdocumented.
show_guide has been renamed toshow.legend: this more accurately reflects what it does(controls appearance of layer in legend), and uses the same conventionas other ggplot2 arguments (i.e. a. between names). (Yes,I know that’s inconsistent with function names with use_,but it’s too late to change now.)
A number of geoms have been renamed to be internally consistent:
stat_binhex() andstat_bin2d() havebeen renamed tostat_bin_hex() andstat_bin_2d() (#1274).stat_summary2d() hasbeen renamed tostat_summary_2d(),geom_density2d()/stat_density2d() has beenrenamed togeom_density_2d()/stat_density_2d().
stat_spoke() is nowgeom_spoke() sinceI realised it’s a reparameterisation ofgeom_segment().
stat_bindot() has been removed because it’s sotightly coupled togeom_dotplot(). If you happened to usestat_bindot(), just change togeom_dotplot()(#1194).
All defunct functions have been removed.
The defaulttheme_grey() background colour has beenchanged from “grey90” to “grey92”: this makes the background a littleless visually prominent.
Labels and titles have been tweaked for readability:
Axes labels are darker.
Legend and axis titles are given the same visualtreatment.
The default font size dropped from 12 to 11. You might besurprised that I’ve made the default text size smaller as it was alreadyhard for many people to read. It turns out there was a bug in RStudio(fixed in 0.99.724), that shrunk the text of all grid based graphics.Once that was resolved the defaults seemed too big to my eyes.
More spacing between titles and borders.
Default margins scale with the theme font size, so the appearanceat larger font sizes should be considerably improved (#1228).
alpha now affects both fill and colour aesthetics(#1371).
element_text() gains a margins argument which allowsyou to add additional padding around text elements. To help see what’sgoing on usedebug = TRUE to display the text region andanchors.
The default font size ingeom_text() has beendecreased from 5mm (14 pts) to 3.8 mm (11 pts) to match the new defaulttheme sizes.
A diagonal line is no longer drawn on bar and rectangle legends.Instead, the border has been tweaked to be more visible, and moreclosely match the size of line drawn on the plot.
geom_pointrange() andgeom_linerange()get vertical (not horizontal) lines in the legend (#1389).
The default linesize forgeom_smooth()has been increased from 0.5 to 1 to make it easier to see when overlaidon data.
geom_bar() andgeom_rect() use aslightly paler shade of grey so they aren’t so visually heavy.
geom_boxplot() now colours outliers the same way asthe boxes.
geom_point() now uses shape 19 instead of 16. Thislooks much better on the default Linux graphics device. (It’s veryslightly smaller than the old point, but it shouldn’t affect anygraphics significantly)
Sizes in ggplot2 are measured in mm. Previously they wereconverted to pts (for use in grid) by multiplying by 72 / 25.4. However,grid uses printer’s points, not Adobe (big pts), so sizes are nowcorrectly multiplied by 72.27 / 25.4. This is unlikely to noticeablyaffect display, but it’s technically correct (https://youtu.be/hou0lU8WMgo).
The default legend will now allocate multiple rows (if vertical)or columns (if horizontal) in order to make a legend that is more likelyto fit on the screen. You can override with thenrow/ncol arguments toguide_legend()
p<-ggplot(mpg,aes(displ,hwy,colour = model))+geom_point()pp+theme(legend.position ="bottom")# Previous behaviourp+guides(colour =guide_legend(ncol =1))Newtheme_void() is completely empty. It’s usefulfor plots with non- standard coordinates or for drawings (
Newtheme_dark() has a dark background designed tomake colours pop out (
theme_minimal() became slightly more minimal byremoving the axis ticks: labels now line up directly beneath grid lines(@tomschloss,#1084)
New theme settingpanel.ontop (logical) make itpossible to place background elements (i.e., gridlines) on top of data.Best used with transparentpanel.background (
The facet labelling system was updated with many new features and amore flexible interface (
facet_wrap() gains alabeller option(#25).
facet_grid() andfacet_wrap() gain aswitch argument to display the facet titles near the axes.When switched, the labels become axes subtitles.switch canbe set to “x”, “y” or “both” (the latter only for grids) to controlwhich margin is switched.
The labellers (such aslabel_value() orlabel_both()) also get some new features:
They now offer themulti_line argument to controlwhether to display composite facets (those specified as~var1 + var2) on one or multiple lines.
Inlabel_bquote() you now refer directly to thenames of variables. With this change, you can create math expressionsthat depend on more than one variable. This math expression can bespecified either for the rows or the columns and you can also providedifferent expressions to each margin.
As a consequence of these changes, referring tox inbackquoted expressions is deprecated.
Similarly tolabel_bquote(),labeller()now take.rows and.cols arguments. Inaddition, it also takes.default.labeller()is useful to customise how particular variables are labelled. The threeadditional arguments specify how to label the variables are notspecifically mentioned, respectively for rows, columns or both. Thismakes it especially easy to set up a project-wide labeller dispatcherthat can be reused across all your plots. See the documentation for anexample.
The new labellerlabel_context() adapts to thenumber of factors facetted over. With a single factor, it displays onlythe values, just as before. But with multiple factors in a compositemargin (e.g. with~cyl + am), the labels are passed over tolabel_both(). This way the variables names are displayedwith the values to help identifying them.
On the programming side, the labeller API has been rewritten in orderto offer more control when faceting over multiple factors (e.g. withformulae such as~cyl + am). This also means that if youhave written custom labellers, you will need to update them for thisversion of ggplot.
Previously, a labeller function would takevariableandvalue arguments and return a character vector. Now,they take a data frame of character vectors and return a list. The inputdata frame has one column per factor facetted over and each column inthe returned list becomes one line in the strip label. See documentationfor more details.
The labels received by a labeller now contain metadata: theirmargin (in the “type” attribute) and whether they come from a wrap or agrid facet (in the “facet” attribute).
Note that the newas_labeller() function operatorprovides an easy way to transform an existing function to a labellerfunction. The existing function just needs to take and return acharacter vector.
Improved documentation foraes(),layer() and much much more.
I’ve tried to reduce the use of... so that you cansee all the documentation in one place rather than having to integratemultiple pages. In some cases this has involved adding additionalarguments to geoms to make it more clear what you can do:
geom_smooth() gains explicitmethod,se andformula arguments.
geom_histogram() gainsbinwidth,bins,origin andrightarguments.
geom_jitter() gainswidth andheight arguments to make it easier to control the amount ofjittering without using the lengthyposition_jitter()function (#1116)
Use ofqplot() in examples has been minimised(#1123,@hrbrmstr).This is inline with the 2nd edition of the ggplot2 box, which minimisesthe use ofqplot() in favour ofggplot().
Tightly linked geoms and stats (e.g. geom_boxplot()andstat_boxplot()) are now documented in the same file soyou can see all the arguments in one place. Variations of the same idea(e.g. geom_path(),geom_line(), andgeom_step()) are also documented together.
It’s now obvious that you can set thebinwidthparameter forstat_bin_hex(),stat_summary_hex(),stat_bin_2d(), andstat_summary_2d().
The internals of positions have been cleaned up considerably.You’re unlikely to notice any external changes, although thedocumentation should be a little less confusing since positions nowdon’t list parameters they never use.
All datasets have classtbl_df so if you also usedplyr, you get a better print method.
economics has been brought up to date to2015-04-01.
Neweconomics_long is the economics data in longform.
Newtxhousing dataset containing information aboutthe Texas housing market. Useful for examples that need multiple timeseries, and for demonstrating model+vis methods.
Newluv_colours dataset which contains the locationsof all built-incolors() in Luv space.
movies has been moved into its own package,ggplot2movies, because it was large and not terribly useful. If you’veused the movies dataset, you’ll now need to explicitly load the packagewithlibrary(ggplot2movies).
All partially matched arguments and$ have been beenreplaced with full matches (
ggplot2 now exportsalpha() from the scales package(#1107), andarrow() andunit() from grid(#1225). This means you don’t need attach scales/grid or doscales::/grid:: for these commonly usedfunctions.
aes_string() now only parses character inputs. Thisfixes bugs when using it with numbers and non defaultOutDec settings (#1045).
annotation_custom() automatically adds a unique idto each grob name, making it easier to plot multiple grobs with the samename (e.g. grobs of ggplot2 graphics) in the same plot (#1256).
borders() now accepts xlim and ylim arguments forspecifying the geographical region of interest (
coord_cartesian() applies the same expansion factorto limits as for scales. You can suppress withexpand = FALSE (#1207).
coord_trans() now works when breaks are suppressed(#1422).
cut_number() gives error message if the number ofrequested bins can be created because there are two few unique values(#1046).
Character labels infacet_grid() are no longer(incorrectly) coerced into factors. This caused problems with customlabel functions (#1070).
facet_wrap() andfacet_grid() now allowyou to use non-standard variable names by surrounding them withbackticks (#1067).
facet_wrap() more carefully checks itsnrow andncol arguments to ensure that they’respecified correctly (
facet_wrap() gains adir argument tocontrol the direction the panels are wrapped in. The default is “h” forhorizontal. Use “v” for vertical layout (#1260).
geom_abline(),geom_hline() andgeom_vline() have been rewritten to have simpler behaviourand be more consistent:
stat_abline(),stat_hline() andstat_vline() have been removed: these were never suitablefor use other than withgeom_abline() etc and were notdocumented.
geom_abline(),geom_vline() andgeom_hline() are bound tostat_identity() andposition_identity()
Intercept parameters can no longer be set to a function.
They are all documented in one file, since they are so closelyrelated.
geom_bin2d() will now let you specify onedimension’s breaks exactly, without touching the other dimension’sdefault breaks at all (#1126).
geom_crossbar() sets grouping correctly so you candisplay multiple crossbars on one plot. It also makes the defaultfatten argument a little bigger to make the middle linemore obvious (#1125).
geom_histogram() andgeom_smooth() nowonly inform you about the default values once per layer, rather thanonce per panel (#1220).
geom_pointrange() gainsfatten argumentso you can control the size of the point relative to the size of theline.
geom_segment() annotations were not transformingwith scales (
geom_smooth() is no longer so chatty. If you want toknow what the default smoothing method is, look it up in thedocumentation! (#1247)
geom_violin() now has the ability to draw quantilelines (
ggplot() now captures the parent frame to use forevaluation, rather than always defaulting to the global environment.This should make ggplot more suitable to use in more situations(e.g. with knitr)
ggsave() has been simplified a little to make iteasier to maintain. It no longer checks that you’re printing a ggplot2object (so now also works with any grid grob) (#970), and alwaysrequires a filename. Parameterdevice now supportscharacter argument to specify which supported device to use (‘pdf’,‘png’, ‘jpeg’, etc.), for when it cannot be correctly inferred from thefile extension (for example when a temporary filename is supplied serverside in shiny apps) (
guide_colorbar() creates correct legend if only onecolor (@krlmlr,#943).
guide_colorbar() no longer fails when the legend isempty - previously this often masked misspecifications elsewhere in theplot (#967).
Newlayer_data() function extracts the data used forplotting for a given layer. It’s mostly useful for testing.
User suppliedminor_breaks can now be supplied onthe same scale as the data, and will be automatically transformed withby scale (#1385).
You can now suppress the appearance of an axis/legend title (andthe space that would allocated for it) withNULL in thescale_ function. To use the default label, usewaiver() (#1145).
Position adjustments no longer warn about potentially varyingranges because the problem rarely occurs in practice and there arecurrently a lot of false positives since I don’t understand exactly whatFP criteria I should be testing.
scale_fill_grey() now uses red for missing values.This matchesscale_colour_grey() and makes it obvious wheremissing values lie. Override withna.value.
scale_*_gradient2() defaults to using Lab colourspace.
scale_*_gradientn() now allowscoloursorcolors (#1290)
scale_y_continuous() now also transforms thelower,middle andupperaesthetics used bygeom_boxplot(): this only affectsgeom_boxplot(stat = "identity") (#1020).
Legends no longer inherit aesthetics ifinherit.aesis FALSE (#1267).
lims() makes it easy to set the limits of any axis(#1138).
labels = NULL now works withguide_legend() andguide_colorbar(). (#1175,#1183).
override.aes now works with American aestheticspelling, e.g. color
Scales no longer round data points to improve performance ofcolour palettes. Instead the scales package now uses a much fastercolour interpolation algorithm (#1022).
scale_*_brewer() andscale_*_distiller() add newdirection argumentofscales::brewer_pal, making it easier to change the orderof colours (@jiho,#1139).
scale_x_date() now clips dates outside the limits inthe same way asscale_x_continuous() (#1090).
stat_bin() gainsbins arguments, whichdenotes the number of bins. Now you can setbins=100instead ofbinwidth=0.5. Note thatbreaks orbinwidth will override it (
stat_boxplot() warns if a continuous variable isused for thex aesthetic without also supplying agroup aesthetic (#992,
stat_summary_2d() andstat_bin_2d() nowshare exactly the same code for determining breaks frombins,binwidth, andorigin.
stat_summary_2d() andstat_bin_2d() nowoutput in tile/raster compatible form instead of rect compatibleform.
Automatically computed breaks do not lead to an error fortransformations like “probit” where the inverse can map to infinity(#871,
stat_function() now always evaluates the function onthe original scale. Previously it computed the function on transformedscales, giving incorrect values (
strip_dots works with anonymous functions withincalculated aesthetics(e.g. aes(sapply(..density.., function(x) mean(x))))(#1154,
theme() gainsvalidate = FALSEparameter to turn off validation, and hence store arbitrary additionaldata in the themes. (
Improved the calculation of segments needed to draw the curverepresenting a line when plotted in polar coordinates. In some cases,the last segment of a multi-segment line was not drawn (