【问题标题】:Stacked bar chart with group by and facet带有分组依据和分面的堆积条形图
【发布时间】:2018-07-06 14:39:54
【问题描述】:

我的数据如下所示:

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 和 operation 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)

我得到的输出是

我需要的是条形图中的区别,它显示了总时间的哪一部分是准备时间,什么是操作时间。我想为 prep_time 和 operation_time 添加一个图例并使用不同的颜色,但我不知道该怎么做。

【问题讨论】:

  • 你到现在都做了什么?此外,请添加您的数据框的dput。

标签: r ggplot2 dplyr bar-chart facet


【解决方案1】:

这应该给你一个开始。您需要根据prep_time 和operation_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)

【讨论】:

  • 完美!这正是我所需要的。非常感谢,我一直在挠头很长时间才弄清楚这一点。 ggplot 的学习曲线当然很长!
猜你喜欢
  • 2015-06-28
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
相关资源
最近更新 更多