'How to create a histogram of frequencies in percentage in ggplot?
I'm trying to create a frequency histogram in ggplot 2 using geom_histogram, but this command only returns the number of observations instead of frequency in percentage. I would also like the percentage values to be on top of the bars.
I find it strange that ggplot doesn't have a frequency=TRUE command from the native hist r-base command.
Is there any simple way to do this in ggplot? I know hist would do it, but ggplot will let me do other things with these plots.
i try
df<-data.frame(corr=runif(100, min = -1, max = 1))
#View(df)
ggplot(data=df, aes(x=corr))+
geom_histogram(color="darkblue", fill="lightblue")
Alternatively, I tried the following command based on this answer Show percent % instead of counts in charts of categorical variables, but it seems to me that the versions used are old and don't respond well in R 4.1.1
ggplot(data=df, aes(x=corr))+
geom_bar(aes(y = (((..count..)/sum(..count..))*100)))
scale_y_continuous(labels = percent))
Solution 1:[1]
You can use this code:
library(tidyverse)
library(scales)
df<-data.frame(corr=runif(100, min = -1, max = 1))
ggplot(df, aes(x = corr)) +
geom_histogram(fill = "blue", col = "black")+
scale_y_continuous(breaks = seq(0,10,1),labels = paste(seq(0, 10, by = 1), "%", sep = ""))+
geom_text(aes(y = (..count..),label = scales::percent((..count..)/sum(..count..))), stat="bin",colour="red",vjust=-1, size = 3) +
ylab("Percentage")
Output:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |


