Geom_text在栏的顶部未对齐

时间:2019-11-29 17:47:38

标签: r ggplot2

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

enter image description here 有人有什么想法可以将它们排列在栏的顶部吗?

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

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)

1 个答案:

答案 0 :(得分:1)

在这里可以通过重新排列数据帧并调整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)

enter image description here