简体   繁体   中英

R scatterplot, legend not shown

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'.

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 (ie use aes() ), which you hadn't for color.

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