R ggplot:图例周围的线

4
我正在尝试使用ggplot2绘制我的数据图表。出于纯粹的表面原因,我想在图例周围画一条线,以更好地区分它与图表(即在图例框周围画一个黑色轮廓)。我在任何论坛上都找不到这个问题的答案,但也许你有什么建议?
library(ggplot2)

Res = matrix(ncol = 3, nrow = 500)
Res[,1] = 1:500
Res[,2] = sin((2*pi)/100*Res[,1])
Res[,3] = cos((2*pi)/100*Res[,1])
Res = as.data.frame(Res)
colnames(Res) = c("X", "Y1", "Y2")

ggplot(Res, aes(X)) + 
  geom_line(aes(y = Y1, colour = "1"), size = 2) +
  geom_line(aes(y = Y2, colour = "2"), size = 2) +
  scale_color_discrete(name = "Y's", labels = c(" sine", " cosine")) +
  theme(legend.position=c(0.9, 0.7))

传说中的正方形框,一个边框? - amrrs
1
theme(...) 中添加 legend.background = element_rect(fill = "grey", colour = "black") 可以通过在图例周围添加黑色边框来区分图例。 - parth
我更多地考虑的是图例框周围的轮廓。 - Arne
1个回答

11

这将为图例周围提供一个轮廓

library(ggplot2)

Res = matrix(ncol = 3, nrow = 500)
Res[,1] = 1:500
Res[,2] = sin((2*pi)/100*Res[,1])
Res[,3] = cos((2*pi)/100*Res[,1])
Res = as.data.frame(Res)
colnames(Res) = c("X", "Y1", "Y2")

ggplot(Res, aes(X)) + 
  geom_line(aes(y = Y1, colour = "1"), size = 2) +
  geom_line(aes(y = Y2, colour = "2"), size = 2) +
  scale_color_discrete(name = "Y's", labels = c(" sine", " cosine")) +
  theme(legend.position=c(0.9, 0.7)) +  
  theme(legend.background = element_rect(colour = 'black', fill = 'white', linetype='solid'))

您可以在此处阅读有关图例设置的更多信息https://github.com/tidyverse/ggplot2/wiki/Legend-Attributes


完美!非常感谢! - Arne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接