How do I convince ggplot2 to create a legend for me?
I've managed to get ggplot2 to create almost the plot I want from a data set, but I can't figure out how to label my points.
Given data looking something like this:
sample <- data.frame(rowid=seq(100), a=runif(100), b=runif(100, .5, 1.5))
I can create a plot comparing these two things like this (looks less funny given my real and better labels, but this does a good approximation):
ggplot(data=sample) +
geom_point(aes(rowid, a), color="#990000", alpha=0.4) +
geom_smooth(aes(rowid, a), color='#990000') +
开发者_运维百科 geom_point(aes(rowid, b), color='#000099', alpha=0.4) +
geom_smooth(aes(rowid, b), color='#000099') +
labs(x='Trial', y='Time')
How can I get that to have a legend displaying what the red and the blue are?
Edit
Thanks to a comment from baptiste, I now have the following:
wide = melt(sample, id="rowid")
ggplot(data=wide) +
geom_point(aes(rowid, value, color=variable), alpha=0.1) +
scale_alpha(0.3) +
scale_colour_manual(name="Variables", values=c("b"="#990000", "a"="#000099")) +
geom_smooth(aes(rowid, value, color=variable)) +
labs(x='Trials', y='Time')
Baptiste pointed you in the right direction by suggesting using melt
from the reshape2
package.
To control the alpha of your points and smoother separately, simply specify the alpha you desire in each geom. Note that the scale_alpha
statement in your example code does nothing, because alpha was not mapped to any aesthetic, so I removed this. Also, since your mapping is identical to all layers, this is easier to specify in the ggplot
paramaters rather than the geom parameters:
sample <- data.frame(rowid=seq(100), a=runif(100), b=runif(100, .5, 1.5))
wide = melt(sample, id="rowid")
ggplot(data=wide, aes(x=rowid, y=value, color=variable)) +
geom_point(alpha=0.1) +
scale_colour_manual(name="Variables", values=c("b"="#990000", "a"="#000099")) +
geom_smooth(alpha=0.8) +
labs(x='Trials', y='Time')
精彩评论