Sergio
Sergio

Reputation: 472

Overlay percentage in barplot with correct scale with ggplot

I am trying to overlay percentages to a barplot with ggplot. I have tried to approaches which have failed:

  1. Using geom_text:

    p <- ggplot(data, aes(x = factor(data[[variable1]]) ), environment = environment() )
    p <- p + geom_bar(aes(y = ..count../sum(..count..)), position = modo)
    p <- p + geom_text( aes(labels = ..count../sum(..count..)) , vjust = -0.2)
    p <- p + scale_y_continuous(labels = percent_format())
    

I get the error message:

Error in eval(expr, envir, enclos) : object 'count' not found

As suggested here, I tried the stat_bin function, but the scale gets messed up, and I lost the bars (based on the new scale, I guess they still exist but are just not visible):

p <- ggplot(data, aes(x = factor(data[[variable1]]) ), environment = environment() )
p <- p + geom_bar(aes(y = ..count../sum(..count..)), position = modo)
p <- p + stat_bin( aes(label = ..count../sum(..count..) ) , vjust = -0.2, geom ="text" )
p <- p + scale_y_continuous(labels = percent_format())

This is what I get:

This is what I get

Any clues on how to solve this?

Upvotes: 0

Views: 526

Answers (1)

Sergio
Sergio

Reputation: 472

Answering my own question here:

I had to map the y values. I also had to multiply label values by 100 in order to have consistent percentages.

p <- ggplot(data, aes(x = factor(data[[variable1]]) ), environment = environment() )
p <- p + geom_bar(aes(y = ..count../sum(..count..)), position = modo)
p <- p + scale_y_continuous(labels = percent_format())
p <- p + stat_bin( aes(y = ..count../sum(..count..), label = paste(  round( 100 * ..count../sum(..count..)), "%" ) ), vjust = -0.2, geom ="text" ) 

Upvotes: 2

Related Questions