如何在ggplot2中叠加条形图

时间:2016-04-05 08:50:26

标签: r plot ggplot2 bar-chart

我想叠加三个条形图。

剧情1:

Plot 1

Plot 2:

Plot 2

剧情3:

Plot 3

fzg <- structure(list(start = c(40L, 22L, 37L, 32L, 72L, 41L, 2L, 11L, 57L, 10L, 102L, 40L, 17L, 48L, 86L, 46L, 49L, 7L, 1L, 2L, 13L, 69L, 42L, 31L, 39L, 64L, 39L, 29L, 67L, 5L, 1L, 54L, 32L, 7L, 4L, 67L, 14L, 26L, 20L, 42L, 26L, 57L, 0L, 34L, 114L), period = 1:45,     zug = c(FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE,     TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE,     FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE,     FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE,     TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE,     TRUE), typ = c(2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L,     2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L,     2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L,     1L, 2L, 2L, 1L), dyn1 = c(0L, 0L, 0L, 0L, 203L, 0L, 0L, 0L,     111L, 0L, 112L, 0L, 0L, 0L, 191L, 0L, 95L, 0L, 0L, 0L, 0L,     92L, 0L, 0L, 0L, 176L, 0L, 0L, 135L, 0L, 0L, 60L, 0L, 0L,     0L, 110L, 0L, 0L, 0L, 0L, 0L, 185L, 0L, 0L, 148L), dyn2 = c(0L,     0L, 0L, 0L, 203L, 0L, 0L, 0L, 0L, 0L, 223L, 0L, 0L, 0L, 0L,     0L, 286L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 268L, 0L, 0L, 0L,     0L, 0L, 0L, 0L, 0L, 0L, 305L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,     0L, 333L)), .Names = c("start", "period", "zug", "typ", "dyn1", "dyn2"), row.names = c(NA, -45L), class = "data.frame")

x_scale_max <- max(fzg$start, fzg$dyn1, fzg$dyn2)

ggplot(fzg, aes(x=period, y=start, fill=typ)) +   geom_bar(stat="identity", position="dodge") + ylim(0,x_scale_max)
ggplot(fzg, aes(x=period, y=dyn1, fill=typ)) +   geom_bar(stat="identity", position="dodge") + ylim(0,x_scale_max)
ggplot(fzg, aes(x=period, y=dyn2, fill=typ)) +   geom_bar(stat="identity", position="dodge")+ ylim(0,x_scale_max)

生成的条形图

  • 显示颜色为0的情节1中的所有小条
  • 显示颜色1中的图1中所有突出显示的条形
  • 显示来自图2的彩色2的添加部分
  • 显示来自图3的彩色3的添加部分

我设法在一个情节中得到所有

library(reshape2)
mdat <- melt(fzg[c("start", "period", "dyn1", "dyn2")], measured=c("start","dyn1","dyn2"), id="period")
ggplot(mdat, aes(x=period, y=value, fill=variable)) +   geom_bar(stat="identity", position="stack") + ylim(0,x_scale_max)

但不同步骤的颜色突出显示效果不佳。

1 个答案:

答案 0 :(得分:1)

如果你正在寻找这个 plot
只需修改您的代码:

mdat <- melt(fzg[c("start", "period", "dyn1", "dyn2", "typ")], measured=c("start","dyn1","dyn2"), id=c("period", "typ"))
mdat <- mdat[mdat$value != 0,]
ggplot(mdat, aes(x=period, y=value, fill=interaction(variable,typ))) + geom_bar(stat = "identity")