首页 > 解决方案 > 在整个条形图中覆盖文本标签

问题描述

在此处输入图像描述

如上图所示,如何覆盖标签并将其在整个条形图中居中?

这是我尝试过的:

ggplot(my_NYC_Crimes, aes(x=Year, y=Crime.total)) + 
geom_bar(stat = "identity", fill= "#b43a74") +
scale_y_continuous(labels = scales::comma) + theme_minimal() +
theme(axis.title.x = element_blank()) + theme(axis.title.y = element_blank()) 
+ theme_void() + geom_text(aes(label = "Major felonies"), position = 
position_stack(0.5), color = "white")[enter image description here][1]

标签: rggplot2bar-chart

解决方案


如果没有原始数据(或其样本),回答这类问题总是比较困难的。但是,假设您的数据看起来像这样:

my_NYC_Crimes <- data.frame(Year = 2001:2019,
Crime.total = c(seq(32, 20, -1.1), 21, 23, 25, 23, 21, 20, 18, 17) * 1000)

那么关键是要意识到您不希望将geom_label其映射到位置美学。您可以通过简单地指定 x、y 位置来添加它,而无需将它们包含在aes调用中:

ggplot(my_NYC_Crimes, aes(x = Year, y = Crime.total)) + 
  geom_col(fill= "#b33877") +
  scale_y_continuous(breaks = 1:3 * 10000) +
  geom_label(label = "Major felonies", x = 2010, y = 7500, size = 10,
             color = "white", fill = "#b33877", label.size = 0) +
  theme_void() +
  theme(panel.grid.major.y = element_line())

在此处输入图像描述


推荐阅读