【问题标题】:Adding a legend to an histogram plot that has several stat_bin layers using ggplot2使用 ggplot2 向具有多个 stat_bin 层的直方图添加图例
【发布时间】:2015-01-18 13:18:07
【问题描述】:

我需要绘制一个包含多个具有不同 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)

提前致谢!

【问题讨论】:

  • 从统计数据的角度来看,我不认为在一个地块中使用不同的 bin 宽度是一个好主意(教育目的除外)。
  • 我同意你的看法。但就我而言,我正在处理符号数据分析框架中的直方图,有时会比较甚至组合具有不同 bin 大小的直方图(通常生成不规则 bin 大小的直方图)。

标签: r plot ggplot2 histogram


【解决方案1】:

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

【讨论】:

  • 是的!这正是我一直在寻找的。事实上我试图用你的方式解决它,但我没有意识到我使用的是 aes_string,所以使用 fill = color[i] 是问题:) 谢谢你的帮助!
猜你喜欢
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
相关资源
最近更新 更多