Eleka
Eleka

Reputation: 3

Create a stacked column chart in R

I'm trying to create a stacked column chart using R.

I have a dataframe that looks like this:

Data df:

structure(list(Period = c("1971-1989", "1990-1999", "2000-2009", 
"2010-2019", "2020-2029"), Cold = c(-1.02, -0.3, -0.13, 0, 0.09
), Heat = c(6.08, -0.4, -0.1, 0, 0.17)), class = "data.frame", row.names = c(NA, 
-5L))

Period is chr, the others are num. I want to produce a stacked column chart that looks like this: (I made this using Excel)

enter image description here

I tried using ggplot:

ggplot(df, aes(fill=cold, y=heat, x=Period)) + 
  geom_bar(position="stack", stat="identity")

But I couldn't get a stacked plot like I wanted.

Any help would be much appreciated.

Upvotes: 0

Views: 217

Answers (1)

ATpoint
ATpoint

Reputation: 878

First transform the wide data.frame to long form, then use basically what you did before:

df <- structure(list(Period = c("1971-1989", "1990-1999", "2000-2009", 
"2010-2019", "2020-2029"), Cold = c(-1.02, -0.3, -0.13, 0, 0.09
), Heat = c(6.08, -0.4, -0.1, 0, 0.17)), class = "data.frame", row.names = c(NA, 
-5L))

library(magrittr)
library(ggplot2)
library(reshape2)

df %>%
  reshape2::melt() %>%
  ggplot(aes(x=Period, y=value, fill=variable)) +
  geom_bar(position="stack", stat="identity") +
  guides(x = guide_axis(angle = 45)) # rotate x-axis label by 45°

enter image description here

From here you can now modify axis and labels as desired.

Upvotes: 3

Related Questions