如何创建一个堆叠线图(How to create a stacked line plot)

2019-08-03 08:54发布

有多种解决方案,打造R中堆叠条形图,但如何绘制堆叠线图?

Answer 1:

一种堆叠线图可与被创建ggplot2包。

一些示例数据:

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

对于这种剧情的功能是geom_area

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



Answer 2:

鉴于图数据可作为与在列“线”和行中的Y值的数据帧和鉴于row.names是X值,该脚本创建层叠使用多边形函数的线图。

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
  }
}


文章来源: How to create a stacked line plot
标签: r charts diagram