How could I change the type of bar plot?

Hi,
How could I change the type of bar plot? From Stacked Bar Charts to Grouped column chart. And let the legend show the pattern of barplot completely(it seems A legend needs).
Thank you for your help in advance.

library(tidyverse)

set.seed(123)
data <- data.frame(
  group = rep(c("A", "B"), each = 5),
  category = rep(c("cat1", "cat2", "cat3", "cat4", "cat5"), 2),
  value = sample(1:10, 10, replace = TRUE)
)
data
ggplot(data, aes(x = category, y = value)) +
  geom_bar(position = "dodge", stat = "identity")+
  geom_bar_pattern(stat = "identity",
                   pattern_color = "white",
                   pattern_fill = "black",
                   aes(pattern = group))+
  scale_fill_manual(values = c("lightblue", "salmon")) +
  labs(x = "category", y = "value", fill = "group") +
  theme_minimal()

Created on 2023-04-19 with reprex v2.0.2

To get a grouped column chart, remove the line for geom_bar() and add position = 'dodge' to geom_bar_pattern(). Then, increase the legend key size in order for the pattern to show for group A.

ggplot(data, aes(x = category, y = value)) +
  geom_bar_pattern(stat = "identity",
                   position = 'dodge',
                   pattern_color = "white",
                   pattern_fill = "black",
                   aes(pattern = group))+
  scale_fill_manual(values = c("lightblue", "salmon")) +
  labs(x = "category", y = "value", fill = "group") +
  theme_minimal() +
  theme(legend.key.size = unit(1.25, 'cm'))

Created on 2023-04-18 with reprex v2.0.2

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.