0

I'm facing a problem with adding labels for the grouped bar plot in R ggplot2.

The bars on my plot are grouped, bars inside the groups have the same color (required!), each bar inside the group corresponds to a date.

Image of my current plot:

enter image description here

I need to add a date below each bar, so they are below the horizontal axis. But at the same point I don't need the names for the gropus. So, I only need dates below each bar.

My dataframe looks like this:

df <- data.frame(
dates = c('2022-01-01', '2022-01-01', '2022-01-01', '2022-01-01', '2022-01-01', '2022-02-01', '2022-02-01', '2022-02-01', '2022-02-01', '2022-02-01', '2022-03-01', '2022-03-01', '2022-03-01', '2022-03-01', '2022-03-01'),
group = c('A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E'),
value = c(1.4, 0.2, 0.3, 0, -0.2, 1.4, 0.3, 0.2, 0.2, 0.5, 1, 0, 0, 0, 0.4)
)

The code for creating the plot is like this:

ggplot(df, aes(group=dates, y=value, x=group, fill=group)) +
    geom_bar(width = 0.8, position = position_dodge(width = 0.9), stat="identity", color="black") +
    
    scale_fill_manual(values=c("#E03225", "#EB6121", "#7F7F7F", "#F5F5F5", "#000000"), name = "") +
    scale_x_discrete(labels= c("", "", "", "", "")) + # switch off labels for 'group'
    xlab("") + 
    ylab("") + 
    theme_minimal() + 
    theme(legend.position="bottom", legend.direction = "horizontal")

I've tried several solutions: "scale_x_continuous" from here (Axis labels for each bar and each group in bar charts with dodged groups), and also adding labels by "facet_wrap" or "facet_grid". The first one conflicts with my scale_x_discrete and the latter two regroup the plot (which is expected).

stefan
  • 90,330
  • 6
  • 25
  • 51
ASKovtun
  • 1
  • 1

1 Answers1

0

One option would be to use facetting, i.e. facet by group which allows to map dates on x. To get rid of the groups labels I removed the strip text via theme options. Finally, to avoid overlapping date labels I have put them on two rows using guide_axis(n.dodge = 2).

library(ggplot2)

ggplot(df, aes(y = value, x = dates, fill = group)) +
  geom_bar(width = 0.8, position = position_dodge(width = 0.9), stat = "identity", color = "black") +
  scale_fill_manual(values = c("#E03225", "#EB6121", "#7F7F7F", "#F5F5F5", "#000000"), name = "") +
  scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
  facet_wrap(~group, nrow = 1) +
  labs(x = NULL, y = NULL) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    legend.direction = "horizontal",
    strip.text.x = element_blank()
  )

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51