Reputation: 51
I have an aggregated data in three column: fuel type, no of car in 2018 and no of car in 2021, shown as below table. However I am stuck in creating a grouped bar chart to compare the fuel type in 2018 and 2021
I would like to create a grouped bar chart to visualize the change (between 2018 and 2021) to compare them side by side (x-axis = fuel type, y-axis = value of 2018 and 2021).
From my search from Google, most of the teaching requries to convert into matrix or table. However, it just turn out into something "unsual". Thus I am hopping for your help or advice in solving this.
table <- table(fuel_trend$2018, fuel_trend$2021)
barplot(table, beside = TRUE)
Additionally, I do welcome new suggestion to better visaulize this data.
Upvotes: 2
Views: 227
Reputation: 79184
I think you need this:
Basically we bring data in long format and plot with ggplot2
package:
library(scales)
library(ggplot2)
library(dplyr)
library(tidyr)
df %>%
pivot_longer(-fuel_typ) %>%
ggplot(aes(x=fuel_typ, y=value, fill=name)) +
geom_col(position = position_dodge())+
scale_fill_manual(values = c("red", "blue")) +
scale_y_continuous(labels = label_comma())+
theme_bw()
data:
structure(list(fuel_typ = c("DIESEL", "DIESEL/ELECTRIC", "LPG",
"PETROL", "PETROL/ELECTRIC"), no_car_18 = c(47817L, 14L, 904L,
333872L, 3653L), no_car_21 = c(3992L, 199L, 2224L, 215199L, 30550L
)), class = "data.frame", row.names = c("1", "2", "3", "4", "5"))
Upvotes: 1