带有分组依据和构面的堆积条形图 [英] 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 和 operation time 的堆积图,它给我 total_time 按系统分组,然后按 operation_type 分面.
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)
我得到的输出是
我需要的是 bar 中的区别,它显示 total_time 的哪一部分是 prep_time,什么是 operation_time.我想添加一个图例并为 prep_time 和 operation_time 设置不同的颜色,但我不知道如何做到这一点.
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.
推荐答案
这应该给你一个开始.您需要根据 prep_time
和 operation_time
将数据帧从宽格式转换为长格式,因为它们是相同的变量.在这里,我将新列称为 Type
.要在 x 轴上绘制 system
,我们可以使用 fill
来分配不同的颜色.geom_col
是绘制堆积条形图的命令.facet_grid
是创建 facet 的命令.
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)
数据
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)
这篇关于带有分组依据和构面的堆积条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!