简体   繁体   中英

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. 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. 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.

例子

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 .

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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