Map the appropriate variable to the fill aesthetic.
We’ll use the
uspopchange data set for this example. It contains the percentage change in population for the US states from 2000 to 2010. We’ll take the top 10 fastest-growing states and graph their percentage change. We’ll also color the bars by region (Northeast, South, North Central, or West).
First, take the top 10 states:
library(gcookbook) # Load gcookbook for the uspopchange data set library(dplyr) uspopchange %>% upc <- arrange(desc(Change)) %>% slice(1:10) upc#> State Abb Region Change #> 1 Nevada NV West 35.1 #> 2 Arizona AZ West 24.6 #> 3 Utah UT West 23.8 #> ...<4 more rows>... #> 8 Florida FL South 17.6 #> 9 Colorado CO West 16.9 #> 10 South Carolina SC South 15.3
Now we can make the graph, mapping Region to fill (Figure 3.9):
ggplot(upc, aes(x = Abb, y = Change, fill = Region)) + geom_col()
The default colors aren’t the most appealing, so you may want to set them using
scale_fill_manual(). With this example, we’ll use the latter, and we’ll set the outline color of the bars to black, with
colour="black" (Figure 3.10). Note that setting occurs outside of
aes(), while mapping occurs within
ggplot(upc, aes(x = reorder(Abb, Change), y = Change, fill = Region)) + geom_col(colour = "black") + scale_fill_manual(values = c("#669933", "#FFCC66")) + xlab("State")
This example also uses the
reorder() function to reorder the levels of the factor
Abb based on the values of
Change. In this particular case it makes sense to sort the bars by their height, instead of in alphabetical order.