Home > Enterprise >  GGplot: Two stacked bar plots side by side (not facets)
GGplot: Two stacked bar plots side by side (not facets)

Time:11-01

I am trying to recreate this solution using ggplot2 in R: enter image description here

I added a new variable to the diamonds dataset called dummy. dummy has two values: a and b. Let's say I want to compare these two values by creating a bar graph that has two stacked bars right next to each other (one for each value of dummy) for each value of color. How can I manipulate this such that there are two stacked bars for each value of color?

I think it would involve position dodge and/or a separate legend, but I've been unsuccessful so far. I do not want to add another facet - I want these both on the x-axis within each facet.

CodePudding user response:

Similiar to the approach in the post you have linked one option to achieve your desired result would be via two geom_col and by converting the x axis variable to a numeric like so. However, doing so requires to set the breaks and labels manually via scale_x_continuous. Additionally I made use of the ggnewscale package to add a second fill scale:

library(ggplot2)
library(dplyr)

d <- diamonds %>%
  filter(color == "D" | color == "E" | color == "F") %>%
  mutate(dummy = rep(c("a", "b"), each = 13057))

ggplot(mapping = aes(y = price))  
  geom_col(data = filter(d, dummy == "a"), aes(x = as.numeric(color) - .15, fill = clarity), width = .3)  
  scale_fill_viridis_d(name = "a", guide = guide_legend(order = 1))  
  scale_x_continuous(breaks = seq_along(levels(d$color)), labels = levels(d$color))  
  ggnewscale::new_scale_fill()  
  geom_col(data = filter(d, dummy == "b"), aes(x = as.numeric(color)   .15, fill = clarity), width = .3)  
  scale_fill_viridis_d(name = "b", option = "B", guide = guide_legend(order = 2))  
  facet_wrap(~cut)

  • Related