Graphics Reference
In-Depth Information
birthwt
low age lwt race smoke ptl ht ui ftv bwt
0 19 182
2
0
0 0 1
0 2523
0 33 155
3
0
0 0 0
3 2551
0 20 105
1
1
0 0 0
1 2557
...
One problem with the faceted graph is that the facet labels are just 0 and 1, and there's no label
indicating that those values are for smoke . To change the labels, we need to change the names
of the factor levels. First we'll take a look at the factor levels, then we'll assign new factor level
names, in the same order:
birthwt1 <- birthwt # Make a copy of the data
# Convert smoke to a factor
birthwt1$smoke <- factor(birthwt1$smoke)
levels(birthwt1$smoke)
"0" "1"
library(plyr) # For the revalue() function
birthwt1$smoke <- revalue(birthwt1$smoke, c( "0" = "No Smoke" , "1" = "Smoke" ))
Now when we plot it again, it shows the new labels ( Figure 6-4 , right).
ggplot(birthwt1, aes(x = bwt)) + geom_histogram(fill = "white" , colour = "black" ) +
facet_grid(smoke ~ . )
With facets, the axes have the same yscaling in each facet. If your groups have different sizes,
it might be hard to compare the shapesof the distributions of each one. For example, see what
happens when we facet the birth weights by race ( Figure 6-5 , left):
ggplot(birthwt, aes(x = bwt)) + geom_histogram(fill = "white" , colour = "black" ) +
facet_grid(race ~ . )
To allow the yscales to be resized independently ( Figure 6-5 , right), use scales="free" . Note
that this will only allow the yscales to be freeā€”the xscales will still be fixed because the histo-
grams are aligned with respect to that axis:
ggplot(birthwt, aes(x = bwt)) + geom_histogram(fill = "white" , colour = "black" ) +
facet_grid(race ~ . , scales = "free" )
Another approach is to map the grouping variable to fill , as shown in Figure 6-6 . The grouping
variable must be a factor or character vector. In the birthwt data set, the desired grouping vari-
Search WWH ::




Custom Search