简体   繁体   English

具有错误百分比的多个变量的图形堆栈栏

[英]Graph stack bar for multiple variables with wrong percentages

I am trying to get a graph stack bar for multiples variables to display percentages for each level in each variable, example:我正在尝试获取多个变量的图形堆栈栏,以显示每个变量中每个级别的百分比,例如:

Category  <- c(rep(c("A", "B", "C", "D"), times = 4))
Country  <- c(rep(c("Country A", "Country B", "Country C", "Country D", "Country F", "Country G"), times = 16))
Data      <- data.frame(Category, Country)

ggplot(Data,aes(x=factor(""),fill=factor(Category)))+
  geom_bar(position="fill")+
  geom_text(aes(label=scales::percent(..count../sum(..count..))), stat='count',position=position_fill(vjust=0.5))

percentages ok百分比没问题

在此处输入图像描述

Now I reshape my data frame, but lamentably I could not get the result expected, graph drisplay wrong percentages:现在我重塑了我的数据框,但遗憾的是我无法得到预期的结果,图形显示错误的百分比:

library(tidyr)
dflong= gather(Data, variable, freq)

ggplot(dflong,aes(x=factor(variable),fill=factor(freq)))+
  geom_bar(aes(x=factor(variable)),position="fill")+
  geom_text(aes(label=scales::percent(..count../sum(..count..))), stat='count',position=position_fill(vjust=0.5))

wrong percentages错误的百分比

在此处输入图像描述

You can pre-calculate the percentages before plotting.您可以在绘图前预先计算百分比。

library(dplyr)
library(ggplot2)

dflong %>%
  count(variable, freq, name = 'percentage') %>%
  group_by(variable) %>%
  mutate(percentage = prop.table(percentage) * 100) %>%
  ggplot() + aes(variable, percentage, fill = freq, 
                 label = paste0(round(percentage,2), '%')) + 
  geom_col() + 
  geom_text(position=position_stack(vjust=0.5))

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM