在我的ggplot2图表中添加geom_smooth()
和geom_vline()
时,我在我的图例中遇到了一些奇怪的行为。这是一个可重复的例子:
library(ggplot2)
n <- 60
set.seed(123)
df <- data.frame(Area = sample(c("A", "B", "C", "D"), size = n, replace = TRUE),
x = runif(n),
y = runif(n),
Type = sample(c("I", "II"), size = n, replace = TRUE),
Result = sample(c("K", "L", "M"), size = n, replace = TRUE))
df.breaks <- data.frame(Area = c("B", "C"), x = c(0.8, 0.3))
ggplot(df, aes(x = x, y = y)) +
geom_point(aes(colour = Result, shape = Type), size = 3) +
geom_smooth(aes(linetype = "Smooth"), colour = "green", se = FALSE) +
geom_hline(yintercept = 0.3) +
facet_wrap(~Area) +
geom_vline(data = df.breaks, aes(xintercept = x, linetype = "Break"), colour = "purple") +
scale_colour_manual(values = c("K" = "red", "L" = "orange", "M" = "blue")) +
scale_linetype_manual(name = "Lines", values = c("Break" = "dashed", "Smooth" = "solid"))
你会注意到&#34; Lines&#34;图例中每个项目都有垂直线和水平线,第一种情况下有几条虚线,而在第二种情况下有几条实线。我尝试调整我的代码以生成一个图例,其中包括(1)水平绿线和旁边的一个键,称为&#34; Smooth&#34; (2)一条垂直的紫色直线,旁边有一个键叫做#34; Break&#34;。无论我尝试过什么(包括linetype
内/外aes()
等,或使用scale_linetype_identity()
,甚至是override.aes
选项,我都会感激一些帮助。我无法找到合适的组合!
我搜索了类似的示例,即使我发现其他帖子在guides
,colour
或fill
等上有叠加的垂直线,我也找不到shape
传奇上的垂直线,例如我的。任何帮助将深表感谢!谢谢!
答案 0 :(得分:1)
对这个问题的迟来的答复,但我认为如果其他人(或我未来的自己!)对此感兴趣,最好有答案。
根据@ aosmith在评论部分中提出的建议以及他对提供答案的鼓励,我最终用以下内容替换了剧情代码:
ggplot(df, aes(x = x, y = y)) +
geom_point(aes(colour = Result, shape = Type), size = 3) +
geom_hline(yintercept = 0.3) +
facet_wrap(~Area) +
geom_vline(data = df.breaks,
aes(xintercept = x, linetype = "Break"), colour = "purple") +
scale_colour_manual(values = c("K" = "red", "L" = "orange", "M" = "blue")) +
scale_linetype_manual(name = "Lines",
values = c("Break" = "dashed", "Smooth" = "solid")) +
geom_smooth(aes(fill = "Smooth"), method = "loess", colour = "green", se = FALSE) +
scale_fill_discrete(name = "")
上面的最后两行替换了原始代码中的以下行:
geom_smooth(aes(linetype = "Smooth"), colour = "green", se = FALSE) +
。
结果图表仍需要一些工作,特别是图例间距,但它解决了原始问题。