Home > Software engineering >  How to build stacked bar chart
How to build stacked bar chart

Time:08-10

How can I build stacked bar chart from this data? Where years will be x axis while Old and NEW differentiated via colours in bars. However I want to avoid manual coding and automatize the process

structure(list(`1998` = c(11, 826), `2000` = c(217, 620), `2007` = c(625, 
212), `2012` = c(836, 1)), class = "data.frame", row.names = c("NEW", 
"OLD"))


    1998 2000 2007 2012
NEW   11  217  625  836
OLD  826  620  212    1

Expected output:

[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/l2Y59.png

CodePudding user response:

Looking for something like this?

library(tidyverse)
df %>%
  # rownames to column
  mutate(type = rownames(.)) %>%
  # convert to long data
  pivot_longer(-"type") %>%
  # plot
  ggplot()   
  geom_col(aes(x = name, y = value, fill = type))

enter image description here

  • Related