简体   繁体   English

x轴上方和下方计数的堆积条形图?

[英]Stacked Bar-chart with count above and below x-axis?

I have a large data set with several categories, and one decider column with values YES and NO.我有一个包含多个类别的大型数据集,以及一个值为 YES 和 NO 的决策列。 I want to plot a stacked bar chart where the decider column stacks the result above the x-axis for YES values and below the x-axis for NO.我想 plot 堆叠条形图,其中决定列将结果堆叠在 x 轴上方的 YES 值和 x 轴下方的 NO。 How can I do this?我怎样才能做到这一点?

I made a mock-up below showing what I want.我在下面做了一个模型来展示我想要的东西。 Note that all categories can have a YES and a NO value.请注意,所有类别都可以有一个 YES 和一个 NO 值。

例子

You can use dplyr to convert your "Yes" values into positive counts and your "No" values to negative counts, then use a stacked geom_col .您可以使用dplyr将“是”值转换为正数,将“否”值转换为负数,然后使用堆叠的geom_col

You haven't provided any sample data, so I've made some up for the following reprex:您还没有提供任何示例数据,所以我为以下代表做了一些补充:

set.seed(69)
df <- data.frame(Var1 = sample(LETTERS[1:6], 500, replace = TRUE, prob = 1:6),
                 Var2 = as.factor(sample(1:6, 500, replace = TRUE, prob = 6:1)),
                 YesNo = sample(c("Yes", "No"), 500, TRUE))
head(df)
#>   Var1 Var2 YesNo
#> 1    D    1   Yes
#> 2    C    3    No
#> 3    D    6   Yes
#> 4    B    3   Yes
#> 5    E    1    No
#> 6    B    1   Yes

The data manipulation and plot would look like this:数据操作和 plot 看起来像这样:

library(dplyr)
library(ggplot2)

df %>% 
  group_by(Var1, Var2) %>% 
  summarize(Yes = sum(YesNo == "Yes"), No = -sum(YesNo == "No")) %>%
  ggplot(aes(x = Var2, y = Yes, fill = Var1)) + 
    geom_col(position = "stack") +
    geom_col(aes(y = No), position = "stack") +
    geom_hline(aes(yintercept = 0)) + 
    labs(y = paste("No", "Yes", sep = paste(rep(" ", 20), collapse = " ")))

Created on 2020-05-14 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2020 年 5 月 14 日创建

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

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