4.19 Summary of Geoms & Grammatical Structure of
In this section, we will have a concise review for using
ggplot() to do data visualization.
4.19.1 Summarize all geoms
First, let’s summarize all the geoms we have covered.
One continuous variable (e.g.
One discrete variable (e.g.
Two continuous variables (e.g.
Two discrete variables (e.g.
One continuous variable and one discrete variable (e.g.
Note that in the summary, we are only using the basic geoms. Clearly, we can map variables to aesthetics or use
facet_wrap() (in Section 4.17.1) or
facet_grid() (in Section 4.17.2) to arrange the subplots into facets depending on the grouping variable(s).
There are more than 40 geoms in the ggplot2 package with many more geoms developed in other packages. So far, we’ve covered the most commonly used geoms. You can feel free to explore other geoms by doing an online search or looking at the documentation.
4.19.2 The grammatical structure of
Next, we review the grammatical structure of
||data to be used|
||geom for generating the desirable plot|
||aesthetic mappings, this may include the x and y axes and other features like
||statistical transformation, for example, when we create the errorbar|
||such as flipping the x and y axes|
||customize the x and y breaks|
||customize labels, title, and fonts|
4.19.3 A complex
To conclude this chapter, let’s look at an example with all components.
library(r02pro) library(tidyverse) ggplot(data = na.omit(sahp)) + geom_bar( mapping = aes(x = kit_qual, fill = oa_qual > 5), stat = "count", #Default stat for geom_bar, can be removed position = "fill") + coord_flip() + facet_wrap(vars(house_style)) + scale_y_continuous(breaks = seq(from = 0, to = 1, by = 0.2)) + theme(plot.title = element_text(size = 24, color = "magenta")) + ylab("proportion") + ggtitle('A bar chart for the sahp dataset')
This plot shows a bar chart using the data
sahp for the variable
kit_qual, map the variable
oa_qual > 5 to the fill aesthetic and with
fill position, with the x and y coordinates flipped, faceted using the variable
house_style, and with the breaks on the y axis, the title and its font, the label on the y axis being customized.