R, ggplot2 add legend with different data frames (of different sizes)
I'm trying to make a simple geom_point plot using ggplot2, but I cannot get a legend to appear. I have two data frames I am plotting from that are different lengths (~2000 rows vs ~6000 rows).
I have tried adding things like 'scale_shape_manual(values=c(21, 23)' to get it to pop up, but this has not worked. I have also tried adding 'shape = 21' into aes and 'shape = 23' into aes for their respective geom_point calls, but I got the error 'Error: Continuous value supplied to discrete scale'. Thanks for any help! See example of code below:
x1 = c(0, 1, 2, 3, 4)
y1 = c(0.44, 0.64, 0.77, 0.86, 0.91)
x2 = c(0, 1)
y2 = c(0.42, 0.61)
df1 = data.frame(x1, y1)
df2 = data.frame(x2, y2)
g<- ggplot(df1, aes(x = (df1[,1]), y = (df1[,2]*100))) +
geom_point(colour = 'black', size = 5, fill = 'blue', shape = 21) +
geom_point(data = df2, aes(x = df2[,1], y = (df2[,2]*100)),
colour = 'black', size = 4, fill = 'white', shape = 23) +
xlab("Consecutive Dry Years") + ylab("Percent") + ggtitle("Plot") +
scale_y_continuous(limits=c(0, 100)) +
scale_x_continuous(breaks=0:20) +
scale_shape_manual(values=c(21, 23),
name="My Legend",
labels=c("Simulated", "Historical")) +
# scale_fill_manual(values=c('blue', 'white'),
# name="My Legend",
# labels=c("Simulated", "Historical")) +
# scale_colour_manual(values=c('black', 'black'),
# name="My Legend",
# labels=c("Simulated", "Historical")) +
theme_bw()
g
For my ggplotting, I always put my data into one dataframe. I sort of remember somebody saying that there is conflict with specifying different colors across geoms. I think this code gives you the idea:
df3 = data.frame(type=c(rep("sim",5), rep("his",2)), x = c(x1,x2), y=c(y1,y2))
g = ggplot(df3, aes(x=x,y=y*100)) + geom_point(aes(color=type)) + geom_line(aes(color=type)) +
xlab("Consecutive Dry Years") + ylab("Percent") + ggtitle("Plot") +
scale_y_continuous(limits=c(0, 100))
g
链接地址: http://www.djcxy.com/p/30918.html
上一篇: 基于R ggpairs变量的着色点