我在R
中运行以下RStudio
代码:
df2<-df1 %>%
gather(year, value, X2016:X2019) %>%
mutate(Mth = Mth %>% fct_rev() %>% fct_relevel('January')) %>%
group_by(Mth) %>%
mutate(y_pos = min(value) / 2)
df2$Mth <- as.character(df2$Mth)
df2$Mth <- factor(df2$Mth, levels=unique(df2$Mth))
df2$AsAt2 = factor(df2$AsAt, levels=c("D-150", "D-120", "D-90", "D-60", "D-30"))
g1<-df2 %>% filter(value!=0)%>%
ggplot(aes(
x = Mth,
y = value,
fill = Mth,
group = year
)) +
geom_col(
position = position_dodge(.65),
width = .5
) +
geom_text(aes(
y = value + max(value) * .03,
label = round(value * 100) %>% str_c('%')
),
position = position_dodge(.65), size=3.5
) +
geom_text(aes(
y = y_pos,
label = str_remove(year, 'X')
),
color = 'white',
angle = 90,
fontface = 'bold',
position = position_dodge(0.65), size=3.5
) +
scale_y_continuous(
breaks = seq(0, .9, .1),
labels = function(x) round(x * 100) %>% str_c('%')
) +
scale_fill_manual(values = c(
rgb(47, 85, 151, maxColorValue = 255),
rgb(255, 51, 51, maxColorValue = 255),
rgb(84, 130, 53, maxColorValue = 255),
rgb(244, 177, 131, maxColorValue = 255),
rgb(112, 48, 160, maxColorValue = 255)
)) +
theme(
plot.title = element_text(hjust = .5),
panel.background = element_blank(),
panel.grid.major.y = element_line(color = rgb(.9, .9, .9)),
axis.ticks = element_blank(),
legend.position = 'none'
) +
xlab('') +
ylab('') +
ggtitle('January to May')
g1 + facet_grid(rows = vars(AsAt2))
输出如下所示:
我的问题是,在某些情况下,栏中的Year(年份)标签会消失。我尝试将字体大小减小到3.5,但遇到了同样的问题。
有没有办法确保标签适合所有条形?
注意:我还添加了tibble
df2
的摘录。
>df2
# A tibble: 100 x 6
# Groups: Mth [5]
Mth AsAt year value y_pos AsAt2
<fct> <chr> <chr> <dbl> <dbl> <fct>
1 January D-150 X2016 0.26 0.12 D-150
2 February D-150 X2016 0.25 0 D-150
3 March D-150 X2016 0.27 0 D-150
4 April D-150 X2016 0.290 0 D-150
5 May D-150 X2016 0.27 0 D-150
6 January D-120 X2016 0.38 0.12 D-120
7 February D-120 X2016 0.25 0 D-120
8 March D-120 X2016 0.36 0 D-120
9 April D-120 X2016 0.35 0 D-120
10 May D-120 X2016 0.31 0 D-120