如何在R中的分组条形图中生成堆叠条形图 [英] How to produce stacked bars within grouped barchart in R
问题描述
我有以下图表
test <- data.frame(person=c("A", "B", "C", "D", "E"),
value1=c(100,150,120,80,150),
value2=c(25,30,45,30,30) ,
value3=c(100,120,150,150,200))
我想为每个人绘制一个分组条形图(水平),其中一个条形表示 value1,另一个条形表示 value2 和 value3.有没有办法使用 ggplot2 来做到这一点?我可以使用 facet 来绘制这些单独的图表吗?
I want to plot a grouped barchart (horizontal) for each person where one bar indicates value1 and the other bar is stack of value2 and value3. Is there a way with which I can do this using ggplot2? Can I use facets to plot these individual graphs one below the other?
推荐答案
这是我想出来的,类似于这里提出的解决方案:分组条形图中的堆积条形
Here is what I came up with, similar to a solution proposed here: stacked bars within grouped bar chart
融化
data.frame
并添加一个新列cat
library(reshape2) # for melt
melted <- melt(test, "person")
melted$cat <- ''
melted[melted$variable == 'value1',]$cat <- "first"
melted[melted$variable != 'value1',]$cat <- "second"
绘制堆积图cat
vs value
,按person
分面.您可能需要调整标签以获得所需的内容:
Plot a stacked chart cat
vs value
, faceting by person
. You may need to adjust the labels to get what you want:
ggplot(melted, aes(x = cat, y = value, fill = variable)) +
geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ person)
这篇关于如何在R中的分组条形图中生成堆叠条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!