带分组依据和构面的堆叠条形图 [英] Stacked bar chart with group by and facet

查看:73
本文介绍了带分组依据和构面的堆叠条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据如下:

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进行分组.

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)

我得到的输出是

我需要的是栏上的区别,该区别显示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_timeoperation_time将数据帧从宽格式转换为长格式,因为它们是相同的变量.在这里,我将新列称为Type.要在x轴上绘制system,我们可以使用fill分配不同的颜色. geom_col是绘制堆积条形图的命令. facet_grid是创建构面的命令.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆