ggplot2 is an R library for creating graphics, based on the The Grammar of Graphics. It has been created by Hadley Wickham and is part of the tidyverse revolution. It can greatly improve the quality and
aesthetics of your graphics, and will make you much more efficient in creating them. ggplot2 allows you to build almost any type of graphic. The R graph gallery focus on its utilisation, so almost every
Customization with theme()
With ggplot2, the appearance of the plot is controlled using the theme function. It allows you to control each of the elements of a graph: axis, background, legend, strip. Note that several built-in themes are available as well.
Marginal plots are not natively supported by ggplot2, but their realisation is straightforward thanks to the ggExtra library as illustrated in graph #277.
Once you’ve realised your graphic, you probably want to annotate it to highlight a specific part of it. The graph #233 will teach you how to add lines, text, rectangles, arrows, and more.
There are several ways to split your graphic window in several part with ggplot2. If the split is made following the value of a specific variable, you should use the facet_wrap or facet_grid functions as proposed below in graph #233:
However, if you want to arrange several graphics that are completely different in the same window, you will have to use the gridExtra library as follow:
When working with discrete variables (also called factors), a common struggle is to manage the orders of entities on the plot. The post #267 is dedicated to reordering, and here are a couple of examples showing of to deal with it.
From ggplot to interactivity.
Another awesome feature of ggplot2 is its link with the plotly library. If you know how to make a ggplot2 graphic, you are 10 seconds close to rendering an interactive version! Just call the ggplotly function, and you’re done. Visit the interactive graphic section of the gallery for more.
p <- gapminder %>%
ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) +
Hover, select a zone, click the legend, export…
Ggplot2 for maps
Ggplot2 is also a very good choice for maps. It provides specific functions to draw geographical shapes. It will allow you to plot any type of map (chloropleth, bubble, connection, hexbin or cartogram.)
If something is not doable with ggplot2… There is an extension to do it! Visit this dedicated webpage to see all of them. Here is an overview of the main ones.
A selection of ggplot2 graphics
Ggplot is skilled to realise any type of graphic. Here is a curated selection from the gallery. If you are looking for a specific type of chart, go to the welcome page of the gallery, and select the chart section that interests you; they all give the ggplot2 way to make it!
Looking for somethig else ? Try a search !