# 第 16 章 ggplot2之图例系统

## 16.1 图例系统

library(tidyverse)

mpg %>%
ggplot(aes(x = displ, y = hwy, color = factor(cyl))) +
geom_point()  

• 要么是字符串 (i.e. "color = colorbar" or "color = legend"),
• 要么是特定的函数 (i.e. color = guide_colourbar() or color = guide_legend())

## 16.2 案例详解

mpg %>%
ggplot(aes(x = displ, y = hwy, color = factor(cyl))) +
geom_point() +
ggtitle("这是我的标题") +
labs(x = "x_displ", y = "y_hwy") +
guides(color = "legend")

mpg %>%
ggplot(aes(x = displ, y = hwy, color = factor(cyl))) +
geom_point() +
ggtitle("这是我的标题") +
labs(x = "x_displ", y = "y_hwy") +
guides(color = guide_bins(
title = "my title",
label.hjust = 1
)
)

mpg %>%
ggplot(aes(x = displ, y = hwy, color = factor(cyl))) +
geom_point() +
ggtitle("这是我的标题") +
labs(x = "x_displ", y = "y_hwy") +
guides(color = guide_legend(
ncol = 4
)
)

mpg %>%
ggplot(aes(x = displ, y = hwy, color = factor(cyl))) +
geom_point() +
ggtitle("这是我的标题") +
labs(x = "x_displ", y = "y_hwy") +
guides(color = guide_legend(
title = "标题好像有点高",
title.position = "top",
title.vjust = 5,
label.position = "left",
label.hjust = 1,
label.theme = element_text(size = 15,
face = "italic",
colour = "red",
angle = 0),
keywidth = 5,
reverse = TRUE
)
)

## 16.3 删除其中一个图例

mpg %>%
ggplot(aes(x = displ, y = hwy, color = class, size = cyl)) +
geom_point()

mpg %>%
ggplot(aes(x = displ, y = hwy, color = class, size = cyl)) +
geom_point() +
guides(color = guide_legend("汽车类型"),  # keep
size = FALSE                       # remove
)

## 16.4 小结

mtcars %>%
as_tibble() %>%
ggplot(aes(x = wt, y = mpg, shape = factor(vs), color = hp)) +
geom_point(size = 3) +
colorspace::scale_color_continuous_sequential(palette = "Dark Mint") +
scale_shape_discrete(labels = c("V-shaped", "Straight")) +
labs(
x = "Weight (1000 lbs)", y = "Miles per gallon",
title = "Motor Trend Car Road Tests",
shape = "Engine", color = "Horsepower"
) +
theme(
text = element_text(size = 18, color = "white"),
rect = element_rect(fill = "black"),
panel.background = element_rect(fill = "black"),
legend.key = element_rect(fill = "black"),
axis.text = element_text(color = "white"),
plot.title.position = "plot",
plot.margin = margin(10, 10, 10, 10)
) +
guides(
shape =
guide_legend(override.aes = list(color = "white"))
)