Home > Enterprise >  Adding percentage in grouped barplot
Adding percentage in grouped barplot

Time:01-06

I would like to as how can I include the percentage difference in the grouped bar plot This is the data frame that I have

enter image description here

The code that I have:

library(scales)
library (ggplot2)
library(dplyr)
library(tidyr)
df %>% 
pivot_longer(-fuel_type) %>%
ggplot(aes(x=fuel_typ, y=value,fill=name)) 
geom_col(position=position_dodge())   
scale_fill_manual(values=c("red","blue"))  
scale_y_continous(labels=label_comma())   
theme_bw()

(above code is credited to @Tarjae)

the output:

enter image description here

May I know how can I label the percentage difference of "no_car_21" relative to "no_car_18" on top of the "no_car_21" bar chart, with positive or negative signs?

Many thanks

CodePudding user response:

You could calculate the percentage change per group with previous value using lag and assign them to geom_text with adjusting the hjust and vjust like this:

df <- data.frame(fuel_type = c("DIESEL", "DIESEL/ELECTRIC", "LPG", "PETROL", "PETROL/ELECTRIC"),
                 no_car_18 = c(47817, 14, 904, 333872, 3653),
                 no_car_21 = c(3992, 199, 2224, 215199, 30550))

library(scales)
library(ggplot2)
library(dplyr)
library(tidyr)
df %>% 
  pivot_longer(-fuel_type) %>%
  group_by(fuel_type) %>%
  mutate(pct = (value/lag(value)-1)*100) %>%
  ggplot(aes(x=fuel_type, y=value,fill=name)) 
  geom_col(position=position_dodge())   
  scale_fill_manual(values=c("red","blue"))  
  geom_text(aes(y = value, label = round(pct, 2)), hjust = 0, vjust = -0.5)  
  scale_y_continuous(labels=label_comma())   
  theme_bw()

Created on 2023-01-03 with reprex v2.0.2

  • Related