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

Adding a legend to an histogram plot that has several stat_bin layers using ggplot2

我需要绘制一个图,其中包含几个具有不同 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)

提前致谢!

为了让 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")