Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a side-by-side bar plot in ggplot2?

Tags:

r

ggplot2

Here is how my data is formatted. Do I need to make it "tidy" first or is this fine?

   Council `2019` `2020`
   <chr>    <dbl>  <dbl>
 1 1          260    206
 2 2          130    157
 3 3           42     48
 4 4           38     42
 5 5           45    126
 6 6           34     26
 7 7           13     21
 8 8           30     13
 9 9           16     15
10 10          15     43

My goal is a create a side by side bar plot for each council to show the difference for each one from 2019 - 2020.

Thank you

like image 955
RL_Pug Avatar asked Nov 15 '25 16:11

RL_Pug


1 Answers

If you need a side-by-side bar chart without facet, try this:

library(tidyverse)

df %>%
  pivot_longer(-1, names_to = "year", values_to = "count") %>%
  ggplot(aes(Council, count, fill = year)) +
  geom_col(position = "dodge2") +
  scale_x_continuous(breaks = 1:10)


Data

df <- structure(list(Council = 1:10, `2019` = c(260L, 130L, 42L, 38L, 
45L, 34L, 13L, 30L, 16L, 15L), `2020` = c(206L, 157L, 48L, 42L, 
126L, 26L, 21L, 13L, 15L, 43L)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))
like image 79
Darren Tsai Avatar answered Nov 18 '25 06:11

Darren Tsai