gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:07:38 25 4
gpt4 key购买 nike

我的数据是这样的:

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)

我得到的输出是 enter image description here

我需要的是条形图的区别,它显示 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)

enter image description here

数据

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)

关于r - 具有分组依据和分面的堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com