【问题标题】:GGplot add Data label to pointsGGplot将数据标签添加到点
【发布时间】:2014-04-14 17:04:58
【问题描述】:

如何使用 ggplot 为点添加数据标签?

我有一个名为“stacked”的堆叠数据框:

 > head(stacked)
    time    value variable
 1  100 152.2211       gg
 2  110 146.3304       gg
 3  115 143.5831       gg
 4  120 140.9527       gg
 5  125 138.4297       gg
 6  130 136.0057       gg

 > tail(stacked)
      time    value variable
  755 1975 56.02922        t
  756 1980 56.14049        t
  757 1985 56.25148        t
  758 1990 56.36219        t
  759 1995 56.47262        t
  760 2000 56.58277        t

现在假设我想显示显示“值”字段的数据标签,其中时间字段等于 100。这就是我所拥有的:

g<- ggplot(stacked, aes( x = time,  y=value, colour=variable, group= variable) )       +   geom_line()  +
 geom_text(data = stacked[stacked$time == 100,], aes(label = stacked$value))
print(g)

我收到错误:

Error: Aesthetics must either be length one, or the same length as the dataProblems:time, value, variable, variable

有什么想法吗?

谢谢。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    问题是在您的aes(...) 调用geom_text 时,您正在设置label = stacked$value。您已经指定了数据子集 (data = stacked[stacked$time == 100,]),因此您需要在此处设置 aes(label = value),因此它需要 value 列。

    我没有您的测试数据,但请看一下这个示例,我仅以 10 的倍数向数据点添加标签。

    ggplot(cars, aes(x = speed, y = dist)) + 
        geom_point() + 
        geom_text(data = subset(cars, speed %% 5 == 0), aes(label = dist))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多