【问题标题】:R scatterplot, legend not shownR散点图,未显示图例
【发布时间】:2015-03-31 21:58:38
【问题描述】:

我在 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

我使用以下 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()

这将导致以下情节。

为什么我的图例没有显示?在 geom_point 中定义颜色还不够吗? 我正在尝试生成一个包含黑点和文本“user1”的图例。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    试试:

    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))
    

    data 参数与aes() 中的规范分开的全部目的是 ggplot 进行非标准评估,允许您仅引用(未引用的)列名。永远不要通过 $[[[aes() 内部专门引用列。

    当您映射美学(即使用aes())时,应该会出现图例,而您没有用于颜色。

    【讨论】: