如何将 geom_histogram 与 stat_bin 或 geom_line 重叠绘制成多个分组?

How to overplot geom_histogram with stat_bin or geom_line with multiple groupings?

我正在尝试创建一个具有以下内容的情节:

  1. “历史”时间段内值的直方图,根据方法“A”创建
  2. “未来”时间段值的直方图,根据方法“A”创建
  3. “历史”和“未来”时间段中的 stat_bin 或 geom_line 个值,由方法“B”创建

示例数据:

draw method Parameter Value
1 A historic 0.99
1 A future 0.98
1 B historic 0.97
1 B future 0.96
2 A historic 0.9
2 A future 0.88
2 B historic 0.95
2 B future 0.94
3 A historic 0.97
3 A future 0.94
3 B historic 0.91
3 B future 0.89

  ggplot(df,aes(x=Value,color=Parameter,fill=Parameter)) + 
  scale_color_discrete(name="Period",labels=c("historic","future")) +
  scale_fill_discrete(name="Period",labels=c("historic","future"),guide="none") +
  geom_histogram(aes(y=..density..),
    breaks=seq(.8,1.0,by=0.01),
    alpha=0.4,position="identity") + 
  theme(axis.title.x=element_blank(),axis.text.x=element_blank(),
  axis.title.y=element_blank()) +
  scale_x_continuous(breaks=seq(.8,1.00,by=0.01)) +coord_flip() +
  theme(legend.position = "bottom") +
  geom_line(data=subset(df,method == "B"),
    aes(x=Value),stat="density")

在图像中,直方图似乎绘制了“方法”值的 所有。但在直方图中,我只想要方法 == “A”(和参数 == “历史”和“未来”)。有没有办法根据两种类型的分组创建不同类型的图? geom_line 应该只绘制 method == "B", Parameter == "historic","future", geom_histogram 应该只绘制 , method == "A", Parameter == "历史性的”,“未来的”。

我希望最终结果看起来像这样:(左侧 geom_line 或右侧 stat_bin

绘制您要求的内容,即来自方法“A”的直方图条和来自方法“B”的线。

正在读取示例数据:

x <- '
draw method Parameter Value
1 A historic 0.99
1 A future 0.98
1 B historic 0.97
1 B future 0.96
2 A historic 0.9
2 A future 0.88
2 B historic 0.95
2 B future 0.94
3 A historic 0.97
3 A future 0.94
3 B historic 0.91
3 B future 0.89
'

df <- read.table(textConnection(x), header = TRUE)

绘图:

 ggplot() +
  geom_histogram(data=df %>% filter(method=="A"),
                 aes(x=Value, y=..density.., fill=Parameter),
                 breaks=seq(.8, 1.0, by=0.01),
                 alpha=0.4, position="identity") +
  geom_line(data=df %>% filter(method=="B"),
            aes(x=Value, colour=Parameter), stat="density") +
  scale_fill_discrete(name="", labels=c("Historic, A","Future, A")) +
  scale_colour_discrete(name="", labels=c("Historic B","Future B")) +
  coord_flip()