Search code examples
rggplot2stacked-area-chart

Making Area Chart with Two Variables


I have a data set of the Win/Loss record of the Boston Red Sox in 2018 which starts like:

Game,W/L,W,L
1,L,0,1
2,W,1,1
3,W,2,1
4,W,3,1
5,W,4,1
6,W,5,1
7,W,6,1
8,W,7,1
9,W,8,1

I want to convert this to a stacked area chart comparing W vs. L with respect to Game in ggplot2, but am struggling with how to set this up. I can get started using

rec = read.csv('redsox_record.csv')

ggplot(rec, aes(x=Game, y=W)) + geom_area()

but this only returns the chart for W, and I'm not sure how to include L as well.


Solution

  • library(reshape2)
    library(ggplot2)
    rec <- melt(rec[, c(1, 3, 4)], id.vars = 'Game')
    ggplot(rec, aes(x=Game, y=value, fill = variable)) + geom_area()
    

    enter image description here