Reputation: 670
I'm having the following data set in R which I want to plot in a scatterplot.
user distance time
1 1 8.559737 4
2 1 5.013872 5
3 1 11.168995 9
4 1 4.059428 4
5 1 3.928071 4
6 1 12.403195 7
I generate my plot using following R code.
plot <- ggplot(scatter, aes(x=scatter[['distance']], y=scatter[['time']])) +
geom_point(shape=16, size=5, colour=scatter[['user']]) +
scale_x_continuous("Distance", limits=c(0,100), breaks=seq(0, 100, 10)) +
scale_y_continuous("Time", limits=c(0,20), breaks=seq(0, 20, 2))
png(filename="scatters/0_2_scatter.png", width=800, height=800)
plot(plot)
dev.off()
This results in the following plot.
Why is my legend not shown? Isn't defining colour in geom_point sufficient? I'm trying to generate a legend containing a black dot and the text 'user1'.
Upvotes: 1
Views: 688
Reputation: 173577
Try:
ggplot(scatter, aes(x=distance, y=time)) +
geom_point(shape=16, size=5, mapping = aes(colour=user)) +
scale_x_continuous("Distance", limits=c(0,100), breaks=seq(0, 100, 10)) +
scale_y_continuous("Time", limits=c(0,20), breaks=seq(0, 20, 2))
The whole purpose of having a data
argument separate from the specifications in aes()
is that ggplot does non-standard evaluation allowing you to refer only to the (unquoted) column names. Don't ever refer to columns specifically via $
or [[
or [
inside of aes()
.
The legend should appear when you map aesthetics (i.e. use aes()
), which you hadn't for color.
Upvotes: 4