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

Viewed 625

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

2 Answers

For ggplot2, I suggest you first reshape (go from "wide" to "long") and then facet:

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

dat %>%
  pivot_longer(-Council, names_to = "year", values_to = "count") %>%
  mutate(Council = as.character(Council)) %>%
  ggplot(aes(Council, count)) +
  geom_bar(stat = "identity", horizontal = TRUE) +
  facet_wrap(~ year)

ggplot2 facetted plot


Data:

dat <- read.table(header = TRUE, check.names = FALSE, text = "
Council   2019   2020
1          260    206
2          130    157
3           42     48
4           38     42
5           45    126
6           34     26
7           13     21
8           30     13
9           16     15
10          15     43")

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"))
Related