percentage on y lab in a faceted ggplot barchart?

前端 未结 6 1334
孤独总比滥情好
孤独总比滥情好 2020-12-01 00:56

doing facets in ggplot I would often like the percentage to be used instead of counts.

e.g.

test1 <- sample(letters[1:2], 100, replace=T)
test2 &         


        
6条回答
  •  星月不相逢
    2020-12-01 01:24

    A very simple way:

    ggplot(test, aes(test2)) + 
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        facet_grid(~test1)
    

    So I only changed the parameter of geom_bar to aes(y = (..count..)/sum(..count..)). After setting ylab to NULL and specifying the formatter, you could get:

    ggplot(test, aes(test2)) +
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        facet_grid(~test1) +
        scale_y_continuous('', formatter="percent")
    

    Update Note that while formatter = "percent") works for ggplot2 version 0.8.9, in 0.9.0 you'd want something like scale_y_continuous(labels = percent_format()). alt text

提交回复
热议问题