如何创建堆叠线图

17

在R中创建堆叠条形图有多种解决方案,但如何绘制堆叠线图呢?

输入图片描述


许多用户在搜索堆积条形图时似乎会找到这个问题。请看这里:http://www.statmethods.net/graphs/bar.html - BurninLeo
3个回答

27

使用 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')

输入图像描述


4

考虑到图表数据以数据框的形式存在,每条线都在列中,并且 Y 值在行中,而行名称是 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
  }
}

建议修改:在参数列表中添加 ...,以便所有 plot 函数的参数都可以使用。特别是,xaxs="i" 可以消除堆叠图与绘图边缘之间的白色边距。 - user1521655

1

只需在 geom_line(position = "stack") 中指定 position = "stack" 即可。例如:

dat <- data.frame(x = c(1:5,1:5),
              y = c(9:5, 10,7,5,3,1),
              type = rep(c("a", "b"), each = 5))

library(dplyr)
library(ggplot2)


dat %>% 
  ggplot(aes(fill = type,
             x = x,
             y = y,
         color = type,
         linetype = type)) +
  geom_line(position = "stack", size = 2) + # specify it here
  theme_bw()

导致了堆积线图:

enter image description here

或者,您还可以将堆叠线图与 geom_area 图表相结合 如此所示

    dat %>% 
  ggplot(aes(fill = type,
             x = x,
             y = y,
         color = type,
         linetype = type)) +
  geom_area(position="stack", 
            stat="identity",
            alpha = 0.5) +
  geom_line(position = "stack", size = 2) + 
  theme_bw()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接