1

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.

enter image description here

Can anyone please help me with this as I am a novice with R?

Duck
  • 39,058
  • 13
  • 42
  • 84
amty
  • 113
  • 1
  • 10
  • What have you tried or researched? [`"R" stacked barplot](https://www.google.com/search?q="R"+stacked+barplot) has several good examples with code to reproduce. – r2evans Nov 17 '20 at 12:56

2 Answers2

1

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").

Érico Patto
  • 1,015
  • 4
  • 18
1

Try this approach using ggplot2 and tidyverse functions. As @r2evans mentioned please next time try creating a reproducible example with data. 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:

enter image description here

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))
Duck
  • 39,058
  • 13
  • 42
  • 84