二进制列总计为ggplot中堆积的条形图的百分比

问题描述 投票:2回答:1

我已经尽一切努力将bar chart I made here从y轴的COUNT转换为y轴的PERCENT OF TOTAL(N = 142),但似乎无法弄清楚。我希望x轴是“ Spatial_Management”,“ Landing_ban”和“ Bycatch_rentention”列,而y轴是该列的值为1的策略百分比。并填充为“强度”。我想我需要预先做一个非常简单的编辑数据,我已经在下面尝试过了,但是没有用。

编辑:样本数据框:

    df<- data.frame(policy=c("Policy A", "Policy B", "Policy C", "Policy D", 
                     "Policy E","Policy F" ),
            Spatial_Management= c(0,1,1,0, 0,1),
            Landing_ban= c(0,1,1,0, 0,1),
            Bycatch_Retention= c(0,1,1,0, 0,1),
            Strength=c("M", "V", "M", "P", "P", "M"),
            stringsAsFactors=FALSE)

我当前的图形代码是:

df %>% 
  pivot_longer(Spatial_management:Bycatch_Retention) 
  filter(value==1) %>%
  ggplot(aes(x=factor(name, level=level_order), fill = factor(Strength)) +
                       y = (..count..)/sum(..count..)) +
 geom_bar()+
 stat_bin(geom = "text",
       aes(label = paste(round((..count..)/sum(..count..)*100), "%")),
       vjust = 5) +
 scale_y_continuous(labels = percent)

我知道这很简单,但会有所帮助!

r ggplot2 graphing
1个回答
2
投票

这里,您需要将数据框重整为更长的格式,然后计算值的数量除以策略的数量(此处等于您数据帧的行数):

library(tidyr)
library(dplyr)
library(ggplot2)
df %>% pivot_longer(-c(policy, Strength), names_to = "var", values_to = "val") %>%
  group_by(Strength, var) %>%
  summarise(Val = sum(val)/ nrow(df)) %>%
  ggplot(aes(x = var, y = Val, fill = Strength))+
  geom_col()+
  scale_y_continuous(labels = percent)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.