12 ggplot extensions for snazzier R graphics

Deal Score0
Deal Score0

ggplot2 isn’t solely the R language’s hottest knowledge visualization package deal, additionally it is an ecosystem. Quite a few add-on packages give ggplot added energy to do every thing from extra simply altering axis labels to auto-generating statistical data to customizing . . . nearly something.

Listed below are a dozen nice ggplot2 extensions it is best to know — plus some extra extras on the finish.

Create your individual geoms: ggpackets

When you’ve added a number of layers and tweaks to a ggplot graph, how will you save that work so it is easy to re-use? A technique is to transform your code right into a operate. One other is to show it into an RStudio code snippet. However the ggpackets package has a ggplot-friendlier approach: Create your individual customized geom! It’s as painless as storing it in a variable utilizing the ggpacket() operate.

The instance code beneath creates a bar chart from Boston snowfall knowledge, and it has a number of strains of customizations that I’d like to make use of once more with different knowledge. The primary code block is the preliminary graph:

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

Right here’s the way to flip that right into a customized geom referred to as my_geom_col:

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

Observe that I saved every thing besides the unique graph’s first ggplot() line of code to the customized geom.

Right here’s how easy it’s to make use of that new geom:

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

Graph created with a customized ggpackets geom.

ggpackets is by Doug Kelkhoff and is accessible on CRAN.

Simpler ggplot2 code: ggblanket and others

ggplot2 is extremely highly effective and customizable, however generally that comes at a value of complexity. A number of packages intention to streamline ggplot2 so frequent knowledge visualizations are both less complicated or extra intuitive.

In the event you are inclined to overlook which geoms to make use of for what, I like to recommend giving ggblanket a strive. Considered one of my favourite issues in regards to the package deal is that it merges col and fill aesthetics right into a single col aesthetic, so I now not want to recollect whether or not to make use of a scale_fill_ or scale_colour_ operate.

One other ggblanket profit: Its geoms corresponding to gg_col() or gg_point() embrace customization choices inside the capabilities themselves as an alternative of requiring separate layers. And which means I solely want to have a look at one assist file to see issues like pal is for outlining a colour palette and y_title units the y-axis title, as an alternative of looking assist recordsdata for a number of separate capabilities. ggblanket might not make it simpler for me to keep in mind all these choices, however they’re simpler to discover.

Right here’s the way to generate a histogram from the Palmer penguins knowledge set with ggblanket, (instance taken from the package deal web site):

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

Histogram created with ggblanket.

The outcome remains to be a ggplot object, which suggests you’ll be able to proceed customizing it by including layers with standard ggplot2 code.

ggblanket is by David Hodge and is accessible on CRAN.

A number of different packages attempt to simplify ggplot2 and alter its defaults, too, together with ggcharts. Its simplified capabilities use syntax like

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

That single line of code gives a reasonably respectable default, plus mechanically sorted bars (you’ll be able to simply override that).

Bar graph with blue bars sorted by ascending values Sharon Machlis

Bar chart created with ggcharts mechanically kinds the bars by values.

See the InfoWorld ggcharts tutorial or the video beneath for extra particulars.

Easy textual content customization: ggeasy

ggeasy doesn’t have an effect on the “fundamental” a part of your dataviz—that’s, the bar/level/line sizes, colours, orders, and so forth. As an alternative, it’s all about customizing the textual content across the plots, corresponding to labels and axis formatting. All ggeasy capabilities begin with easy_ so it’s, sure, straightforward to seek out them utilizing RStudio auto-complete.

Have to middle a plot title? easy_center_title(). Need to rotate x-axis labels 90 levels? easy_rotate_labels(which = "x").

Study extra in regards to the package deal within the InfoWorld ggeasy tutorial or the video beneath.

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

Spotlight gadgets in your plots: gghighlight

Typically you need to name consideration to particular knowledge factors in a graph. You may actually try this with ggplot alone, however gghighlight goals to make it simpler. Simply add the gghighlight() operate together with a situation. For instance, if winters with complete snowfall increased than 85 inches are essential to the story I’m telling, I might use gghighlight(Complete > 85):

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

Graph with totals over 85 highlighted utilizing gghighliight.

Or if I need to name out particular years, corresponding to 2011-12 and 2014-15, I can set these as my gghighlight() situation:

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

gghighlight is by Hiroaki Yutani and is accessible on CRAN.

Add themes or colour palettes: ggthemes and others

The ggplot2 ecosystem contains a variety of packages so as to add themes and colour palettes. You doubtless gained’t want all of them, however chances are you’ll need to flick through them to seek out ones which have themes or palettes you discover compelling.

After putting in one among these packages, you’ll be able to normally use a brand new theme or colour palette in the identical approach that you simply’d use a built-in ggplot2 theme or palette. Right here’s an instance with the ggthemes package’s solarized theme and colorblind palette:

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

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

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

Different theme and palette packages to contemplate:

ggsci is a group of ggplot2 colour palettes “impressed by scientific journals, knowledge visualization libraries, science fiction films, and TV reveals” corresponding to scale_fill_lancet() and scale_color_startrek().

hrbrthemes is a well-liked theme package deal with a concentrate on typography.

ggthemr is a bit much less well-known than these others, nevertheless it has a number of themes to select from plus a GitHub repo that makes it straightforward to browse themes and see what they appear like.

bbplot has only a single theme, bbc_style(), the publication-ready fashion of the BBC, in addition to a second operate to save lots of a plot for publication, finalise_plot().

paletteer is a meta package deal, combining palettes from dozens of separate R palette packages into one with a single constant interface. And that interface contains capabilities particularly for ggplot use, with a syntax corresponding to scale_color_paletteer_d("nord::aurora"). Right here nord is the unique palette package deal title, aurora is the precise palette title, and the _d signifies that this palette is for discreet values (not steady). paletteer is usually a little overwhelming at first, however you’ll nearly actually discover a palette that appeals to you.

Observe that you should use any R colour palette with ggplot, even when it doesn’t have ggplot-specific colour scale capabilities, with ggplot’s guide scale capabilities and the colour palette values, corresponding to scale_color_manual(values=c("#486030", "#c03018", "#f0a800")).

Add colour and different styling to ggplot2 textual content: ggtext

The ggtext package deal makes use of markdown-like syntax so as to add types and colours to textual content inside a plot. For instance, underscores surrounding the textual content add italics and two asterisks across the textual content create daring styling. For this to work correctly with ggtext, the package deal’s element_markdown() operate have to be added to a ggplot theme, too. Syntax is so as to add the suitable markdown styling to the textual content and then add element_markdown() to the factor of the theme, corresponding to this for italicizing a subtitle:

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

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

Convey uncertainty: ggdist

ggdist provides geoms for visualizing knowledge distribution and uncertainty, producing graphics like rain cloud plots and logit dotplots with new geoms like stat_slab() and stat_dotsinterval(). Right here’s one instance from the ggdist web site:

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

Rain cloud plot generated with the ggdist package deal.

Take a look at the ggdist website for full particulars and extra examples. ggidst is by Matthew Kay and is accessible on CRAN.

Add interactivity to ggplot2: plotly and ggiraph

In case your plots are going on the internet, you may want them to be interactive, providing options like turning collection on and off and displaying underlying knowledge when mousing over some extent, line, or bar. Each plotly and ggiraph flip ggplots into interactive HTML widgets.

plotly, an R wrapper to the plotly.js JavaScript library, is very simple to make use of. All you do is place your last ggplot inside the package deal’s ggplotly() operate, and the operate returns an interactive model of your plot. For instance:

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

plotly works with different extensions, together with ggpackets and gghighlights. plotly  graphs don’t all the time embrace every thing that seems in a static model (as of this writing it didn’t acknowledge ggplot2 subtitles, for instance). However the package deal is difficult to beat for fast interactivity.

Observe that the plotly library additionally has a non-ggplot-related operate, plot_ly(), which makes use of a syntax just like ggplot’s qplot():

plot_ly(snowfall2000s, x = ~Winter, y = ~Complete, kind = "bar")

We will be happy to hear your thoughts

Leave a reply

Enable registration in settings - general