Graphics Reference
In-Depth Information
Using Colors in a Bar Graph
Problem
You want to use different colors for the bars in your graph.
Solution
Map the appropriate variable to the fill aesthetic.
We'll use the uspopchange data set for this example. It contains the percentage change in pop-
ulation 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 Cen-
tral, or West).
First, we'll take the top 10 states:
library(gcookbook) # For the data set
upc <- subset(uspopchange, rank(Change) > 40 )
upc
State Abb Region Change
Arizona AZ West
24.6
Colorado CO West
16.9
Florida FL South
17.6
Georgia GA South
18.3
Idaho ID West
21.1
Nevada NV West
35.1
North Carolina NC South
18.5
South Carolina SC South
15.3
Texas TX South
20.6
Utah UT West
23.8
Now we can make the graph, mapping Region to fill ( Figure 3-9 ):
ggplot(upc, aes(x = Abb, y = Change, fill = Region)) + geom_bar(stat = "identity" )
Search WWH ::




Custom Search