Ggplot gigrogram with percentage and percentage labels *
I want to use ggplot to generate a bar chart using percentages. I found this answer which helps me with this.
However, I also want to place a label at the top of each bar chart showing the actual percentage.
Here is my code and link to output:
p <- ggplot(mtcars, aes(x = hp)) +
geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) +
## scale_y_continuous(labels = percent_format()) #version 3.0.9
scale_y_continuous(labels = percent) #version 3.1.0
p <- p + stat_bin(aes(label=round((..count..)/sum(..count..),2)), geom="text", size=4)
plot(p)
Here's the result:
Unfortunately, you can see that data labels are not placed in percentage locations, but columns are "squeezed" down.
Is there a way to change the stat_bin parameters so that the text labels appear inside or immediately on top of the percentage bars (so that my bars aren't cut)?
Thank!
source to share
You just need to set values y
for your labels (and also make sure you are using the same cells as for bars)
library(scales)
p <- ggplot(mtcars, aes(x = hp)) +
geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) +
scale_y_continuous(labels = percent_format()) #version 3.0.9
##scale_y_continuous(labels = percent) #version 3.1.0
p <- p + stat_bin(aes(y=(..count..)/sum(..count..),
label=round((..count..)/sum(..count..),2)),
geom="text", size=4, binwidth = 25, vjust=-1.5)
plot(p)
source to share
When used geom_bar()
with, binwidth
you are currently getting the following error:
geom_bar()
no longer has a parameterbinwidth
. Please usegeom_histogram()
instead.
I modified MrFlick's code to include geom_histogram()
and display the values ββto be displayed as a percentage (instead of a fraction) using a function paste0
.
library(scales)
p <- ggplot(mtcars, aes(x = hp)) +
geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 25) +
stat_bin(aes(y=(..count..)/sum(..count..),
label=paste0(round((..count..)/sum(..count..)*100,1),"%")),
geom="text", size=4, binwidth = 25, vjust=-1.5)
plot(p)
source to share