12 ggplot extensions for more elegant R graphics

ggplot2 is not only the most popular R language data visualization package, it is also an ecosystem. Many add-on packages give ggplot extra power to do everything from easier change of axis labels to automatic generation of statistical information to customization of . . . almost all.

Here are a dozen ggplot2 extensions you should know about.

Create your own geoms: ggpackets

Once you’ve added multiple layers and adjustments to a ggplot plot, how can you save that work so it’s easy to reuse? One way is to convert your code into a function. Another is to turn it into an RStudio code snippet. But the ggpackets package has a more ggplot-friendly way: create your own custom geom! It’s as painless as storing it in a variable using the ggpacket() function.

The sample code below creates a bar chart from Boston snowfall data, and it has several rows of customizations that I’d like to reuse with other data. The first block of code is the initial graph:

snowfall2000s <- import("https://gist.githubusercontent.com/smach/5544e1818a76a2cf95826b78a80fc7d5/raw/8fd7cfd8fa7b23cba5c13520f5f06580f4d9241c/boston_snowfall.2000s.csv")
ggplot(snowfall2000s, aes(x = Winter, y = Total)) +
  geom_col(color = "black", fill="#0072B2") +
  theme_minimal() +
  theme(panel.border = element_blank(), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.line =
          element_line(colour = "gray"),
        plot.title = element_text(hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5)
  ) +
  ylab("") + xlab("")

Here’s how to turn that into a custom geom called my_geom_col:

my_geom_col <- ggpacket() +
  geom_col(color = "black", fill="#0072B2") +
  theme_minimal() +
  theme(panel.border = element_blank(), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.line =
          element_line(colour = "gray"),
        plot.title = element_text(hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5)
  ) +
  ylab("") + xlab("")

Note that I saved everything except the first original graphic ggplot() line of code to custom geom.

Here’s how easy it is to use this new geom:

ggplot(snowfall2000s, aes(x = Winter, y = Total)) +
bar chart with blue bars Sharon Machlis

Chart created with a custom ggpackets geom.

ggpackets is by Doug Kelkhoff and is available on CRAN.

Simpler ggplot2 code: ggblanket and others

ggplot2 is incredibly powerful and customizable, but sometimes it comes at a cost of complexity. Several packages aim to streamline ggplot2 so that common data visualizations are simpler or more intuitive.

If you tend to forget which geoms to use for what, I recommend giving ggblanket a try. One of my favorite things about the wrap is that it merges the col and fill aesthetic into one col aesthetic, so I no longer have to remember whether to use a scale_fill_ Where scale_colour_ function.

Another advantage of ggblanket: its surveyors such as gg_col() Where gg_point() include customization options in the functions themselves instead of requiring separate layers. And that means I only need to look at a help file to see things like pal is used to define a color palette and y_title sets the y-axis title, instead of searching help files for several separate functions. ggblanket may not make it easy for me remember all of these options, but they are easier to to find.

Here’s how to generate a histogram from the Palmer penguin dataset with ggblanket (example taken from the package website):

penguins |>
  gg_histogram(x = body_mass_g, col = species)
Histogram with 3 colors and a legend Sharon Machlis

Histogram created with ggblankets.

The result is still a ggplot object, which means you can further customize it by adding layers with conventional ggplot2 code.

ggblankets is by David Hodge and is available on CRAN.

Several other packages attempt to simplify ggplot2 and also change its defaults, including ggcharts. Its simplified functions use a syntax like

column_chart(snowfall2000s, x = Winter, y = Total)

This single line of code provides a pretty decent default value, as well as auto-sorted bars (you can easily override that).

Bar chart with blue bars sorted by increasing values Sharon Machlis

The bar chart created with ggcharts automatically sorts the bars by values.

See the InfoWorld ggcharts tutorial or the video below for more details.

Simple text customization: ggeasy

ggeasy does not affect the “main” part of your dataviz, i.e. bar/point/line sizes, colors, orders, etc. Instead, it’s about customizing text around plots, like labels and axis formatting. All ggeasy functions start with easy_ so it is, yes, easy to find them using RStudio’s autocomplete.

Need to center a plot title? easy_center_title(). Want to rotate the x-axis labels 90 degrees? easy_rotate_labels(which = "x").

Learn more about the package in the InfoWorld ggeasy tutorial or the video below.

ggeasy is by Jonathan Carroll and others and is available on CRAN.

Highlight elements of your plots: gghighlight

Sometimes you want to draw attention to specific data points in a chart. You can certainly do this with ggplot alone, but gghighlight aims to make it easier. Just add the gghighlight() function with a condition. For example, if winters with total snowfall greater than 85 inches are important to the story I’m telling, I might use gghighlight(Total > 85):

ggplot(snowfall2000s, aes(x = Winter, y = Total)) +
  my_geom_col() +
  gghighlight(Total > 85)
Bar chart with 2 blue bars highlighted and the rest in grey. Sharon Machlis

Chart with totals greater than 85 highlighted using gghighlight.

Or if I want to call specific years, such as 2011-12 and 2014-15, I can set them as my gghighlight() condition:

ggplot(snowfall2000s, aes(x = Winter, y = Total)) +
  my_geom_col() +
  gghighlight(Winter %in% c('2011-12', '2014-15'))

gghighlight is by Hiroaki Yutani and is available on CRAN.

Add themes or color palettes: ggthemes and others

The ggplot2 ecosystem includes a number of packages for adding themes and colormaps. You probably won’t need all of them, but you might want to browse through them to find ones with themes or palettes that you find compelling.

After installing one of these packages, you can usually use a new theme or color palette the same way you would use a built-in ggplot2 theme or palette. Here is an example with the solarized theme and the colorblind palette from the ggthemes package:

ggplot(penguins, aes(x = bill_length_mm, y = body_mass_g, color = species)) +
  geom_point() +
  ggthemes::theme_solarized() +
Scatter plot with pale yellow background Sharon Machlis

Scatter plot using a colorblind palette and a solarized theme from the ggthemes package.

ggthemes is by Jeffrey B. Arnold and others and is available on CRAN.

Other theme and palette packages to consider:

ggsci is a collection of ggplot2 colormaps “inspired by scientific journals, data visualization libraries, science fiction movies and TV shows” such as scale_fill_lancet() and scale_color_startrek().

hrbrthemes is a popular theme package focused on typography.

ggthemr is a little less well known than the others, but it offers plenty of themes, as well as a GitHub repository that makes it easy to navigate through themes and how they look.

bbplot has only one theme, bbc_style()the BBC’s ready-to-publish style, plus a second function to save a plot for publication, finalise_plot().

paletteer is a meta-package, combining palettes from dozens of separate R palette packages into one with a single consistent interface. And this interface includes functions specifically for using ggplot, with syntax like scale_color_paletteer_d("nord::aurora"). here nord is the original bundle of pallets Last name, aurora is the specific palette name, and the _d means that this palette is for discrete (not continuous) values. palette can be a bit overwhelming at first, but you’re almost certain to find a palette you like.

Note that you can use any R colormap with ggplot, although it doesn’t have ggplot-specific colorscale functions, with ggplot’s manual scale functions and colormap values, such as scale_color_manual(values=c("#486030", "#c03018", "#f0a800")).

Add color and other styles to ggplot2 text: ggtext

The ggtext package uses markdown-like syntax to add styles and colors to text in a plot. For example, underscores around text add italics, and two asterisks around text create a bold style. For this to work correctly with ggtext, the package element_markdown() The function must also be added to a ggplot theme. The syntax is to add the appropriate markdown style to the text and then add element_markdown() to theme elementlike this to italicize a subtitle:

ggplot(snowfall2000s, aes(x = Winter, y = Total)) +
  my_geom_col() +
  labs(title = "Annual Boston Snowfall", subtitle = "_2000 to 2016_") +
    plot.subtitle = element_markdown()

ggtext is by Claus O. Wilke and is available on CRAN.

Convey uncertainty: ggdist

ggdist adds geoms to visualize data distribution and uncertainty, generating plots like rain cloud plots and logit dotplots with new geoms like stat_slab() and stat_dotsinterval(). Here is an example from the ggdist website:

set.seed(12345) # for reproducibility
  abc = c("a", "b", "b", "c"),
  value = rnorm(200, c(1, 8, 8, 3), c(1, 1.5, 1.5, 1))
) %>%
  ggplot(aes(y = abc, x = value, fill = abc)) +
  stat_slab(aes(thickness = stat(pdf*n)), scale = 0.7) +
  stat_dotsinterval(side = "bottom", scale = 0.7, slab_size = NA) +
  scale_fill_brewer(palette = "Set2")
Three rain cloud plots, each a different color Sharon Machlis

Rain cloud plot generated with the ggdist package.

See the ggdist website for more details and more examples. ggidst is by Matthew Kay and is available on CRAN.

Add interactivity to ggplot2: plotly and ggiraph

If your plots are served on the web, you may want them to be interactive, offering features such as turning series on and off and displaying underlying data when you hover over a point. , a line or a bar. plotly and ggiraph turn ggplots into interactive HTML widgets.

plotly, an R wrapper of the plotly.js JavaScript library, is extremely easy to use. All you do is put your final ggplot in the package ggplotly() function, and the function returns an interactive version of your plot. For instance:

ggplot(snowfall2000s, aes(x = Winter, y = Total)) +
  geom_col() +
  labs(title = "Annual Boston Snowfall", subtitle = "2000 to 2016")

works with other extensions including ggpackets and gghighlights. plotly plots don’t always include everything that appears in a static version (at the time of this writing, it doesn’t recognize ggplot2 subtitles, for example). But the package is hard to beat for fast interactivity.

Note that the plotly library also has a function unrelated to ggplot, plot_ly()which uses a syntax similar to that of ggplot qplot():

plot_ly(snowfall2000s, x = ~Winter, y = ~Total, type = "bar")