Stacked bar chart with group by and facet

2020-04-19 08:07发布

问题:

My data looks like this:

system  operation_type  prep_time   operation_time
A       x               0.7         1.4
A       y               0.11        2.3
A       z               1.22        6.7
B       x               0.44        5.2
B       y               0.19        2.3
B       z               3.97        9.5
C       x               1.24        2.4
C       y               0.23        2.88
C       z               0.66        9.7

I would like to have a stacked chart on prep_time and operation time that gives me total_time grouped by system and then faceted by operation_type.

My code looks like this for now.

library(ggplot2)

df <- read.csv("test.csv", strip.white=T)
plot <- ggplot(df, aes(x=system,y=(prep_time+operation_time))) + geom_bar(stat="identity") + facet_grid(.~operation_type)

The output I get is

What I need is a distinction in bar that shows what part of the total_time is prep_time and what is operation_time. I thought of adding a legend and having different colors for prep_time and operation_time but I cannot figure out how I can do that.

回答1:

This should give you a start. You need to convert your data frame from wide format to long format based on prep_time and operation_time because they are the same variable. Here I called new column Type. To plot the system on the x-axis, we can use fill to assign different color. geom_col is the command to plot a stacked bar chart. facet_grid is the command to create facets.

library(tidyr)
library(ggplot2)

df2 <- df %>% gather(Type, Time, ends_with("time"))

ggplot(df2, aes(x = system, y = Time, fill = Type)) +
  geom_col() +
  facet_grid(. ~ operation_type)

DATA

df <- read.table(text = "system  operation_type  prep_time   operation_time
A       x               0.7         1.4
                 A       y               0.11        2.3
                 A       z               1.22        6.7
                 B       x               0.44        5.2
                 B       y               0.19        2.3
                 B       z               3.97        9.5
                 C       x               1.24        2.4
                 C       y               0.23        2.88
                 C       z               0.66        9.7",
                 header = TRUE, stringsAsFactors = FALSE)