《R数据科学》的第21章主要是讲解如何用ggplot2绘制“良好图形”,这篇笔记包括“标签”和“注释”两部分。
1. 标签
#v0
ggplot(mpg, aes(displ, hwy)) + geom_point(aes(color = class)) + geom_smooth(se = FALSE)
#v1
ggplot(mpg, aes(displ, hwy)) + geom_point(aes(color = class)) + geom_smooth(se = FALSE) + labs(
title = "Fuel efficiency generally decreases with engine size",
subtitle = "Two seaters (sports cars) are an exception because of their light weight",
caption = "Data from fueleconomy.gov",
x = "Engine displacement (L)",
y = "Highway fuel economy (mpg)",
colour = "Car type"
)
当标签中含有数学公式?
#?plotmath 查看一些基本数学公式的表示方法
df <- tibble(
x = runif(10),
y = runif(10)
)
ggplot(df, aes(x, y)) + geom_point() + labs(x = quote(sum(x[i] ^ 2, i ==1, n)), y = quote(alpha + beta + frac(delta, theta)))
2. 注释
“更加细节的文本标签”
best_in_class <- mpg %>% group_by(class) %>% filter(row_number(desc(hwy)) == 1) #按照class分组,每一组依次filter;desc()表示降序排列;row_number()表示第几行
ggplot(mpg, aes(displ, hwy)) + geom_point(aes(color = class)) + geom_text(aes(label = model), data = best_in_class)
#图片如下,存在文本标签重叠以及文本掩盖了点的情况
ggplot(mpg, aes(displ, hwy)) + geom_point(aes(color = class)) + geom_label(aes(label = model), data = best_in_class, nudge_y = 2, alpha = 0.5) #nudge_y = 2表示文本框向上移2个单位
#图片如下,文本框重叠,不能明确文本框指代的是哪一个点
ggplot(mpg, aes(displ, hwy)) + geom_point(aes(color = class)) + geom_point(size = 3, shape = 1, data = best_in_class) + ggrepel::geom_label_repel(aes(label = model), data = best_in_class, size = 4, label.size = 1, segment.color = "green")
#优点:
#第二个geom_point()函数勾出了文本框指代的点,与geom_label_repel()函数搭配使用效果更好;
#同时geom_label_repel()可以错开原来重叠的文本框;
#size文本框中字体大小;
#label.size文本框粗细;
#segment.color左上角指代线段的颜色
text_cor <- tibble(displ = Inf, hwy = Inf)
ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_text(data = text_cor, aes(label = "Increasing engine size is \nrelated to decreasing fuel economy."), vjust = "top", hjust = "right")
hjust和vjust共有9种对齐组合,如下
其他的注释函数
#如何添加参考线,并使参考线位于拟合线的下方(调整图层顺序即可)
p <- ggplot(mpg, aes(displ, hwy)) + geom_point(aes(color = class)) +
geom_hline(yintercept = 40, size = 1, color = "grey") +
geom_vline(xintercept = 6, size = 1, color = "grey") +
geom_smooth(se = FALSE)
#如何添加箭头
arrow_cor <- tibble(xend = c(5.3, 5.7), yend = c(25, 26), x = c(5.1, 5.9), y = c(27, 28))
p + geom_segment(data = arrow_cor, aes(x = x, y = y, xend = xend, yend = yend), arrow = arrow(length = unit(0.1, "inches")))
总结
:哪些函数可以添加注释(包括文本、线、箭头)
geom_text(), geom_label(), ggrepel::geom_label_repel(), geom_hline(), geom_vline(), geom_segment(arrow = ...)