gpt4 book ai didi

r - 如何更改图例符号(关键字形)以匹配绘图符号?

转载 作者:行者123 更新时间:2023-12-04 15:24:43 25 4
gpt4 key购买 nike

我在几组中绘制数据点,然后添加不同变量(相同单位)的箱线图。请参见下图。如何更改图例中的符号以匹配图中的符号?

Different groups of variables with different symbols

代码:

p <- ggplot(data = tdata, aes( y=Temp ,x=Distance, color=Type)) +
geom_point() +
geom_boxplot( aes(y = Ambient,x=5,color="Ambient"))
p + facet_grid(cols = vars(Time),rows = vars(Day))

数据:

structure(list(Day = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), Time = c("a", "a", "a",
"a", "a", "b", "b", "b", "b", "b", "a", "a", "a", "a", "a", "b",
"b", "b", "b", "b"), Type = c("s", "f", "s", "f", "s", "f", "s",
"f", "s", "f", "s", "f", "s", "f", "s", "f", "s", "f", "s", "f"
), Temp = c(5, 3.1, 5.9, 8.4, 5.5, 9.9, 2.2, 6.9, 2.9, 8.8, 0.6,
2.2, 3.1, 1.4, 4, 8.4, 5.2, 2.2, 7.9, 2.7), Distance = c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L,
2L, 3L, 4L), Ambient = c(4.4, 6.3, 3.1, 2.5, 7.7, 7.1, 2.1, 5.1,
9.4, 5.7, 6.3, 4.9, 0.8, 6.5, 2.1, 1.6, 4.4, 7.9, 5.3, 5.2)), row.names = c(NA,
-20L), class = "data.frame")

F 和 S 应该分别是绿点和蓝点,Ambient 必须是图例中的箱线图符号。

最佳答案

一般来说,图例中的符号或字形可以通过参数 key_glyph 为每个 geom 设置。有关可用字形的概述,请参阅 here . (感谢@Tjebo 指出这一点。)

但是,使用 key_glyph 参数可以为“整个”geom 和图例全局设置 glpyh,即不能为不同的组设置不同的字形。

为了克服这个问题并获得预期的结果,我的方法是使用两个图例,而不是我将它们“粘合”在一起,使它们看起来像一个图例。这是通过添加第二个图例并通过 theme() 删除图例的间距和边距来实现的。

为了获得第二个图例,我在 geom_boxplot 中使用了 fill aes 而不是 color。为了模拟颜色映射,我通过 scale_fill_manual 将填充颜色设置为 white 并通过 guide_legend 调整填充指南。试试这个:

library(ggplot2)

p <- ggplot() +
geom_point(data = tdata, aes(y=Temp, x = Distance, color = Type)) +
geom_boxplot(data = tdata, aes(x = 5, y = Ambient, fill = "box"), color = scales::hue_pal()(3)[1]) +
scale_fill_manual(values = "white") +
scale_color_manual(values = scales::hue_pal()(3)[2:3]) +
guides(fill = guide_legend(title = "Type", order = 1), color = guide_legend(title = NULL, order = 2)) +
theme(legend.margin = margin(t = 0, b = 0), legend.spacing.y = unit(0, "pt"), legend.title = element_text(margin = margin(b = 10)))
p + facet_grid(cols = vars(Time),rows = vars(Day))

reprex package 创建于 2020-06-22 (v0.3.0)

关于r - 如何更改图例符号(关键字形)以匹配绘图符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62510721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com