R中使用ggplot2将行作为堆积的条形图 [英] Rows As Stacked Bar Plot Using ggplot2 In R
问题描述
我刚刚开始使用 R
中的 ggplot2()
(数据可视化)开始。我的数据在行格式下有不同的工作量。这些列中的每列都有四个我要绘制为堆积条形图的参数,最好使用 ggplot2()
。
I am just getting started with ggplot2()
(data visualization) in R
. The data I have has different workloads in row format. Each of these column has four different parameters that I want to plot as stacked bar plot, preferably using ggplot2()
.
可重现数据
Workload P1 P2 P3 P4
W1 0.3 0.2 0.4 0.1
W2 0.5 0.1 0.3 0.1
W3 0.2 0.3 0.4 0.1
W4 0.3 0.2 0.5 0.1
我想将工作量
绘制为 x轴
然后绘制 P1
, P2
, P3
和 P4
将在 y轴
上堆叠每个工作负载。
I want to plot Workload
as x-axis
and then P1
, P2
, P3
and P4
will be stacked for each of the workload on y-axis
.
我尝试了很多事情,但是我与 ggplot2()
参数和参数纠缠不清。如果有人可以建议我该怎么做,那将是有帮助的。
I tried many things, but I am getting tangled with ggplot2()
parameters and arguments. If anyone can suggest how I can do this, it will be helpful.
谢谢。
推荐答案
更改为高级长格式(在这里我使用 tidyr :: gather
),然后将您的列映射到美学,并使用堆叠位置的列几何(栏是一种特殊情况,它计算观察值的数量)。
Change to the "superior" long format (here I use tidyr::gather
), then map your columns to aesthetics, with a column geom with stacked position (bar is a special case which counts number of observations).
library(tidyverse)
df <- read.table(text = "
Workload P1 P2 P3 P4
W1 0.3 0.2 0.4 0.1
W2 0.5 0.1 0.3 0.1
W3 0.2 0.3 0.4 0.1
W4 0.3 0.2 0.5 0.1", header = TRUE)
df_long <- df %>%
gather(P, value, P1:P4)
ggplot(df_long, aes(x = Workload, y = value, fill = P)) +
geom_col(position = position_stack())
这篇关于R中使用ggplot2将行作为堆积的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!