Advanced data visualization with R and ggplot2



This practical follows the previous basic introduction to ggplot2. It allows to go further with ggplot2: annotation, theme customization, color palette, output formats, scales, and more.

Get ready


The following libraries are needed all along the practical. Install them with install.packages() if you do not have them already. Then load them with library().

1- General appearance


→ Titles


Q1.1 The code below builds a basic histogram for Rbnb apartment prices on the French Riviera. It shows only value under 300 euros. Add code to:

  • add a title with ggtitle()
  • change axis labels xlab() and ylab()
  • change axis limits with xlim() and ylim()

→ Chart components

All ggplot2 chart components can be changed using the theme() function. You can see a complete list of components in the official documentation.

Note: components are changed using different functions: element_text(), element_line() for lines and so on..




Q1.2 Reproduce the previous histogram and change:

  • plot title size and color with plot.title
  • X axis title size and color with axis.title.x
  • Grid appearance with panel.grid.major

2- Annotation


Annotation is a crucial component of a good dataviz. It can turn a boring graphic into an interesting and insightful way to convey information. Dataviz is often separated in two main types: exploratory and explanatory analysis. Annotation is used for the second type.

→ Text

The most common type of annotation is text. Let’s say you have a spike in a line plot. It totally makes sense to highlight it, and explain more in details what it is about.




Q1.1 Build a line plot showing the bitcoin price evolution between 2013 and 2018. Dataset is located here and can be read directly with read.table(). What part of the chart would you highlight?




Q1.2 Use the annotate() function to add text. Annotate requires several arguments:

  • geom: type of annotation, use text
  • x: position on the X axis
  • y: position on the Y axis
  • label: what you want to write
  • Optional: color, size, angle and more.

→ Shape


Q1.3 Find the exact spike date and its value. Use this information to add a circle around the spike. This is done with the annotate() function once more:

  • geom: use point
  • x: position on the X axis
  • y: position on the Y axis
  • shape: use 21, to be able to change the fill and the color arguments. (fill=inside, color=stroke)
  • size

→ Abline


Q1.4 Add a horizontal abline to show what part of the curve is over 5000 $. This is possible thanks to the geom_hline() function that requires its yintercept argument.

→ Color


Q1.5 Build a scatterplot based on the gapminder dataset. Use gdpPercap for the X axis, lifeExp for the Y axis, and pop for bubble size. Keep only the year 2007.




Q1.6 Highlight South Africa in the chart: draw it in red, with all other circles in grey. Follow those steps:

  • create a new column with mutate: this new column has the value yes if country=="South Africa", no otherwise. This is possible thanks to the ifelse function.
  • in the aesthetics part of the ggplot call, use this new column to control dot colors
  • use scale_color_manual() to control the color of both group. Use a bright color for the country to highlight, and grey for the others.

→ Multiple text


Q1.7 Highlight every country with gdpPercap > 5000 & lifeExp < 60 in red. Write their names using the geom_text_repel of theggrepel` package to avoid text overlapping.

3- Faceting


Faceting is a very powerful data visualization technique. It splits the figure in small subsets, usually one by level of a categorical variable. ggplot2 offers 2 functions to build small multiples: facet_wrap() and facet_grid().

→ facet_wrap()


Q3.1 Build a spaghetti chart showing the evolution of 9 baby names in the US. (See code here). What’s wrong with this chart?




Q3.2 Use the facet_wrap() function to build one area chart for each name. Basically, you have to provide a categorical variable to the function. It will build a chart for each of its level.

Have a look to the Y axis. What do you observe? Is it a good option?

You should get something like this:




Q3.3 Find out how to use the scale option to have different Y axis limits for each subset. Does it make sense? In which conditions?

You should get something like this:

→ facet_grid()


Bonus Find out what the facet_grid() function does. Why is it different to facet_wrap()?




BonusLoad this dataset in R. Build a histogram for every combination of day and sex using facet_wrap()

You should get something like:

4- Saving plots





Q4.1 - Save the previous chart as a PNG file using the ggsave() function. Where is saved the file?




Q4.2 - Specify the complete path before file name to save the chart at a specific location.

5- Colors


Picking the right colors is a crucial step for a good dataviz. R offers awesome options and packages to make the right choices. Here is an overview of the main options.

→ One color


Q5.1 Several options exist to pick one color. Change the histogram color using the fill argument on the chart below using each of the following options:

  • plain color name. Type colors() to see all the options.
  • using rgb(). This function provides the quantity of red, green and blue to build the color. Plus an argument for the opacity. Example, try rgb(.7, .6, .3, .2)
  • using HTML colors. Use this website to pick one you like.

→ Discrete color palette


Q5.2 Build a scatterplot based on the iris dataset. Use Sepal.Length for the X axis, Petal.Length for the Y axis. Use color=Species to color groups.




Q5.3 It is possible to set the color scale manually using scale_color_manual(). Use the hint below to see how to use it and apply it to the previous scatterplot.

Note: it is a bad practice to pick colors randomly. Your palette will be ugly and will probably not be colorblind friendly.




Q5.4 Fortunately, people already tackeled this issue for us and created packages offering nice color palettes. The most famous one is RColorBrewer. Palettes are already available in ggplot2. See all of them here, and use one on your chart using scale_color_brewer().

Pick the one you like the most and apply it to to previous scatterplot. Use it to color the Species.

→ Continuous color palette


Q5.5 RColorBrewer also offers continuous color palette. However they must be called through the scale_color_distiller function. Use the palette you like the most to color circles depending on Sepal_length.

6- Interactive charts


An interactive chart is a chart on which you can zoom, hover shapes to get tooltips, click to trigger actions and more. Building interactive charts requires javascript under the hood, but it is relatively easy to build it using R packages that wrap the javascript for you. This type of packages are called HTML widgets.

→ Plotly


Q6.1 Build the gapminder bubble plot you’ve already done in the annotation part of this practical. Store it in an object called p




Q6.2 Install and load the plotly package. Build an interactive chart using the ggplotly() function. What are the new functionalities of this chart? Is it useful? What could be better?




Q6.3 Let’s improve the tooltip of the chart:

  • build a new column called myText. Fill it with whatever you want to show in the tooltip.
  • add a new aesthetics: text=myText
  • in the ggplotly() call, add tooltip="text"

→ Leaflet


Q6.4 Use the HTML widget called leaflet to build an interactive map showing the earthquakes described in the dataset called quakes. Code is fully provided here, since cartography with R could deserve an entire practical. The idea is just to discover to potential offered in a few lines of code:

→ Heatmap

The d3heatmap package allows to build interactive heatmaps in a few line of code. Let’s see how it works




Q6.5 Load this dataset in R. Have a look to the first rows. Describe it. (source)




Q6.6 R offers a heatmap() function to build… heatmaps! Apply it to the dataset. What do you observe? Are you happy with this heatmap? What’s wrong with it? How can we solve the issue?

Note: input dataset must be at the matrix format to be accepted by the function. Use as.matrix() to get this format.




Q6.7 Check the scale option of the heatmap() function. What is it for? Can it help us? How? Use it to improve the heatmap.




Q6.8 d3heatmap() uses exactly the same syntax than heatmap(). Use the function to get an interactive version of the previous heatmap!

→ Time Seriesx


Q6.9 - Use the HTML widget called dygraphs to build an interactive line plot of the bitcoin price evolution. Try to reproduce the example below.

→ HTML widgets


BONUS - The packages showcased above are just a sample of the possibilities offered by the html widgets. Visit this website to have an overview of what kind of interactive chart you can do with R. Pick your favorite example and try to reproduce it.

7- Scales


Scales control the details of how data values are translated to visual properties. Many different scales are offered by ggplot2. The most widely one is probably the log scale.




Q7.1 Build a histogram showing the night price distribution of the french riviera apartements (data here). Keep all the data, with extreme values.




Q7.2 A common practice to avoid the effect of extreme values is to filter data, or use xlim to zoom on a part of the axis. Another approach is to use scale_x_log10() to apply a log transformation. Apply this function to the histogram.




Q7.3 What’s the difference between scale_x_log10() and applying the log() function on the dataset before doing the chart? Why is it better?

 




A work by a practical by Yan Holtz