修改ggplot的图例符号
测试开头



















测试结尾
介绍
最新版本的ggplot2 3.2.0使我们能够像这样改变图例中的符号。
1library(ggplot2)
2
3ggplot(economics_long, aes(date, value01, colour = variable)) +
4 geom_line(key_glyph = "timeseries")

它们同样可以用draw_key_*
函数指定。
1ggplot(economics_long, aes(date, value01, colour = variable)) +
2 geom_line(key_glyph = draw_key_timeseries)

展示例子
下面是ggplot2中所有可用的draw_key_*
函数。请注意,点图和多边形中的深灰色是未指定填充美学的结果。生成这些图形的代码可以在本文末尾找到。
















自定义符号键
因为draw_key_*
函数只返回一个grob,所以您可以花一些时间来创建自己的自定义符号!从draw_key_boxplot中获得灵感。
1draw_key_boxplot
2## function (data, params, size)
3## {
4## grobTree(linesGrob(0.5, c(0.1, 0.25)), linesGrob(0.5, c(0.75,
5## 0.9)), rectGrob(height = 0.5, width = 0.75), linesGrob(c(0.125,
6## 0.875), 0.5), gp = gpar(col = data$colour %||% "grey20",
7## fill = alpha(data$fill %||% "white", data$alpha), lwd = (data$size %||%
8## 0.5) * .pt, lty = data$linetype %||% 1))
9## }
10## <bytecode: 0x7fa7a2983380>
11## <environment: namespace:ggplot2>
我会试着自己用点和线做一个符号。
1library(grid)
2library(rlang)
3draw_key_smile <- function(data, params, size) {
4 grobTree(
5 pointsGrob(0.25, 0.75, size = unit(.25, "npc"), pch = 16),
6 pointsGrob(0.75, 0.75, size = unit(.25, "npc"), pch = 16),
7 linesGrob(c(0.9, 0.87, 0.78, 0.65, 0.5, 0.35, 0.22, 0.13, 0.1),
8 c(0.5, 0.35, 0.22, 0.13, 0.1, 0.13, 0.22, 0.35, 0.5)),
9 gp = gpar(
10 col = data$colour %||% "grey20",
11 fill = alpha(data$fill %||% "white", data$alpha),
12 lwd = (data$size %||% 0.5) * .pt,
13 lty = data$linetype %||% 1
14 )
15 )
16}
17
18ggplot(economics_long, aes(date, value01, colour = variable)) +
19 geom_line(key_glyph = draw_key_smile)

它看起来很开心!
附录
1library(dplyr)
2library(magrittr)
3library(ggplot2)
4library(grid)
5
6draws <- ls(getNamespace("ggplot2"), pattern = "^draw_key_")
7
8legend_fun <- function(x) {
9 ggg <- economics_long %>%
10 mutate(variable = factor(variable, labels = paste("Option", LETTERS[1:5]))) %>%
11 ggplot(aes(date, value01, colour = variable)) +
12 geom_line(key_glyph = get(x)) +
13 labs(color = x)
14
15 legend <- cowplot::get_legend(ggg)
16
17 grid.newpage()
18 grid.draw(legend)
19}
20
21purrr::walk(draws[1:12], legend_fun)
22p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars))) +
23 geom_text(aes(colour = factor(ceiling(seq_len(nrow(mtcars)) %% 5), labels = paste("Option", LETTERS[1:5])))) +
24 labs(color = "draw_key_text")
25legend <- cowplot::get_legend(p)
26
27grid.newpage()
28grid.draw(legend)
29purrr::walk(draws[14:16], legend_fun)
原文链接:
https://www.hvitfeldt.me/blog/changing-glyph-in-ggplot2/
您在阅读中有什么问题,请留言。若是觉得有用,请您点赞和分享给其他朋友,感谢支持和分享。
公众号推荐:
数据人才(ID:datarencai)
(一个帮助数据人才找工作,
帮助数据公司招人才的公众号,
也分享数据人学习和生活的有趣事情。)
请关注“恒诺新知”微信公众号,感谢“R语言“,”数据那些事儿“,”老俊俊的生信笔记“,”冷🈚️思“,“珞珈R”,“生信星球”的支持!