使用 ggplot 在分组条形图上定位标签

Positionning labels on a grouped bar chart with ggplot

我在为分组条形图定位标签时遇到问题。
在可重现的示例下方和图像上,您可以看到我希望放置标签的位置。

并非都在同一行上,但每个标签都与 3 个条形图中的每一个对齐,理想情况下每个标签都位于每个相应条形图的正上方。

知道如何实现吗?我想保留分组条形图而不是堆叠条形图。

data_F <- "https://raw.githubusercontent.com/max9nc9/Temp/main/temp.csv"
data_F <- read.csv(data_F, sep = ";")
colnames(data_F) <- c("Month_Year", "Type", "Amount")
data_F$Amount <- as.numeric(data_F$Amount)

Final_Graph <-
  ggplot(data_F, aes(x = Month_Year, y = Amount, label = Amount, fill = Type)) +
  geom_bar(position="dodge", stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5), color = "black") +
  theme(axis.text.x = element_text(angle = 90)) +
  scale_fill_manual(values = c("#e62200", "#00c41d", "#f7b21e")) +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.subtitle = element_text(hjust = 0.5))

Final_Graph

当您将 position_dodge 用于条形图时,也将其用于标签,我使用 width = .9,这是条形图的默认设置:

data_F <- "https://raw.githubusercontent.com/max9nc9/Temp/main/temp.csv"
data_F <- read.csv(data_F, sep = ";")
colnames(data_F) <- c("Month_Year", "Type", "Amount")
data_F$Amount <- as.numeric(data_F$Amount)

library(ggplot2)

ggplot(data_F, aes(x = Month_Year, y = Amount, label = Amount, fill = Type)) +
  geom_bar(position="dodge", stat = "identity") +
  geom_text(size = 3, position = position_dodge(width = .9), vjust = 0, color = "black") +
  theme(axis.text.x = element_text(angle = 90)) +
  scale_fill_manual(values = c("#e62200", "#00c41d", "#f7b21e")) +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.subtitle = element_text(hjust = 0.5))