创建堆叠条形图,其中每个堆叠的总和为 100% [英] Create stacked barplot where each stack is scaled to sum to 100%

查看:37
本文介绍了创建堆叠条形图,其中每个堆叠的总和为 100%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 data.frame:

I have a data.frame like this:

df <- read.csv(text = "ONE,TWO,THREE
                       23,234,324
                       34,534,12
                       56,324,124
                       34,234,124
                       123,534,654")

我想生成一个看起来像这样的百分比条形图(在 LibreOffice Calc 中制作):

I want to produce a percent bar plot which looks like this (made in LibreOffice Calc):

因此,应该对条形进行标准化,以便所有堆栈具有相同的高度并且总和为 100%.到目前为止,我所能得到的只是一个堆积的条形图(不是百分比),使用:

Thus, the bars should be standarized so all stacks have the same height and sums to 100%. So far all I have been able to get is is a stacked barplot (not percent), using:

barplot(as.matrix(df))

有什么帮助吗?

推荐答案

这是一个使用 ggplot 包(版本 3.x)的解决方案,以及您目前获得的解决方案.

Here's a solution using that ggplot package (version 3.x) in addition to what you've gotten so far.

>

我们使用 geom_barposition 参数设置为 position = "fill".如果您想使用 position_fill() 的参数(vjustreverse).

We use the position argument of geom_bar set to position = "fill". You may also use position = position_fill() if you want to use the arguments of position_fill() (vjust and reverse).

请注意,您的数据采用宽"格式,而 ggplot2 要求它采用长"格式.因此,我们首先需要收集数据.

Note that your data is in a 'wide' format, whereas ggplot2 requires it to be in a 'long' format. Thus, we first need to gather the data.

library(ggplot2)
library(dplyr)
library(tidyr)

dat <- read.table(text = "    ONE TWO THREE
1   23  234 324
2   34  534 12
3   56  324 124
4   34  234 124
5   123 534 654",sep = "",header = TRUE)

# Add an id variable for the filled regions and reshape
datm <- dat %>% 
  mutate(ind = factor(row_number())) %>%  
  gather(variable, value, -ind)

ggplot(datm, aes(x = variable, y = value, fill = ind)) + 
    geom_bar(position = "fill",stat = "identity") +
    # or:
    # geom_bar(position = position_fill(), stat = "identity") 
    scale_y_continuous(labels = scales::percent_format())

这篇关于创建堆叠条形图,其中每个堆叠的总和为 100%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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