r - How to add percentage or count labels above percentage bar plot? -


using ggplot2 1.0.0, followed instructions in below post figure out how plot percentage bar plots across factors:

sum percentages each facet - respect "fill"

test <- data.frame(      test1 = sample(letters[1:2], 100, replace = true),       test2 = sample(letters[3:8], 100, replace = true)      ) library(ggplot2) library(scales) ggplot(test, aes(x= test2, group = test1)) +  geom_bar(aes(y = ..density.., fill = factor(..x..))) +  facet_grid(~test1) + scale_y_continuous(labels=percent) 

enter image description here

however, cannot seem label either total count or percentage above each of bar plots when using geom_text.

what correct addition above code preserves percentage y-axis?

staying within ggplot, might try

ggplot(test, aes(x= test2,  group=test1)) +    geom_bar(aes(y = ..density.., fill = factor(..x..))) +   geom_text(aes( label = format(100*..density.., digits=2, drop0trailing=true),                  y= ..density.. ), stat= "bin", vjust = -.5) +   facet_grid(~test1) +   scale_y_continuous(labels=percent) 

for counts, change ..density.. ..count.. in geom_bar , geom_text

update ggplot 2.x

ggplot2 2.0 made many changes ggplot including 1 broke original version of code when changed default stat function used geom_bar ggplot 2.0.0. instead of calling stat_bin, before, bin data, calls stat_count count observations @ each location. stat_count returns prop proportion of counts @ location rather density.

the code below has been modified work new release of ggplot2. i've included 2 versions, both of show height of bars percentage of counts. first displays proportion of count above bar percent while second shows count above bar. i've added labels y axis , legend.

  library(ggplot2)   library(scales) # # displays bar heights percents percentages above bars #     ggplot(test, aes(x= test2,  group=test1)) +      geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +     geom_text(aes( label = scales::percent(..prop..),                    y= ..prop.. ), stat= "count", vjust = -.5) +     labs(y = "percent", fill="test2") +     facet_grid(~test1) +     scale_y_continuous(labels=percent) # # displays bar heights percents counts above bars #     ggplot(test, aes(x= test2,  group=test1)) +      geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +     geom_text(aes(label = ..count.., y= ..prop..), stat= "count", vjust = -.5) +     labs(y = "percent", fill="test2") +     facet_grid(~test1) +     scale_y_continuous(labels=percent) 

the plot first version shown below.

enter image description here


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -