MCP_infiltrator
MCP_infiltrator

Reputation: 4189

Add bar labels in ggplot2 R 3.0.3

I am trying to produce a count label a geom_bar() chart. The data is in the format of a Factor w/ 2 levels "0","1"

Right now I have the following code but get an error of 'count' not found.

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:

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.

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.

Thank you,

Upvotes: 0

Views: 610

Answers (1)

Robert Krzyzanowski
Robert Krzyzanowski

Reputation: 9344

You can add a Count column first. Here it is with the plyr package:

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)

enter image description here

Upvotes: 1

Related Questions