How to create a stacked line plot

23,760

Solution 1

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

Solution 2

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
  }
}
Share:
23,760
BurninLeo
Author by

BurninLeo

Updated on August 27, 2020

Comments

  • BurninLeo
    BurninLeo over 3 years

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

    enter image description here

  • user1521655
    user1521655 almost 9 years
    Suggested tweak: add ... to the parameter list so all plot function parameters are available for use. In particular, xaxs="i" will get rid of white margin between the stacked graph and the edges of the plot.