Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

r - Stacked bar chart with group by and facet

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 enter image description here

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

enter image description here

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...