Home > Blockchain >  Add count lable to proportion plot
Add count lable to proportion plot

Time:04-01

I'm trying to add labels of counts to a proportion plot. Here is an example of my data and the code I've done so far.

df <- data.frame(E2A = c(1, 1, 2, 2, 1, 1, 2, 1, 2, NA),
                 E4A = c("P", "P", "P", NA, "G", "G", "H", "H", "H", "H"),
                 E5A = c("R", "R", "R", "R", "R", "O", "O", "O", "O", "O"),
                 Tooth = c(rep("P3", 9), NA))

ggplot(data = remove_missing(df, na.rm = TRUE, vars = c("E2A", "E4A", "E5A")))   # remove NA's for cleaner plot
  aes(x = E4A, fill = E5A)  
  geom_bar(position = "fill")  
  theme(plot.title = element_text(hjust = 0.5))  
  labs(x = "", y = "", fill = "Canal configurations")  
  theme_bw(base_size = 14)  
  theme(legend.position = "top")  
  theme(axis.text.y = element_text(size = 8))  
  theme(axis.text.x = element_text(size = 10))  
  guides(fill = guide_legend(nrow = 1, byrow = TRUE))  
  facet_wrap(.~ E2A, labeller = labeller(E2A = E2_lab), scales = "free")

Is there a way to add a count lable to the stacked barchart? Below is a mock up to help visualise what Im trying to do. goal!

CodePudding user response:

We could use stat = 'count' in geom_label to get that:

ggplot(data = remove_missing(df, na.rm = TRUE, vars = c("E2A", "E4A", "E5A")))   # remove NA's for cleaner plot
  aes(x = E4A, fill = E5A)  
  geom_bar(position = "fill")  
  geom_label(stat = 'count', aes(label = ..count..), position = position_fill(vjust = 0.5))  
  theme(plot.title = element_text(hjust = 0.5))  
  labs(x = "", y = "", fill = "Canal configurations")  
  theme_bw(base_size = 14)  
  theme(legend.position = "top")  
  theme(axis.text.y = element_text(size = 8))  
  theme(axis.text.x = element_text(size = 10))  
  guides(fill = guide_legend(nrow = 1, byrow = TRUE))  
  facet_wrap(.~ E2A, scales = "free")

enter image description here

CodePudding user response:

We could use geom_label this way:

ggplot(data = remove_missing(df, na.rm = TRUE, vars = c("E2A", "E4A", "E5A")))   # remove NA's for cleaner plot
  aes(x = E4A, fill = E5A)  
  geom_bar(position = "fill")  
  theme(plot.title = element_text(hjust = 0.5))  
  labs(x = "", y = "", fill = "Canal configurations")  
  theme_bw(base_size = 14)  
  theme(legend.position = "top")  
  theme(axis.text.y = element_text(size = 8))  
  theme(axis.text.x = element_text(size = 10))  
  guides(fill = guide_legend(nrow = 1, byrow = TRUE))  
  facet_wrap(.~ E2A, scales = "free")  
  geom_label(data = . %>% 
              count(E2A, E4A, E5A, Tooth),
            aes(y = n, label = n),size=5,
            position = position_fill(0.5),
            show.legend = FALSE)

enter image description here

  • Related