简体   繁体   English

如何创建以百分比计算的数字的堆叠条形图?

[英]How to create a stacked barplot with numbers calculated in percentages?

I want to create a stacked barplot for data similar to the following.我想为类似于以下的数据创建一个堆叠的条形图。 The barplot should represent the percentage of patients by race visiting each of the clinics as well as it should show the respective numbers.条形图应代表按种族访问每个诊所的患者百分比,并应显示各自的数字。

在此处输入图片说明

Can anyone please help me with this as I am a novice with R?任何人都可以帮我解决这个问题,因为我是 R 的新手吗?

Here is a link from a place I like. 这是我喜欢的地方的链接。 Enjoy.享受。

The bottom line is: in your geom_bar() , do this: geom_bar(position="fill", stat="identity") .底线是:在您的geom_bar() ,执行以下操作: geom_bar(position="fill", stat="identity")

Try this approach using ggplot2 and tidyverse functions.使用ggplot2tidyverse函数尝试这种方法。 As @r2evans mentioned please next time try creating a reproducible example with data.正如@r2evans提到的,下次请尝试使用数据创建一个可重现的示例。 Here the code.这里是代码。 You would need to compute the position for labels and then sketch the code:您需要计算标签的位置,然后绘制代码:

library(ggplot2)
library(dplyr)
library(tidyr)
#Code
df %>% pivot_longer(-Race) %>%
  group_by(name) %>% mutate(Pos=value/sum(value)) %>%
  ggplot(aes(x=name,y=value,fill=Race))+
  geom_bar(stat = 'identity',position = 'fill')+
  geom_text(aes(y=Pos,label=value),position = position_stack(0.5))+
  scale_y_continuous(labels = scales::percent)

Output:输出:

在此处输入图片说明

Some data used:使用的一些数据:

#Data
df <- structure(list(Race = c("Caucasian/White", "African American", 
"Asian", "Other"), `Clinic A` = c(374, 820, 31, 108), `Clinic B` = c(291, 
311, 5, 15), `Clinic C` = c(330, 206, 6, 5), `Clinic D` = c(950, 
341, 6, 13)), class = "data.frame", row.names = c(NA, -4L))

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

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