gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:33:22 26 4
gpt4 key购买 nike

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

resulting plot

关于r - 使用 ggplot2 向具有多个 stat_bin 层的直方图添加图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28010091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com