I have created the following graph with this code
geom_bar(colour="black",fill="darkgrey") theme_apa() theme(
plot.title = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank())
geom_text(stat='count', aes(label=..count..), vjust=-0.5)
scale_y_continuous(limits = c(0,25))
First of all, how do I make the
scale_y_continuous(limits = c(0,25))
automatically recognize the max count in the graph, and expand the y axis by 3? In this case, I've set it to 25 myself, but is there a way to make it do that automatically (e.g. 22 from the first response 3)?On top of each bar I have the count of each response. Is there a way to make it show the count, and in brackets the percent of that count compared to the total? E.g the percent of 22 out of the 51 responses in total would look like 22 (43%)
CodePudding user response:
To answer your question point by point.
- The
limits
argument of the scale can take a function (or in recent versions a lambda syntax formula), that takes the natural limits as a length 2 vector as input. You can write your own formula if you want to expand the maximum by 3. - You can use the
after_stat()
function to access computed variables, so you can format thecount
computed variable to your liking.
library(ggplot2)
df <- data.frame(
value = sample(LETTERS[1:5], 50, replace = TRUE)
)
ggplot(df, aes(value))
geom_bar()
geom_text(
stat = "count", vjust = -1,
aes(label = after_stat(
paste0(count, " (", count * 100 / sum(count), "%)")
))
)
scale_y_continuous(
limits = ~ c(0, .x[2] 3)
)
Created on 2021-11-01 by the reprex package (v0.3.0)