Abstract
ggplot2 is one of the most powerful packages in r for data visualizations and it is essential to master the underlying grammar of graphics to fully utilize its power. While the theming system of ggplot2 allows you to customize the appearance of the plot according to our needs in practice, it is always a frustration to identify the elements on the plot you want to change as you may find it difficult to remember the element names and their corresponding functions to modify, at least this is the case for me.
## [1] "compact" "midsize" "suv" "2seater" "minivan"
## [6] "pickup" "subcompact"
## tibble [61 x 11] (S3: tbl_df/tbl/data.frame)
## $ manufacturer: chr [1:61] "toyota" "toyota" "toyota" "toyota" ...
## $ model : chr [1:61] "4runner 4wd" "4runner 4wd" "4runner 4wd" "4runner 4wd" ...
## $ displ : num [1:61] 2.7 2.7 3.4 3.4 4 4.7 2.2 2.2 2.4 2.4 ...
## $ year : int [1:61] 1999 1999 1999 1999 2008 2008 1999 1999 2008 2008 ...
## $ cyl : int [1:61] 4 4 6 6 6 8 4 4 4 4 ...
## $ trans : chr [1:61] "manual(m5)" "auto(l4)" "auto(l4)" "manual(m5)" ...
## $ drv : chr [1:61] "4" "4" "4" "4" ...
## $ cty : int [1:61] 15 16 15 15 16 14 21 21 21 21 ...
## $ hwy : int [1:61] 20 20 19 17 20 17 29 27 31 31 ...
## $ fl : chr [1:61] "r" "r" "r" "r" ...
## $ class : chr [1:61] "suv" "suv" "suv" "suv" ...
p <- mpg_df %>%
ggplot(aes(displ,hwy,col = factor(cyl))) +
geom_point() +
facet_grid(manufacturer ~ class) +
labs(title = "hwy vs. displ") +
scale_color_discrete(name = "Cylinders") +
mytheme
p
p1 <- p +
theme(plot.background = element_rect(fill = "lemonchiffon",
color = "black",
size = 2),
plot.title = element_text(hjust = 0.5, colour = "red", face = "bold"),
plot.margin = margin(20, 20, 20, 20))
p1
p2 <- p1 + theme(axis.line = element_line(colour = "yellow", size = 1),
axis.text = element_text(colour = "red"),
axis.ticks = element_line(colour = "purple", size = 1))
p2
p3 <- p2 + theme(legend.background = element_rect(fill = "deepskyblue2"),
legend.key = element_rect(fill = "lemonchiffon"),
legend.title = element_text(colour = "white", face = "bold"),
legend.text = element_text(colour = "blue"),
legend.margin = margin(10, 10, 10, 10))
p3
p4 <- p3 + theme(panel.background = element_rect(fill = "lightblue"),
panel.grid = element_line(colour = "grey60", size = 0.2),
panel.border = element_rect(colour = "black", fill = NA))
p4
p5 <- p4 + theme(strip.background = element_rect(fill = "steelblue"),
strip.text = element_text(colour = "white"),
panel.spacing = unit(0.3, "in"))
p5
从示例中可以看到,要修改plot中的单个元素,只需遵循参数: theme(element.name = element function())
。这个例子中的最后一个图并不一定很漂亮,因为我使得识别相应的元素变得更加容易。