I have a barplot in which I need to rotate the bar labels giving the Freq values:
library(dplyr)
ggplot(df,
aes(x = partcl, y = Pct)) +
geom_bar(stat="identity") +
# rotate x-axis labels by 90°:
theme(axis.text.x = element_text(angle = 90)) +
# plot `Freq` labels:
geom_text(aes(x = partcl, y = Pct, label = Freq, angle = 90, hjust = -0.2))
But there are two issues: first, the Freq labels are not fitted to the plotting area; instead the maximum Frequ label (for yeah well) is cut off. Second, the x-axis labels are not perfectly aligned with the x-axis ticks. How can these issues be fixed?
Data:
df <- structure(list(partcl = c("yeah well", "well yeah", "yeah yeah well",
"yeah well well", "yeah well yeah", "well yeah well", "well yeah yeah",
"well yeah yeah yeah", "yeah yeah yeah well", "well yeah well well"
), Freq = c(1515L, 408L, 52L, 20L, 17L, 11L, 8L, 2L, 2L, 1L),
Pct = c(74.3011280039235, 20.0098087297695, 2.55026974006866,
0.980872976949485, 0.833742030407062, 0.539480137322217,
0.392349190779794, 0.0980872976949485, 0.0980872976949485,
0.0490436488474743)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -10L))
>Solution :
For the ticks set vjust=.5 as by default theme_grey uses vjust=1. For the labels I don’t know of any out-of-the-box option except for increasing the expansion of the y scale:
library(ggplot2)
ggplot(df, aes(x = partcl, y = Pct)) +
geom_bar(stat="identity") +
# rotate x-axis labels by 90°:
theme(axis.text.x = element_text(angle = 90, vjust = .5)) +
# plot `Freq` labels:
geom_text(aes(x = partcl, y = Pct, label = Freq, angle = 90, hjust = -0.2)) +
scale_y_continuous(expand = expansion(mult = c(0, .15)))

