Home > Software engineering >  R - Grouped Barplot with legend
R - Grouped Barplot with legend

Time:02-12

I have tried to replicate code/ guidance from other answers to grouped barplot help but always seem to encounter error messages. I get these even before trying to add in titles/ legend.

I have the below dataset;

Month CT Report Terminals ATM DB Terminals Member Stats Terminals HC Errors
Nov-21 406 139 1251 888
Dec-21 640 1438 1544 740
Jan-22 795 939 1000 297

I want to replicate the below graph;

enter image description here

I can do this easily in excel but trying to stick with R. I have the below code;

library(ggplot2)

read_excel("ct_summary.xlsx")

data <- read_excel("ct_summary.xlsx")

Category <- c("CT Report Terminals", "ATM DB Terminals", 
              "Member Stats Terminals", "HC Errors")

ggplot(data, aes(x = Category, y = Category, fill=Month))  
  geom_bar(stat="identity", position = "dodge")

The error message Error: Aesthetics must be either length 1 or the same as the data (3): x and fill keeps appearing or I get errors around bar height.

CodePudding user response:

You need to pivot your data into long format. You can use tidyr::pivot_longer(data, -1) to do this easily. Everything else in the following code is just cosmetic tweaks to make your plot look more like the original:

library(ggplot2)
library(dplyr)
library(tidyr)

data %>% 
  pivot_longer(-1) %>%
  mutate(Month = factor(Month, c("Nov-21", "Dec-21", "Jan-22")),
         name = stringr::str_wrap(name, 12),
         name = factor(name, levels(factor(name))[c(2, 1, 4, 3)])) %>%
  ggplot(aes(name, value, fill = Month))  
  geom_col(width = 0.6, position = position_dodge(width = 0.8))  
  scale_fill_manual(values = c("#4472c4", "#ed7d31", "#a5a5a5"))  
  scale_y_continuous(breaks = 0:9 * 200)  
  labs(x = "", y = "", title = "Heading TBC")  
  theme_bw()  
  theme(panel.grid.major.x = element_blank(),
        panel.border = element_blank(),
        plot.title = element_text(hjust = 0.5))

enter image description here


Data

data <- structure(list(Month = c("Nov-21", "Dec-21", "Jan-22"), 
                       `CT Report Terminals` = c(406L, 640L, 795L), 
                       `ATM DB Terminals` = c(139L, 1438L, 939L), 
                       `Member Stats Terminals` = c(1251L, 1544L, 1000L), 
                       `HC Errors` = c(888L, 740L, 297L)), 
                  class = "data.frame", row.names = c(NA, -3L))
  • Related