How to show percent labels on histogram bars using ggplot2

我的梦境 提交于 2020-01-02 07:26:08

问题


I have seen lots of question regarding converting count on y axis into percent but must of them are in bar plot.

I want to do similar thing in histogram but not able to show the labels on the bar clearly. Please tell me where I am doing wrong.

x = runif(100, min = 0, max = 10)
data1 <- data.frame(x = x)

ggplot(aes(x = x), data = data1)+
geom_histogram(aes(y = (..count..)/sum(..count..)), bins = 10, breaks = 
seq(0,10,1), fill = "blue", col = "black")+
geom_text(aes(y = ((..count..)/sum(..count..)), 
            label = scales::percent((..count..)/sum(..count..))), 
        stat = "count", vjust = -10)+ 
scale_y_continuous(labels = scales::percent)

Output:


回答1:


Use scale_y_continous with breaks and labels will solve your problem.

  data1 <- data.frame (x = runif(100, min = 0, max = 10))
ggplot(aes(x=x), data1) + stat_bin(aes(y = ..count..)) 
ggplot(data1, aes(x = x)) + geom_histogram(fill = "blue", col = "black")+ scale_y_continuous(breaks = seq(0,10,1),labels = paste(seq(0, 10, by = 1) / 100, "%", sep = ""))+geom_text(aes(y = (..count..),label =  scales::percent((..count..)/sum(..count..))), stat="bin",colour="green",vjust=2) 

or, you can specify where you would like to add the percentage like this:

geom_text(aes(y = (..count..)+0.5))

of course you can change the color as well. from,

stat="bin",colour="your prefer color "

Also you can change the width of the bins as follows:

geom_histogram(fill = "blue", col = "black", binwidth = 0.5) 



来源:https://stackoverflow.com/questions/46482621/how-to-show-percent-labels-on-histogram-bars-using-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!