如何在 R 中分类变量的堆积条形图中包含 "total" 的条形图

How to include a bar for "total" in a stacked bar chart for categorical variable in R

我想在绘制分类变量的堆积条形图中包含一个“总计”条。我的问题的一个简化示例如下所示:

我有 3 个城市(伦敦、柏林、维也纳)和 2 种类型的游客。我可以使用下面的代码绘制每个城市不止一次(重复)的游客与只来一次(一次)的游客的比例。

现在,我想在同一图表中为一般情况下的份额 repeat/once 添加一个条形图(不是按城市)。不幸的是,我找不到有关如何执行此操作的任何提示。

如能提示如何添加此“总计栏”,我将不胜感激,因为我经常需要它。非常感谢您!

df <- data.frame("City"=c("Vienna","Vienna","London","London","Berlin", "London", "Berlin","Berlin","Vienna","Vienna","Vienna", "Vienna", "Berlin","Vienna","Vienna","Vienna"),"Type"=c("repeat","once","repeat","once","repeat","once", "repeat","once","repeat","once","repeat","repeat","repeat","repeat","repeat","once"))


df %>% 
  ggplot(aes(x=City, fill=Type), reorder(Type)) + 
  geom_bar(position="fill", alpha=0.75) +
  scale_fill_brewer(palette = "Paired") + 
  coord_flip()


´´´

您可以通过添加第二个 geom_bar 来实现您想要的结果,其中您在 x 上映射一个常量(例如字符串 Total)并通过 [= 设置类别的顺序14=]:

library(ggplot2)

ggplot(df, aes(x=City, fill=Type), reorder(Type)) + 
  geom_bar(position="fill", alpha=0.75) +
  geom_bar(aes(x = "Total"), position="fill", alpha=0.75) +
  scale_fill_brewer(palette = "Paired") + 
  scale_x_discrete(limits = c("Total", unique(df$City))) +
  coord_flip()