我正在嘗試創建一個具有以下內容的情節:
- 從方法“A”創建的“歷史”時間段中值的直方圖
- “未來”時間段內的值的直方圖,由方法“A”創建
- “歷史”和“未來”時間段中的 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應該只繪制方法==“B”,引數==“歷史”,“未來”,并且應該geom_histogram只繪制,方法==“A”,引數==“歷史”,“未來”。

我希望最終結果看起來像這樣:(左側,withgeom_line或右側,with stat_bin)

uj5u.com熱心網友回復:
繪制您要求的內容,即方法“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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483774.html
