Get startedGet started for free

Recreating the plot

1. Recreating the plot

Now that you've cleaned, tidied, and summarized the data, you're ready to begin recreating the plot! We'll be tackling that over several steps in the exercises of this chapter using the ggplot2 techniques you've learned in this course. Before we get there, let's cover a few more tips.

2. Labs

Recall that you add a labs() layer to your plot. labs() stands for "labels" and allows you to add and modify the text around the plot, including the title and x- and y-axis labels. In the case of the 538 plot, this includes a subtitle and a caption.

3. Example graph

We'll need to make a few more modifications using a method that we haven't covered in this course. We'll use the geom_text() layer to add the numbers above each bar showing their value. Let's try out an example. Take a look at this initial plot. Here, we're graphing the mean miles per gallon of cars by the number of carburetors using the classic mtcars dataset.

4. Geom_text

To add the mean mpg above each bar, we use the geom_text() layer and assign the argument, label, within the aesthetic, to equal the mean mpg, rounded to the nearest whole number. Let's see what that looks like. Well, the numbers are there, but they're overlapping with each bar. That doesn't look very nice! They're overlapping because each number is centered around the tip of the bar, or where the number actually falls on the x-axis.

5. Moving text

To fix this issue, we can add an additional argument, y, to the aesthetics of geom_text(). Because we've used coord_flip() on this plot, the y corresponds to what is now the x-axis. We can use this argument to say where we want the text to fall on the axis. To ensure the text is always above each bar, we can set y equal to mean mpg plus a number. Let's see how that looks. Much better! We now can clearly read the numbers because they're no longer overlapping with the bar.

6. Theme

With the mean miles per gallon now above each bar, we don't need the tick labels or marks on the x-axis anymore. We can use the theme() layer to remove them. The theme() layer lets us modify the non-data elements of a plot individually. In this case, we'll want to modify two elements - the x-axis text and the x-axis ticks. To remove both of them, we can set them equal to element blank. And voila! No more text or tick marks.

7. Let's practice!

Let's put all we've learned into practice to recreate that 538 graph.