繁体   English   中英

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

[英]How to add inside legend for a combined plot in 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')

尝试:

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 =“ 1”和col =“ 2” 放在美学aes()内,您是在告诉ggplot向绘图添加颜色尺寸(而不仅仅是对点“ red”和“黑色”)。 因此,您现在看到一个图例。 然后,通过将颜色设置为等于“ 1”和“ 2”,您就是说将它们用作标签。 scale_colour_manual允许您将这些颜色更改为红色和黑色,而不是默认的“红色和蓝色”。

无论何时要向绘图添加任何尺寸,都适用相同的规则。 但是, scale_colour_manual使用colscale_colour_manual ,您还可以使用shapescale_shape_manual类的替代scale_shape_manual

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

#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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM