在R中绘制二进制列总和的图形,然后用一定比例的分类变量覆盖这些列 [英] Graphing binary column sums in R, and then overlay those columns with a ratio of categorical variables

查看:114
本文介绍了在R中绘制二进制列总和的图形,然后用一定比例的分类变量覆盖这些列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中绘制定性策略分析数据.我的数据库中每个策略都有一行,然后是二进制变量的列,如果满足该条件,则条件将被编码为"1".最后,每一行还包含一栏,说明该政策是强制性,自愿性还是部分性.

I am trying to graph qualitative policy analysis data in R. My database has one row for each policy, and then columns for binary variables, conditions that are coded "1" if that condition is met. Finally, each row also contains a column for whether that policy is mandatory, voluntary, or partial.

我想创建一个对各列求和的条形图,然后根据总和的百分比是强制性,自愿性还是部分性在条形中显示颜色.

I want to create a bar chart that sums the columns, then colors in the bars according to what percentage of the sum is Mandatory, Voluntary, or Partial.

理想的结果是创建一个如下所示的条形图,但根据强制性,自愿性或部分性政策的比例按颜色进行编码

The ideal outcome would be to create a bar chart like the one below, but coded by color according to the ratio of Mandatory, Voluntary, or Partial policies

以下是一些格式相同的示例数据:

Here is some sample data in the same format:

df<- data.frame(ID=c(1,2,3,4,5,6),
            policy=c("Policy A", "Policy B", "Policy C", "Policy D", 
            "Policy E","Policy F" ),
            Data_collection= c(1, 0, 0, 1, 1, 0),
            Handling_release= c(0, 1, 0, 1, 0, 1),
            Gear_modification= c(1, 0, 0, 1, 1, 0),
            Stength=c("M", "V", "M", "P", "P", "M"),
            stringsAsFactors=FALSE)

推荐答案

您似乎真的需要将数据重塑为适当的整齐格式,以使绘制更加容易.例如,您可以

It looks like you really need to reshape your data to a proper tidy format to make plotting easier. For example you could do

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

df %>% 
  pivot_longer(Data_collection:Gear_modification) %>% 
  filter(value==1) %>% 
  ggplot(aes(name, fill=Stength)) +
  geom_bar()

对于提供的示例数据,这给出了

For the sample data provided this gives

要在顶部添加总计,请参见以下现有问题:

For adding the total on top see this existing question: draw the sum value above the stacked bar in ggplot2

这篇关于在R中绘制二进制列总和的图形,然后用一定比例的分类变量覆盖这些列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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