GGplot将数据标签添加到点 [英] GGplot add Data label to points

查看:548
本文介绍了GGplot将数据标签添加到点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I add data labels to points using ggplot?

我有一个称为"stacked"的堆叠数据框:

I have a stacked data frame called "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.这是我拥有的:

Now lets say I want to show data labels displaying the "value" field where the time field is equal to 100. Here is what I have:

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

有什么想法吗?

谢谢.

推荐答案

问题在于,在您对geom_textaes(...)调用中,您正在设置label = stacked$value.您已经指定了数据子集(data = stacked[stacked$time == 100,]),因此这里需要做的全部是设置aes(label = value),以便它使用value列.

The problem is that in your aes(...) call for geom_text you are setting label = stacked$value. You've already specified the data subset (data = stacked[stacked$time == 100,]) so all you need to do here is set aes(label = value) so it takes the value column.

我没有您的测试数据,但请看下面的示例,在该示例中,我仅以10的倍数的速度仅向数据点添加标签.

I don't have your test data but take a look at this example where I'm adding labels only to the data points at speeds that are a multiple of 10.

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

这篇关于GGplot将数据标签添加到点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆