我的数据框df
看起来像这样
Year Frequency
1 1975 86
2 1976 52
3 1977 53
4 1978 54
5 1979 301
6 1980 161
Run Code Online (Sandbox Code Playgroud)
您可以使用它自己重现 data.frame:
Year Frequency
1 1975 86
2 1976 52
3 1977 53
4 1978 54
5 1979 301
6 1980 161
Run Code Online (Sandbox Code Playgroud)
我用以下方法绘制了这个图表
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))
然而,正如您所看到的,条形上方的频率重叠。我尝试将 x 轴移开或像 xlabel 一样将频率旋转 90 度。我已经做了很多谷歌搜索,但没有运气。我对 R 还很陌生,所以我的绘图代码可能不正确或者可以做得更好。请注意,我喜欢图例显示为一个栏的方式,并且不想更改它。
按照 @markus、nudge_y 和角度的建议使用 geom_col 作为标签:
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
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v0.3.0)于 2020-12-27 创建