R ggplot-如何在条形图上方旋转计数 [英] R ggplot - How to rotate count above barchart
问题描述
我的数据框 df
看起来像这样
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")
然后我用
ggplot(ydf,aes(x =年,y =频率,填充=频率))+ 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一样将Frequency 90旋转.我做了很多谷歌搜索,但是没有运气.我是R的新手,所以我的绘图代码可能不正确或可以做得更好.请注意,我喜欢将图例显示为一个条,并且不想更改它.
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.
推荐答案
按照@ markus,nudge_y和标签角度建议使用geom_col:
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
由 reprex软件包(v0.3.0)创建于2020-12-27 sup>
Created on 2020-12-27 by the reprex package (v0.3.0)
这篇关于R ggplot-如何在条形图上方旋转计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!