Geom_Text没有在Geom_Bar上定位标签

时间:2019-07-02 21:02:52

标签: r ggplot2 geom-bar geom-text

我正在跟踪this post中的代码,但对我来说却不一样。这是我的代码和下面的屏幕截图。您能帮我将标签居中放置在条形上方吗?

Click Here - Screenshot

p <- ggplot(data=mrc, aes(x = Year, y = Total, fill = Year)) + 
  geom_bar(stat="identity", position = "dodge") +
  geom_text(
        aes(x = Year, y = Total, label = Total),
        position = position_dodge(width = 1),
        vjust = -0.5, size = 3
  ) +
  theme_bw() +
  scale_fill_manual(values = c("#115740","#B9975B","#D0D3D4","#F0B323")) +
  theme(axis.title.x=element_blank(),
        axis.title.y=element_blank(),
        legend.position = "none",
        plot.title = element_text(hjust = 0.5, face = "bold", colour = "#B9975B")) +
  ggtitle("Petitions") 

ggplotly(p)

1 个答案:

答案 0 :(得分:0)

The issue这里是ggplotly。一种解决方案是使用style(textposition = "top")

重新创建数据:

mrc <- data.frame(Year = c("2015-16", "2016-17", "2017-18", "2018-19"),
                  Total = c(225, 461, 471, 230),
                  stringsAsFactors = FALSE)

运行代码的第一部分以生成p

p

enter image description here

一切都很好。但结果使用ggplotly

ggplotly(p)

enter image description here

添加style()

ggplotly(p) %>% style(textposition = "top")

enter image description here