R ggplot - How to rotate count above barchart

Viewed 263

My dataframe df look like this

  Year Frequency
1 1975        86
2 1976        52
3 1977        53
4 1978        54
5 1979       301
6 1980       161

You can use this to reproduce the data.frame yourself:

ydf <- structure(list(Year = c(1975, 1976, 1977, 1978, 1979, 1980), 
                      Frequency = c(86, 52, 53, 54, 301, 161)),
                 row.names = c(NA, -6L), class = "data.frame")

And I plotted this graph with

ggplot(ydf, aes(x = Year, y = Frequency, fill=Frequency)) + geom_bar(stat = "identity") + geom_text(aes(label = Frequency), nudge_y=1, check_overlap=TRUE)+ scale_x_discrete(guide = guide_axis(angle = 90))

enter image description here

However as you can see the Frequency above the bars overlap. I tried to move the xaxis apart or rotate the Frequency 90 like the xlabel. I have done a lot of googling but no luck. I am pretty new to R so it's possible my plotting code is incorrect or could be done better. Note I like how the legend is displayed as one bar and don't want to change that.

1 Answers

Using geom_col as suggested by @markus, nudge_y, and angle for the labels:

library(ggplot2)

set.seed(42)
# Making up data
my_df <- tibble::tibble(year = 1:25, freq = sample(50:400, replace = T, size = 25))

# a variable to change nudge_y based on data's range
range = max(my_df$freq) -min(my_df$freq)

#Plotting
ggplot(my_df, aes(x = year, y = freq)) + 
  geom_col(aes(fill = freq)) + 
  geom_text(aes(label = freq), 
            angle = 90,
            nudge_y = range / 20) # the 20 may need adjusting for data with significantly different range

Created on 2020-12-27 by the reprex package (v0.3.0)

Related