简体   繁体   中英

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. 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"). Hence, you see a legend now. Then, by setting colour equal to "1" and "2", you're saying to use these as labels. scale_colour_manual allows you to change these colours to red and black, instead of the red and blue" default.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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