繁体   English   中英

ggplot - 堆叠子组的 geom_bar

[英]ggplot - geom_bar with subgroups stacked

我正在尝试在 ggplot 中创建一个图表,其中 Round1 和 Round2 之间存在分隔,同时能够区分 Round2 中的茶点池。 我正在尝试不使用 facet wrap 或 grid do 来处理演示问题。

data.frame(Var1=c("old+","old+","old+","middle", "middle", "middle", "young", "young", "young"),
Round=c(1,2,2,1,2,2,1,2,2),
Refreshment=c(0,0,2,0,0,2,0,0,2),
Round_Refr=c(1.0,2.0,2.2,1.0,2.0,2.2,1.0,2.0,2.2),
pertotal=c(0.199, 0.196, 0.031, 0.459, 0.461, 0.020, 0.342, 0.343, 0.032))

我得到的最接近的是这个 - 但是它将每个类别(回合和年龄组作为X轴上的不同组)并在第二轮的顶部添加茶点轮,而不是将它视为它的一部分回合。

    ggplot(data, aes(x = (interaction(Round,Var1)), y = pertotal)) + 
       geom_bar(aes(fill = Round_Refr),stat = "identity",color="white")+
       scale_y_continuous(labels=percent)+ xlab("category")+
      ylab("Percent of ")+ labs(fill = "Round")+
       ggtitle("Plot")+
      theme(plot.title = element_text(hjust = 0.5)

在此处输入图像描述

你知道一种让它看起来更像下图的方法吗? 他们仍然按年龄/回合分组,并且在第 2 回合的茶点池与其他受访者之间存在界限。

在此处输入图像描述

这是可能的,但需要一些技巧。 您需要使用连续的 x 轴并将其标记为离散轴。 这需要一些数据操作:

library(tidyverse)

data %>%
  mutate(category = as.numeric(interaction(Round,Var1)),
         category = category + (category %% 2)/5 - 0.1,
         Round_cat = factor(Round_Refr, labels = c("1", "2", "Break")),
         Round_cat = factor(Round_cat, c("Break", "1", "2"))) %>%
  group_by(Var1, Round) %>%
  mutate(pertotal = ifelse(Round == 2 & Refreshment == 0,
                           pertotal - pertotal[Round_Refr > 2], pertotal)) %>%
  ggplot(aes(x = category, y = pertotal)) + 
  geom_col(aes(fill = Round_cat), color="white")+
  scale_y_continuous(labels=scales::percent)+ 
  scale_x_continuous(breaks = c(1.5, 3.5, 5.5), 
                     labels = levels(factor(data$Var1))) +
  xlab("category")+
  ylab("Percent of ")+ 
  labs(fill = "Round")+
  ggtitle("Plot")+
  scale_fill_brewer(palette = "Set1") +
  theme_light(base_size = 16) +
  theme(plot.title = element_text(hjust = 0.5))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM