如何在ggplot2中为组合图添加内部图例

时间:2017-09-25 06:37:05

标签: r ggplot2

我有以下df和ggplot2代码来制作散点图但无法在图中添加图例。谢谢:)

x1 = 1:5 
x2 = 6:10
y1 = 3:7
y2 = 2:6

df <- data.frame(x1, y1, x2, y2)

ggplot(df) + geom_point(aes(x=x1, y = y1),col='red') + geom_point(aes(x = x2, y = y2),col='black')

2 个答案:

答案 0 :(得分:1)

尝试:

x1 = 1:5 
x2 = 6:10
y1 = 3:7
y2 = 2:6

df <- data.frame(x1, y1, x2, y2)

ggplot(df) + geom_point(aes(x=x1, y = y1, col = "1")) + 
geom_point(aes(x = x2, y = y2, col = "2")) + scale_colour_manual(values = c("red", "black"))

在上面的代码中,通过输入col =&#34; 1&#34;和col =&#34; 2&#34; 内部美学aes(),你告诉ggplot为剧情添加颜色维度(而不只是为点着色&#34;红色&#34;和&#34;黑& #34)。因此,你现在看到一个传奇。然后,通过设置等于&#34; 1&#34;和&#34; 2&#34;,您说要将它们用作标签。 scale_colour_manual允许您将这些颜色更改为红色和黑色,而不是红色和蓝色&#34;默认值。

只要您想要为图添加任何尺寸,这同样适用。但是,您可以使用colscale_colour_manual之类的替代方案,而不是使用shapescale_shape_manual

答案 1 :(得分:1)

这是一种长格式数据输入方式

#data into long format
x1 = 1:5 
x2 = 6:10
y1 = 3:7
y2 = 2:6
df <- data.frame(x=c(x1, x2), y=c(y1, y2), group=rep(c("x1", "x2"), c(5, 5)))
#plot it
library(ggplot2)
ggplot(df) + 
  geom_point(aes(x=x, y = y, colour=group))+
  scale_colour_manual(values=c("red", "black"))