首页 > 解决方案 > Geom_text 未在条形顶部对齐

问题描述

geom_text 标签不在下图中的条形顶部居中,尤其是最后两个标签(从左到右):

在此处输入图像描述 有没有人有任何想法将它们对齐在栏的顶部?

我尝试了一些代码更改,但我得到的最好的一个是:

my_df = data.frame(c('2017','2018','2019','2019','2019','2019','2020','2020'),
                   c(96, 91, 20.59, 47.37, 78.12, 10.00, 15.00 ,91),
                   c("No","No", "20%", "20%", "5%", "20%", "20%", "No"))        
colnames(my_df) <- c("Year","Threshold","Fee")

colors <- c("No"="seagreen3","5%"="yellow2","20%"="red4")

ggplot(data=my_df,
       aes(x=Year, y=Threshold, label=Threshold, group=Fee)) + 
  geom_col(aes(fill = Fee),
           position = position_dodge2(width = 1, preserve = "single")) + 
  geom_text(position = position_dodge2(width = 1), vjust=-0.5,size=2) + 
  scale_fill_manual(values = cores2)

标签: rggplot2

解决方案


这是通过重新排序数据框并调整 position_dodge2 元素的可能解决方案。

my_df<-my_df[order(my_df$Year, my_df$Fee), ]
ggplot(data=my_df,aes(x=Year, y=Threshold, label=Threshold)) +
  geom_col(aes(fill = Fee), width=1, position = position_dodge2(width = 1, preserve = "single")) +
  geom_text(position = position_dodge2(width = 1, preserve = "single"), vjust=-0.5, size=3)

在此处输入图像描述


推荐阅读