Rows As Stacked Bar Plot Using ggplot2 In R

試著忘記壹切 提交于 2020-01-22 00:46:14

问题


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().

Reproducible Data

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

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.

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.

Thanks.


回答1:


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())



来源:https://stackoverflow.com/questions/50380229/rows-as-stacked-bar-plot-using-ggplot2-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!