0

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")

enter image description here

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))
wesleysc352
  • 579
  • 1
  • 8
  • 21
  • For the density, `geom_histogram(aes(y=..density..), etc)` is a [duplicate](https://stackoverflow.com/questions/21061653/creating-a-density-histogram-in-ggplot2). – Rui Barradas Mar 21 '22 at 15:12
  • It's not density, it's frequency – wesleysc352 Mar 21 '22 at 15:20
  • Does this answer your question? [Show percent % instead of counts in charts of categorical variables](https://stackoverflow.com/questions/3695497/show-percent-instead-of-counts-in-charts-of-categorical-variables) – benson23 Mar 21 '22 at 15:32
  • @benson23, This answer is old and I can't reproduce it. I'm using version R 4.1.1 – wesleysc352 Mar 21 '22 at 15:41

1 Answers1

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:

enter image description here

Quinten
  • 35,235
  • 5
  • 20
  • 53