将简单的直方图添加到 ggplot2 中的图例

Add simple histogram to legend in ggplot2

给定使用以下代码生成的 ggplot

size = 10000
d = data.frame(
  type = rep(c("A","B","C"), each=size),
  val = c(rnorm(size, 0, 1), rnorm(size, 1, 2),rnorm(size, 2, 3))
)

require(ggplot2)
(
  ggplot(subset(d, is.element(type, c("A", "C"))), aes(x=val))
  + geom_histogram(aes(y=..density..), bins=100, position="identity", alpha=0.5)
  + geom_line(aes(color=type), stat="density", size=1)
)

是否可以在图例中添加带有表示简单直方图的自定义标签的灰色方块?没有creating a dummy item可以吗?

您只需要将 fill= 放入 aes() 以获取 geom_histogram() 行。您的数据集中没有要分配给它的列,但如果您在 aes() 中分配 fill="string name",则 ggplot 将创建一个填充图例,并将其作为标签。

当然,颜色将默认为 ggplot“红色”颜色,因此如果您想再次使用灰色,则必须使用 scale_fill_manual() 进行设置,因为 fill=aes() 将覆盖你放在 aes().

内的任何内容
ggplot(d, aes(x=val)) + 
  geom_histogram(aes(y=..density.., fill='histogram'),
    bins=100, position="identity", alpha=0.5) +
  geom_line(aes(color=type), stat="density", size=1) +
  scale_fill_manual(values='gray20')