r - overlaying 2 plots from different sized dataset with legends using ggplot -
i have 2 datasets, different size. how plot them , have each different color , legend? in case, legend count1, count2, , legend title choose, let's say: mylegend. need change or add following commands?
x <- data.frame(q=1:10, count1=21:30) y <- data.frame(q=seq(1,10,0.5), count2=seq(11,20, 0.5)) ggplot() + geom_line(data=x, aes(x=q, y=count1)) + geom_point(data=y, aes(x=q, y=count2))
the easiest solution combine data in same data.frame, set aesthetics (aes
) in ggplot.
here 1 way can combine everything:
df <- data.frame(q = c(x$q, y$q), count = c(x$count1, y$count2), type = c(rep("count1", 10), rep("count2", 19)) )
but can use commands rbind()
or melt()
(from reshape2
library).
with data combined 1 data.frame:
ggplot(df, aes(x=q, y=count, colour=type)) + geom_point() + geom_line() + scale_colour_discrete(name="mylegend")
this basic example, , highly recommend hadley wickham's ggplot2 book, searching google (stack overflow, r cookbook, etc) solutions specific plotting problems or more ways customize plots.
Comments
Post a Comment