Movatterモバイル変換


[0]ホーム

URL:


ggstackplot

2025-01-31

# load the packagelibrary(ggstackplot)

This vignette explores the various features of the ggstackplotpackage.

Main Arguments

x andy arguments

Vertical stack

Select variables to make a stack. The selection order translates tothe order with which the plots are stacked. Any valid tidyselectselection and/or renaming are supported.

# select any number of variables to make the stackmtcars|>ggstackplot(x = mpg,y =c(wt, qsec, drat)  )

# the selection order translates into stack ordermtcars|>ggstackplot(x = mpg,y =c(drat, wt, qsec)  )

# use any valid tidyselect selection syntaxmtcars|>ggstackplot(x = mpg,y =c(4,"carb",starts_with("d"))  )

# use any valid tidyselect renaming syntax to rename stack panelsmtcars|>ggstackplot(x =c(`mpg [units]`= mpg),y =c(`weight [tons]`= wt,`speed`= qsec, drat)  )

Horizontal stack

Select multiple x variables to stack:

# all examples shown in this document work the same way for a horizontal# stack, simply switch out the x and y assignmentsmtcars|>ggstackplot(y = mpg,x =c(wt, qsec, drat)  )

palette argument

Set individual plot colors by providing an RColorBrewer palette.Color definition applies to the color and fill aesthetics as well as theactual axis colors.

# use the Set1 RColorBrewer palettemtcars|>ggstackplot(x = mpg,y =c(wt, qsec),palette ="Set1"  )

# likewise for the horizontal stack versionmtcars|>ggstackplot(y = mpg,x =c(wt, qsec),palette ="Set1"  )

color argument

Alternatively, set colors manually by supplying a character vector ofcolors:

# select any specific colors for each plotmtcars|>ggstackplot(x = mpg,y =c(wt, qsec),color =c("#E41A1C","#377EB8")  )

remove_na argument

This removes NA values so that lines are not interrupted. Whenremove_na is set toFALSE, breaks in lines mayappear due to NA values.

library(dplyr)# default (NAs are removed so lines are not interrupted)mtcars|>add_row(mpg =22,wt =5,qsec =NA)|>ggstackplot(x = mpg,y =c(wt, qsec),color =c("#E41A1C","#377EB8")  )

# explicit `remove_na` = FALSEmtcars|>add_row(mpg =22,wt =5,qsec =NA)|>ggstackplot(x = mpg,y =c(wt, qsec),color =c("#E41A1C","#377EB8"),remove_na =FALSE  )

both_axes argument

Whenboth_axes = TRUE , the stacked variable axes areduplicated on both sides of each stacked plot.

# Vertical stackplotmtcars|>ggstackplot(x = mpg,y =c(wt, qsec),color =c("#E41A1C","#377EB8"),both_axes =TRUE  )

# Horizontal stackplotmtcars|>ggstackplot(y = mpg,x =c(wt, qsec),color =c("#E41A1C","#377EB8"),both_axes =TRUE  )

alternate_axes argument

Whenalternate_axes = FALSE , the axes for the multiplevariables are kept on the same side of the facets. The default behavioralternates these axes left/right or top/bottom.

# axes do not alternate:mtcars|>ggstackplot(x = mpg,y =c(wt, qsec),color =c("#E41A1C","#377EB8"),alternate_axes =FALSE  )

# Horizontal versionmtcars|>ggstackplot(y = mpg,x =c(wt, qsec),color =c("#E41A1C","#377EB8"),alternate_axes =FALSE  )

switch_axes argument

Determines whether to switch the stacked axes. Not switching meansthat for vertical stacks the plot at the bottom has the y-axis always onthe left side; and for horizontal stacks that the plot on the left hasthe x-axis on top. Settingswitch_axes = TRUE}, leads tothe opposite. Ifalternate_axes = TRUE this essentiallyswitches the order with which the axes alternate (e.g., right/left/rightvs. left/right/left). Note that ifboth_axes = TRUE,neither theswitch_axes noralternate_axesparameter has any effect.

# stacked axis starts on the rightmtcars|>ggstackplot(x = mpg,y =c(wt, qsec),color =c("#E41A1C","#377EB8"),switch_axes =TRUE  )

# or for the horizontal version, stacked axis# starts on the bottommtcars|>ggstackplot(y = mpg,x =c(wt, qsec),color =c("#E41A1C","#377EB8"),switch_axes =TRUE  )

# and in combination with alternate_axes = FALSE# all axes on the rightmtcars|>ggstackplot(x = mpg,y =c(wt, qsec),color =c("#E41A1C","#377EB8"),alternate_axes =FALSE,switch_axes =TRUE  )

# or all axes on the topmtcars|>ggstackplot(y = mpg,x =c(wt, qsec),color =c("#E41A1C","#377EB8"),alternate_axes =FALSE,switch_axes =TRUE  )

overlap argument

Overlap determines the grid overlap between the multiple stackedplots.1 corresponds to fully overlapping (similar tohaving a ggplotsec_axis enabled) while0 doesnot overlap at all.

# define any overlap between 0 and 1mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),overlap =0.3  )

# full overlapmtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),overlap =1  )

Different overlaps

Multiple overlap arguments can be supplied with a numeric vector ofnumbers between 0 and 1, where each element in the vector corresponds tothe overlap between then andn+1th overlap value. Forexample, for a plot with four stacked panels:qsec,drat,wt,hp, a vector ofoverlap = c(1, 0, 1) indicates that between the first 2elements (qsec anddrat) there is fulloverlap. Betweendrat andwt there is nooverlap (0). Betweenwt andhpthere is full overlap.

# different overlap between stack panelsmtcars|>ggstackplot(x = mpg,y =c(qsec, drat, wt, hp),color =c("#E41A1C","#377EB8","#4DAF4A","#984EA3"),overlap =c(1,0,1)  )

# and the horizontal versionmtcars|>ggstackplot(y = mpg,x =c(qsec, drat, wt, hp),color =c("#E41A1C","#377EB8","#4DAF4A","#984EA3"),overlap =c(1,0,1)  )

shared_axis_size argument

The size of the shared axis determines the size of any shared axesrelative to the grid size of the original ggplot. The size of the sharedaxis often needs to be adjusted depending on which aspect ratio isintended. It is defined as fraction of a full panel, between 0 and1.

mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),overlap =1,# can be only 10% of a plot size as we're overlapping plotsshared_axis_size =1  )

simplify_shared_axis argument

Sometimes it’s better just to keep the shared axis on each panel.This produces something akin to afacet_wrap() orcowplot::plot_grid().

mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),simplify_shared_axis =FALSE  )

# also goes well with changing `both_axes`, `switch_axes` and/or `alternate_axes`mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),simplify_shared_axis =FALSE,alternate_axes =FALSE  )

Thetemplate argument

This is the most important argument. It defines which ggplot to useas the template for all plots in the stack. This can be an actual plot(just the data will be replaced) or a ggplot that doesn’t have dataassociated yet. The possibilities are pretty much endless. Just makesure to always add thetheme_stacked_plot() base theme (youcan modify it more from there on). A few examples below:

Theme modifications

Add any modification to the overlying theme as you see fit.

Here,template allows the user to define that aggplot() will serve as the base, withgeom_line as the primary geom. Then,theme_stackplot() is applied and customtheme() options are set.

library(ggplot2)# increase y axis text sizemtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),template =ggplot()+geom_line()+theme_stackplot()+theme(axis.title.y =element_text(size =20),axis.text.y =element_text(size =16)      )  )

# increase the panel marginsmtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),template =ggplot()+geom_line()+theme_stackplot()+theme(# increase left margin to 20% and top/bottom margins to 10%plot.margin =margin(l =0.2,t =0.1,b =0.1,unit ="npc")      )  )

Grid modifications

Modifying thepanel.grid argument can create gridlinesfor both the stacked variable axes and the shared axis. This can get abit cluttered in a plot whereoverlap = 1.

mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),overlap =1,template =ggplot()+geom_line(data =function(df)filter(df, .yvar=="qsec"))+geom_point(data =function(df)filter(df, .yvar=="drat"))+theme_stackplot()+theme(panel.grid.major =element_line(color ="lightgray",linewidth =0.8)      )  )

But, this can look reasonable if there is no overlap of the stackedplats, and/or if the lines are made inconspicuous:

mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),overlap =0,template =ggplot()+geom_line(data =function(df)filter(df, .yvar=="qsec"))+geom_point(data =function(df)filter(df, .yvar=="drat"))+theme_stackplot()+theme(panel.grid.major =element_line(color ="lightgray",linetype ="dotted",linewidth =0.5)      )  )

Other themes

You aren’t bound to our theme’s aesthetic choices :), you can alwaysadd another theme or theme modifications on top oftheme_stackplot()! Here we add the classictheme_bw() to get those nice clean gridlines back, as wellas a panel border.

mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),overlap =0,template =ggplot()+geom_line(data =function(df)filter(df, .yvar=="qsec"))+geom_point(data =function(df)filter(df, .yvar=="drat"))+theme_stackplot()+theme_bw()# give us that good theme!  )

Custom geom data

It is possible to use different geoms for different stacked panels.Here, we use both lines and points. These geoms are defined in thetemplate argument.

# use different geoms for different panels# you can refer to y-stack panel variables with `.yvar` and x-stack panel variables with `.xvar`mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),overlap =1,template =ggplot()+geom_line(data =function(df)filter(df, .yvar=="qsec"))+geom_point(data =function(df)filter(df, .yvar=="drat"))+theme_stackplot()  )

Different plot elements

One can also change the geoms in the default theme. Here we usegeom_path() instead ofgeom_line() in ahorizontal stack. This is a very common use case becausegeom_line() connects the data points by increasing x-axiswhich is not always what we want (for example in oceanographic depthplots where we want to connect the data points by increasing y-axisvalue).

# horizontal stack with default (geom_line())mtcars|>ggstackplot(y = mpg,x =c(qsec, drat),color =c("#E41A1C","#377EB8"),template =ggplot()+geom_point()+geom_line()+# default in templatetheme_stackplot()  )

# the following is the exact same data but using a# horizontal stack with "depth-profile" like geom_path()mtcars|># arrange data by the y-axisarrange(mpg)|>ggstackplot(y = mpg,x =c(qsec, drat),color =c("#E41A1C","#377EB8"),template =ggplot()+geom_point()+geom_path()+# plots data in ordertheme_stackplot()  )

Additional plot elements

One can also add additional plot elements just as with a normalggplot. Here we add a vertical line that is shared across all stackedplots:

mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),overlap =0.2,template =ggplot()+geom_vline(xintercept =20,linewidth =4,color ="gray80")+geom_line()+theme_stackplot()  )

Axis modifications

Sometimes secondary axes will still be desired, especially if thataxis is a transformation of an existing one. For example, here, wecreate a square root mpg axis that is plotted against the mpg axis. Allthis can also be defined in thetemplate argument by addingascale_x_continuous argument, just as you would in anormal ggplot.

# add a secondary x axismtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),both_axes =TRUE,overlap =0.1,template =ggplot()+geom_line()+scale_x_continuous(# change axis namename ="this is my mpg axis",# this can be the same with dup_axis() or as here have a transformed axissec.axis =sec_axis(transform = sqrt,name =expression(sqrt(mpg)),breaks = scales::pretty_breaks(5)        )      )+theme_stackplot()  )

Similarly, transformation axes can be introduced such as e.g. a logaxis.

mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),both_axes =TRUE,overlap =0.1,template =ggplot()+geom_line()+scale_x_log10("this is my log10 mpg axis")+theme_stackplot()  )

Additional aesthetics

Aesthetics are also defined in thetemplate argument.Remember, the only parameters that are defined in the stackplot are (i)the shared axis (in this case,mpg ), (ii) the axes to bestacked, in this casey = c(wt, qsec, drat), (iii) anyggstackplot-specific arguments. All ggplot arguments and aesthetics areassigned in thetemplate argument.

# add aesthetics to the plotmtcars|>ggstackplot(x = mpg,y =c(wt, qsec, drat),alternate_axes =FALSE,template =ggplot()+aes(color =factor(cyl),linetype =factor(cyl),shape =factor(cyl))+geom_line()+geom_point(size =3)+theme_stackplot()  )

Theadd argument

For even more specific plot refinements, theaddargument provides an easy way to add ggplot components tospecific panels in the stack plot. A few examplesbelow:

Custom geoms

Similar to the examplecustom geom data theadd argument can also be used to add specific geomsonly to specific panels.

This takes the form of alist() where each item in thelist is of the form:panel_name = panel_addition wherepanel_name is the panel-specific variable andpanel_addition is the item toadd(+) to that panel.add also allows the user tomake additions by index (e.g., first panel, second panel, third panel,etc.).

Here, we add ageom_line to theqsec paneland ageom_rect rectangle to thedrat panel bydefining these panels in thelist().

mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),template =ggplot()+theme_stackplot(),# add:add =list(# panel by nameqsec =geom_line(),drat =geom_rect(xmin =20,xmax =25,ymin =3.2,ymax =4.2,fill ="gray90")+geom_point()    )  )

Custom themes

Similarly, custom theme options can be added to specific panels.Here, weadd by panel index:

mtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),# define ggplot template optionstemplate =ggplot()+geom_line()+theme_stackplot(),# define panel-specific additionsadd =list(# panel by index# first panel:geom_point()+theme(axis.title.y =element_text(size =30)),# second panel:theme(panel.grid.major.y =element_line(color ="lightgray",size =0.2))    )  )

Custom axes

Theadd argument also allows the definition of customaxes. This is particularly useful if applying functions from thescales package.

# particularly useful is also the possibility to modify individual scalesmtcars|>ggstackplot(x = mpg,y =c(qsec, drat),color =c("#E41A1C","#377EB8"),template =ggplot()+geom_line()+theme_stackplot(),add =list(# modify the axis for the second plotdrat =scale_y_continuous("$$ drat",labels = scales::label_dollar())+expand_limits(y =0)+theme(axis.title.y =element_text(size =30))    )  )

Legend positioning

Another example of theme modification is the use of the `add`argument to specify legend positioning.

mtcars|>ggstackplot(x = mpg,y =c(wt, qsec, drat),color =c("#E41A1C","#377EB8","#4DAF4A"),template =ggplot()+aes(linetype =factor(vs))+geom_line()+theme_stackplot(),# switch legend position for middle plotadd =list(qsec =theme(legend.position ="left"))  )

mtcars|>ggstackplot(x = mpg,y =c(wt, qsec, drat),color =c("#E41A1C","#377EB8","#4DAF4A"),template =ggplot()+aes(linetype =factor(vs))+geom_line()+theme_stackplot()+# remove the legends, then...theme(legend.position ="none"),# ... re-include the middle panel legend on the plot# with some additional stylingadd =list(qsec =theme(# define legend relative position in x,y:legend.position =c(0.2,0.9),# other legend stylistic changes:legend.title =element_text(size =20),legend.text =element_text(size =16),legend.background =element_rect(color ="black",fill ="gray90",linewidth =0.5),legend.key =element_blank(),legend.direction ="horizontal"        )+labs(linetype ="VS")    )  )

Putting it all together

# example from the README with economics data bundled with ggplot2ggplot2::economics|>ggstackplot(# define shared x axisx = date,# define the stacked y axesy =c(pce, pop, psavert, unemploy),# pick the RColorBrewer Dark2 palette (good color contrast)palette ="Dark2",# overlay the pce & pop plots (1), then make a full break (0) to the once# again overlaye psavert & unemploy plots (1)overlap =c(1,0,1),# switch axes so unemploy and psavert are on the side where they are# highest, respectively - not doing this here by changing the order of y# because we want pop and unemploy on the same sideswitch_axes =TRUE,# make shared axis space a bit smallershared_axis_size =0.15,# provide a base plot with shared graphics eelements among all plotstemplate =# it's a ggplotggplot()+# use a line plot for allgeom_line()+# we want the default stackplot themetheme_stackplot()+# add custom theme modifications, such as text sizetheme(text =element_text(size =14))+# make the shared axis a date axisscale_x_date("year")+# include y=0 for all plots to contextualize data betterexpand_limits(y =0),# add plot specific elementsadd =list(pce =# show pce in trillions of dollarsscale_y_continuous("personal consumption expenditures",# always keep the secondary axis duplicated so ggstackplot can# manage axis placement for yousec.axis =dup_axis(),# labeling function for the dollar unitslabels =function(x)sprintf("$%.1f T", x/1000),          ),pop =# show population in millionsscale_y_continuous("population",sec.axis =dup_axis(),labels =function(x)sprintf("%.0f M", x/1000)          ),psavert =# savings is in %scale_y_continuous("personal savings rate",sec.axis =dup_axis(),labels =function(x)paste0(x,"%"),          )+# show data points in addition to linegeom_point(),unemploy =# unemploy in millionsscale_y_continuous("unemployed persons",sec.axis =dup_axis(),labels =function(x)sprintf("%.0f M", x/1000)          )+# show data points in addition to linegeom_point()      )  )

Advanced

Instead of callingggstackplot() to make a plot, you canalso useprepare_stackplot() andassemble_stackplot() to separate the two main steps ofmaking a ggstackplot.prepare_stackplot() provides a tibblewith all the plot components that can be modified directly in the tibbleif so desired before assembling the plot withassemble_stackplot(). Usuallyt this is not necessarybecause the combination of thetemplate andadd parameters inggstackplot() provides thesame kind of flexibility as modifying plot elements in the plottibble.

# prep plotplot_prep<-  mtcars|>prepare_stackplot(x = mpg,y =c(wt, qsec),palette ="Set1"  )# show plot tibbleplot_prep#> # A tibble: 2 × 6#>   .var  config           data               plot   theme   add#>   <chr> <list>           <list>             <list> <list>  <list>#> 1 wt    <tibble [1 × 9]> <tibble [32 × 11]> <gg>   <theme> <NULL>#> 2 qsec  <tibble [1 × 9]> <tibble [32 × 11]> <gg>   <theme> <NULL># modify plot tibbleplot_prep$plot[[2]]<-ggplot(mtcars)+aes(mpg, drat)+geom_point()plot_prep$theme[[2]]<-theme_bw()# assemble stackplotplot_prep|>assemble_stackplot()


[8]ページ先頭

©2009-2025 Movatter.jp