ML_Enthousiast
ML_Enthousiast

Reputation: 1269

Positionning labels on a grouped bar chart with ggplot

I am having issues positionning my labels for my grouped bar chart.
Below a reproducible example, and on the image you can see where I would like the labels to be placed.

Not all on the same line, but each label aligned with each of the 3 bar chart, and ideally each label placed right above each corresponding bar chart.

Any idea how to achieve this? I want to keep a grouped bar chart and not a stacked bar chart.

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

enter image description here

Upvotes: 0

Views: 1731

Answers (1)

stefan
stefan

Reputation: 125228

As you use position_dodge for the bars use it for the labels as well, where I use width = .9, which is the default for bars:

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))

Upvotes: 2

Related Questions