Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a stacked line plot

Tags:

r

diagram

charts

There are multiple solutions to create a stacked bar plot in R, but how to draw a stacked line plot?

enter image description here

like image 617
BurninLeo Avatar asked Nov 30 '12 11:11

BurninLeo


People also ask

What is a stacked line in Excel?

Stacked Line charts show the contribution to trends in the data. This is done by stacking lines on top of each other. Stacked Line charts are used with data which can be placed in an order, from low to high. The charts are used when you have more than one data column which all add up to the total trend.


2 Answers

A stacked line plot can be created with the ggplot2 package.

Some example data:

set.seed(11)
df <- data.frame(a = rlnorm(30), b = 1:10, c = rep(LETTERS[1:3], each = 10))

The function for this kind of plot is geom_area:

library(ggplot2)
ggplot(df, aes(x = b, y = a, fill = c)) + geom_area(position = 'stack')

enter image description here

like image 157
Sven Hohenstein Avatar answered Sep 20 '22 17:09

Sven Hohenstein


Given that the diagram data is available as data frame with "lines" in columns and the Y-values in rows and given that the row.names are the X-values, this script creates stacked line charts using the polygon function.

stackplot = function(data, ylim=NA, main=NA, colors=NA, xlab=NA, ylab=NA) {
  # stacked line plot
  if (is.na(ylim)) {
    ylim=c(0, max(rowSums(data, na.rm=T)))
  }
  if (is.na(colors)) {
    colors = c("green","red","lightgray","blue","orange","purple", "yellow")
  }
  xval = as.numeric(row.names(data))
  summary = rep(0, nrow(data))
  recent = summary

  # Create empty plot
  plot(c(-100), c(-100), xlim=c(min(xval, na.rm=T), max(xval, na.rm=T)), ylim=ylim, main=main, xlab=xlab, ylab=ylab)

  # One polygon per column
  cols = names(data)
  for (c in 1:length(cols)) {
    current = data[[cols[[c]]]]
    summary = summary + current
    polygon(
      x=c(xval, rev(xval)),
      y=c(summary, rev(recent)),
      col=colors[[c]]
    )
    recent = summary
  }
}
like image 35
BurninLeo Avatar answered Sep 20 '22 17:09

BurninLeo