具有分组依据和分面的堆积条形图

Stacked bar chart with group by and facet

我的数据是这样的:

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

我想在 prep_time 和操作时间上有一个堆叠图表,让我 total_time 按系统分组,然后按 operation_type 分面。

我的代码现在看起来像这样。

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)

我得到的输出是

我需要的是显示 total_time 的哪一部分是 prep_time 以及 operation_time 的哪一部分的区别。我想为 prep_time 和 operation_time 添加图例并使用不同的颜色,但我不知道该怎么做。

这应该给你一个开始。您需要根据 prep_timeoperation_time 将数据框从宽格式转换为长格式,因为它们是相同的变量。在这里,我将新列命名为 Type。要在 x 轴上绘制 system,我们可以使用 fill 分配不同的颜色。 geom_col 是绘制堆积条形图的命令。 facet_grid 是创建分面的命令。

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)

数据

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)