GGplot:两个并排堆叠的条形图(不是小平面)

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

我正在尝试使用 R 中的 ggplot2 重新创建此解决方案:

diamonds %>% 
  filter(color=="D"|color=="E"|color=="F") %>% 
  mutate(dummy=rep(c("a","b"),each=13057)) %>% 
  ggplot(aes(x=color,y=price))+
  geom_bar(aes(fill=clarity),stat="identity",width=.25)+
  facet_wrap(~cut)

我向 diamonds 数据集添加了一个名为 dummy 的新变量。 dummy 有两个值:ab。假设我想通过为 color 的每个值创建一个条形图来比较这两个值,该条形图具有两个彼此相邻的堆叠条(一个代表 dummy 的每个值)。我如何操作它,以便 color 的每个值都有两个堆积条?

我认为它会涉及 position dodge and/or 一个单独的 legend,但到目前为止我一直没有成功。我 不想 添加另一个方面 - 我希望它们都在每个方面的 x 轴上。

类似于 post 中的方法,您已链接一个选项来实现您想要的结果,方法是通过两个 geom_col 并将 x 轴变量转换为 numeric 之类的所以。但是,这样做需要通过 scale_x_continuous 手动设置中断和标签。此外,我使用 ggnewscale 包添加第二个填充比例:

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)