简体   繁体   中英

How to show percent labels on histogram bars using ggplot2

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:

在此输入图像描述

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) 

在此输入图像描述

在此输入图像描述

继承人的图表

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM