简体   繁体   English

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

[英]How to add inside legend for a combined plot in ggplot2

I have the following df and ggplot2 code to make a scatter plot but failed to add a legend inside the plot. 我有以下df和ggplot2代码制作散点图,但未能在图内添加图例。 Thanks :) 谢谢 :)

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')

Try: 尝试:

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

In the above code, by putting col = "1" and col = "2" inside the aesthetics aes(), you're telling ggplot to add a colour dimension to the plot (and not just colour the points "red" and "black"). 在上面的代码中,通过将col =“ 1”和col =“ 2” 放在美学aes()内,您是在告诉ggplot向绘图添加颜色尺寸(而不仅仅是对点“ red”和“黑色”)。 Hence, you see a legend now. 因此,您现在看到一个图例。 Then, by setting colour equal to "1" and "2", you're saying to use these as labels. 然后,通过将颜色设置为等于“ 1”和“ 2”,您就是说将它们用作标签。 scale_colour_manual allows you to change these colours to red and black, instead of the red and blue" default. scale_colour_manual允许您将这些颜色更改为红色和黑色,而不是默认的“红色和蓝色”。

The same applies anytime you want to add any dimension to the plot. 无论何时要向绘图添加任何尺寸,都适用相同的规则。 But, instead of using col and scale_colour_manual , you would use an alternative such as shape and scale_shape_manual . 但是, scale_colour_manual使用colscale_colour_manual ,您还可以使用shapescale_shape_manual类的替代scale_shape_manual

Here is a way of long format data input 这是长格式数据输入的一种方法

#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