具有聚合数据的堆叠条形图(ggplot2) [英] stacked barplot with aggregated data (ggplot2)

查看:49
本文介绍了具有聚合数据的堆叠条形图(ggplot2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ggplot2存在一些主要问题.即使对您来说这可能是一个非常简单的问题,但我仍无法解决(我已经读过一本ggplot2-book,也在寻找stackoverflow).

最初,有一个由因子变量(国家/地区)和二分变量组成的数据集.不幸的是,我自己没有这种扩展格式的数据:我有两个变量"var1"和"var2".var1给出原始数据集中某个条件为true的个案数,而var2给出相同条件为false的个案数:

 国家|var1 |var2----------------------"A" |20 |30"B" |24 |53"C" |21 |24"D" |30 |66 

现在,我想生成一个堆叠的条形图,并在每个国家/地区内使用 y轴显示百分比(所有条形都应具有相同的高度)加上条形图中显示的绝对数字:

I have some major problems with ggplot2. Even though it might be a very easy question to you I couldnt manage yet to get it right (I have read a ggplot2-book and was looking on stackoverflow as well).

Orginally there was a dataset consisting of a factor variable (country) and a dichotomous variable. Unfortunately I dont have my data in this extended format myself: I have two variables "var1" and "var2". var1 gives the number of cases in the original dataset where a certain condition is true and var2 gives the number of cases where the same condition is false:

country | var1 | var2
----------------------
"A" | 20 | 30
"B" | 24 | 53
"C" | 21 | 24
"D" | 30 | 66

Now I'd like to produce a stacked barplot with a y-axis showing percentages within each country (all bars should have the same height) plus the absolute numbers displayed within the bars:

How it should look

I found out that if the data were in an extended format, I could use

ggplot(data=dataset)+geom_bar(aes(x=country, fill=variable), position='fill')

However, I only have aggregated data.

Could anyone please help me?

Thank you!

解决方案

A quick solution by first reshaping and then plotting:

library(ggplot2)
library(tidyr)

temp2 <- gather(temp, var, val, -country)
ggplot(temp2, aes(country, val, fill = var)) + 
  geom_col(position = 'fill') +
  geom_text(aes(label = val), position = position_fill(vjust = 0.5)) +
  scale_y_continuous(labels = scales::percent_format())

这篇关于具有聚合数据的堆叠条形图(ggplot2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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