使用ggplot2将图例添加到具有多个stat_bin图层的直方图中

时间:2015-01-18 13:18:08

标签: r plot ggplot2 histogram

我需要绘制一个包含多个具有不同bin大小配置的直方图的图。为此,我使用了几个stat_bin层。情节还可以,但我无法了解如何添加将每个直方图名称与填充颜色相关联的图例。

我一直在尝试几种选择,但似乎没有人工作。知道怎么做吗?

以下是代码:

  hist.name.list <- list("H1", "H2", "H3")    
  returns.data.frame <- data.frame("H1" = runif(100, 4.0, 7.5), 
                                   "H2" = runif(100, 1.0, 5.0), 
                                   "H3" = runif(100, 6.0, 9.5))
  breaks.list <- list(seq(4, 7.5, 0.1),
                      seq(1, 5, 0.4),
                      seq(6, 9.5, 0.8))
  color <- c(1,2,3)

  library(ggplot2)
  m <- ggplot(returns.data.frame) + theme_bw()

  for (i in seq(1,3)) {    
    m <- m + stat_bin(
        aes_string(x = hist.name.list[[i]], 
                   y = "..count../sum(..count..)"),
        breaks = breaks.list[[i]],
        drop = FALSE, 
        right = TRUE, 
        col = color[i],
        fill = color[i],
        alpha = 0.2) 
  }
  print(m)

提前致谢!

1 个答案:

答案 0 :(得分:4)

为了让ggplot2显示指南(图例),您需要将某些内容映射到相应的比例。这是在aes(或本例中为aes_string)中完成的。

color <- factor(color)
library(ggplot2)
m <- ggplot(returns.data.frame) + theme_bw()

for (i in seq(1,3)) {    
  m <- m + stat_bin(
    aes_string(x = hist.name.list[[i]], 
               y = "..count../sum(..count..)",
               color = paste0("color[", i, "]"),
               fill = paste0("color[", i, "]")),
    breaks = breaks.list[[i]],
    drop = FALSE, 
    right = TRUE, 
    alpha = 0.2) 
}

m  + 
  scale_fill_discrete(name = "group") +
  scale_color_discrete(name = "group")

resulting plot