简体   繁体   English

在ggplot2 R 3.0.3中添加条形标签

[英]Add bar labels in ggplot2 R 3.0.3

I am trying to produce a count label a geom_bar() chart. 我试图产生一个计数标签geom_bar()图表。 The data is in the format of a Factor w/ 2 levels "0","1" 数据的格式为Factor w/ 2 levels "0","1"

Right now I have the following code but get an error of 'count' not found. 现在,我有以下代码,但未找到'count'错误。

Here is my code of my most recent try: 这是我最近尝试的代码:

ggplot(mb,
       aes(x = Intervention_grp,
           y = ..count..,)) +
  geom_bar(aes(fill = Intervention_grp),
           alpha = (1 - 0.618)) +
  geom_text(aes(label=Intervention_grp),
            vjust = -0.2)
Error in eval(expr, envir, enclos) : object 'count' not found

I see in the R Graphics Cookbook the following code: 我在R Graphics Cookbook中看到以下代码:

ggplot(cabbage_exp, aes(x=ineraction(Date, Cultivar), y=Weight)) +
    geom_bar(stat="identity") +
    geom_text(aes(label=Weight), vjust = -0.2)

So I tried it in a similar format, just not using the interaction 所以我尝试了类似的格式,只是没有使用交互

ggplot(mb,
       aes(x = Intervention_grp,
           y = Intervention_grp)) + 
  geom_bar(stat = "identity") +
  geom_text(aes(label=sum(as.numeric(Intervention_grp))),
            vjust = -0.2)

My result is two bars one for group 0 and one for group 1 with a label of 1519, there aren't that many observations in the data set. 我的结果是两个条形图,一个条形用于第0组,一个条形用于第1组,标签为1519,在数据集中没有多少观察值。

How do I properly get the labels in there with the counts? 如何正确放置带有计数的标签?

When I do the following: 当我执行以下操作时:

ggplot(mb,
       aes(x = Intervention_grp,
           y = ..count..,)) +
  geom_bar()

I get an appropriate bar graph with the correct counts on the y axis, I just want to put them on the bars themselves. 我得到一个在y轴上具有正确计数的合适的条形图,我只想将它们放在条形图本身上。

Thank you, 谢谢,

You can add a Count column first. 您可以先添加一个“ Count列。 Here it is with the plyr package: 这就是plyr软件包:

mb <- merge(mb, ddply(mb, .(Intervention_grp), summarise, Count=length(Intervention_grp), by = 'Intervention_grp')

Then you can use 那你可以用

geom_text(aes(label = Count, y = Count), vjust = -0.25)

Example

iris2 <- iris[sample(seq_len(150), 50), ]
iris2 <- merge(iris2, ddply(iris2, .(Species), summarise, Count = length(Species)), by = 'Species')
ggplot(iris2, aes(x = Species)) + geom_bar() + geom_text(aes(label = Count, y = Count), vjust = -0.25)

在此处输入图片说明

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

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