如何创建堆叠线图

时间:2012-11-30 11:37:38

标签: r charts diagram

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

enter image description here

3 个答案:

答案 0 :(得分:20)

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

enter image description here

答案 1 :(得分:4)

假设图表数据可用作数据框,列中包含“行”,行中的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
  }
}

答案 2 :(得分:0)

只需在position = "stack"中指定geom_line(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_areaas shown here结合起来:

    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