为多个变量制作堆叠条形图 - g中的ggplot2 [英] Making a stacked bar plot for multiple variables - ggplot2 in R
问题描述
在ggplot2中制作堆叠条形图时遇到一些问题。我知道如何用barplot()创建一个,但是我想使用ggplot2,因为它很容易让bar具有相同的高度('position ='fill'',如果我没有弄错的话)。
我的问题是我有多个变量,我想在彼此之上绘图;我的数据如下所示:
dfr < - data.frame(
V1 = c(0.1,0.2, (0.3,0.6,0.5),
V4 = c(0.5,0.1,0.7),
row.names = LETTERS [1:3]
)
我想要的是在X轴上具有类别A,B和C的绘图,并且对于其中的每一个,V1,V2,V3和V4的值在Y轴上彼此堆叠。我所看到的大多数图表在Y轴上只绘制了一个变量,但我确信某人可以以某种方式做到这一点。
我怎样才能用ggplot2做到这一点?谢谢!
首先进行一些数据操作。
dfr $ category< - row.names(dfr)将数据类型作为变量添加并将数据融化为长格式。
mdfr < - melt(dfr,id.vars =category)
现在使用名为变量
的变量来确定每个栏的填充颜色。
(p <-ggplot(mdfr,aes(category,value,fill = variable))+
geom_bar(position =fill,stat =identity) +
scale_y_continuous(labels = percent)
)
(编辑:代码已更新使用 scales
包,按照ggplot2 v0.9的要求。)
I have some problems with making a stacked bar chart in ggplot2. I know how to make one with barplot(), but I wanted to use ggplot2 because it's very easy to make the bars have the same height (with 'position = 'fill'', if I'm not mistaken).
My problem is that I have multiple variables that I want to plot on top of each other; my data looks like this:
dfr <- data.frame(
V1 = c(0.1, 0.2, 0.3),
V2 = c(0.2, 0.3, 0.2),
V3 = c(0.3, 0.6, 0.5),
V4 = c(0.5, 0.1, 0.7),
row.names = LETTERS[1:3]
)
What I want is a plot with categories A, B, and C on the X axis, and for each of those, the values for V1, V2, V3, and V4 stacked on top of each other on the Y axis. Most graphs that I have seen plot only one variable on the Y axis, but I'm sure that one could do this somehow.
How could I do this with ggplot2? Thanks!
First, some data manipulation. Add the category as a variable and melt the data to long format.
dfr$category <- row.names(dfr)
mdfr <- melt(dfr, id.vars = "category")
Now plot, using the variable named variable
to determine the fill colour of each bar.
library(scales)
(p <- ggplot(mdfr, aes(category, value, fill = variable)) +
geom_bar(position = "fill", stat = "identity") +
scale_y_continuous(labels = percent)
)
(EDIT: Code updated to use scales
packages, as required since ggplot2 v0.9.)
这篇关于为多个变量制作堆叠条形图 - g中的ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!