Home > front end >  How to plot with ggplot grouped data in two levels?
How to plot with ggplot grouped data in two levels?

Time:02-08

Here is my data set:

SP <- c("DC","DC","DP","DP","DC")
ES <- c("CA","CA","CA","CA","CK")
W <- c("B","A","B","A","B")
P <- c(0.5,0.77,0,0.43,.38)
df <- data.frame(SP, ES, W, P)

I would like to plot this like in the picture that I made in excel. It is important that the data are grouped and have the space between each of them.

Please find below my excel barplot: enter image description here

CodePudding user response:

Using your original data, here is one approach using ggplot's facet_wrap.

Note: shadows are not good practice for graphs.

dat <- data.frame(SP = rep(rep(c("DC", "DP"), each = 2), 3),
                  ES = rep(c("CA", "CK", "HD"), each = 4),
                  W = rep(c("B", "A"), 6),
                  P = c("50%", "77%", "0%", "43%", "38%", "68%", "0%", "26%", "13%", "5%", "0%", "4%"))

library(dplyr)
library(stringr)
library(ggplot2)

dat %>% 
  mutate(P = as.numeric(str_extract(P, "\\d "))/100) %>% 
  ggplot(aes(SP, P, fill = W))   
  geom_col(position = position_dodge2(width = 0.8, reverse = TRUE)) 
  facet_wrap(~ES, nrow = 1) 
  geom_text(aes(label = scales::percent(P, accuracy = 1)),
            position = position_dodge2(width = 0.8, reverse = TRUE),
            vjust = 1.5,
            colour = "white",
            size = 3) 
  labs(x = NULL,
       y = NULL) 
  theme_bw() 
  theme(legend.position = "bottom",
        axis.ticks = element_blank(),
        axis.text.y = element_blank(),
        panel.border = element_blank(),
        panel.spacing = unit(30, "mm"))

Created on 2022-02-07 by the reprex package (v2.0.1)

  •  Tags:  
  • Related