简体   繁体   English

R散点图,未显示图例

[英]R scatterplot, legend not shown

I'm having the following data set in R which I want to plot in a scatterplot. 我在R中有以下数据集,我想在散点图中绘制。

     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. 我使用以下R代码生成我的情节。

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? 是不是在geom_point中定义了足够的颜色? I'm trying to generate a legend containing a black dot and the text 'user1'. 我正在尝试生成包含黑点和文本“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. data参数与aes()的规范分开的整个目的是ggplot执行非标准评估,允许您仅引用(未引用的)列名。 Don't ever refer to columns specifically via $ or [[ or [ inside of aes() . 不要特别通过$[[[ aes()内部aes()引用列。

The legend should appear when you map aesthetics (ie use aes() ), which you hadn't for color. 当您映射美学(即使用aes() )时,应该会出现图例,而这些美学并不是为了颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM