为多个变量制作堆积条形图 - R 中的 ggplot2 [英] Making a stacked bar plot for multiple variables - ggplot2 in R

查看:42
本文介绍了为多个变量制作堆积条形图 - R 中的 ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ggplot2 中制作堆积条形图时遇到了一些问题.我知道如何使用 barplot() 制作一个,但我想使用 ggplot2,因为很容易使条形图具有相同的高度(如果我没记错的话,使用 'position = 'fill'').

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

我想要的是在 X 轴上具有类别 A、B 和 C 的图,对于每个类别,V1、V2、V3 和 V4 的值在 Y 轴上彼此堆叠.我见过的大多数图表都只在 Y 轴上绘制了一个变量,但我确信人们可以以某种方式做到这一点.

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.

我怎么能用 ggplot2 做到这一点?谢谢!

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

现在绘图,使用名为 variable 的变量来确定每个条的填充颜色.

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

(代码更新为使用 scales 包,自 ggplot2 v0.9 起就需要.)

( Code updated to use scales packages, as required since ggplot2 v0.9.)

这篇关于为多个变量制作堆积条形图 - R 中的 ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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