Reputation: 1
i am trying to overlay the percentage of people in the sample belonging to each bar, but i am not able to place the number on top of each bar. Even if I try to simply align each percentage with 0, the percentage of the first two bars are a little bit higher than the rest.
ggplot(bbdd, aes(t_fluoro)) +
geom_histogram(breaks = seq(0, 30, by = 3.5), fill="#99ccff") +
scale_x_continuous(breaks=seq(0,30,by=3.5), limits=c(0,24.5), expand=c(0,0)) +
scale_y_continuous(limits=c(0,45), expand=c(0,0)) +
stat_bin(breaks = seq(0, 30, by = 3.5),
geom = "text",
color = "#333366",
aes(y = after_stat(count / sum(count)),
label = scales::percent(after_stat(count / sum(count)))),
vjust=0) +
coord_fixed(ratio=0.6) +
xlab(label = "Fluoroscopy time (min)") +
ylab(label = "number of subjects") +
theme_light() +
theme(panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank())
Thanks for the help!
I have tried several configs of Vjust and Hjust
Upvotes: 0
Views: 44
Reputation: 3912
In your code, simply change y = after_stat(count / sum(count))
to y = after_stat(count)
. Only use after_stat(count)
as y
paramater in aes
to place the percentage labels on top
library(ggplot2)
library(scales)
set.seed(123) # For reproducibility
bbdd <- data.frame(
t_fluoro = rnorm(100, mean = 12, sd = 5) # Generate 100 values with mean=12 and sd=5
)
ggplot(bbdd, aes(t_fluoro)) +
geom_histogram(breaks = seq(0, 30, by = 3.5), fill="#99ccff") +
scale_x_continuous(breaks=seq(0,30,by=3.5), limits=c(0,24.5), expand=c(0,0)) +
scale_y_continuous(limits=c(0,45), expand=c(0,0)) +
stat_bin(breaks = seq(0, 30, by = 3.5),
geom = "text",
color = "#333366",
aes(y = after_stat(count), # change made here
label = scales::percent(after_stat(count / sum(count)))),
vjust=-0.5) +
coord_fixed(ratio=0.6) +
xlab(label = "Fluoroscopy time (min)") +
ylab(label = "number of subjects") +
theme_light() +
theme(panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank())
I have tried several configs of Vjust and Hjust
vjust=0.5
--> keeps the labels vertical position the same, 0 adjusted the labels up, 1 adjusts the labels down
hjust=0.5
--> keeps the labels horizontal position the same, 0 adjusted the labels to the right, 1 adjusts the labels to the left
See, how they work together:
Upvotes: 0