在基礎R中,我們可以使用函式hist()來創建一個給定變數的密度直方圖,例如x。如果我們寫:
h < - hist(x, freq=FALSE)
那么,h$mids是一個包含每個bin的中點值的向量,而h$density包含每個bin的密度。我想用ggplot2的geom_histogram()繪制我的密度直方圖。
是否有辦法從ggplot2函式中檢索出類似的值(每個bin的中點和密度)?
uj5u.com熱心網友回復:
你可以通過使用ggplot() geom_histogram()創建一個直方圖,然后使用ggplot_build()來提取bin中點、最小和最大值、密度、計數等等。
下面是一個使用內置iris資料集的簡單例子:
library(ggplot2)
# 使用虹膜資料集和ggplot()制作直方圖# 制作直方圖
h <- ggplot(data = iris)
geom_histogram(mapping = aes(x=Petal. 寬度),
bins = 11)
# 使用ggplot_build()提取直方圖的基本特征。
vals < - ggplot_build(h)/span>$data[[1]]
# print the bin midpoints
vals$x
## 0.00 0.24 0.48 0.72 0.96 1.20 1.44 1.68 1.92 2.16 2.40
# print the bin densities[/span]。
vals$密度
## 0.1388889 1.0000000 0.2500000 0.0000000 0.1944444 0.5833333 0.5555556 0.5000000 0.3055556 0.2500000 0.3888889
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330218.html
標籤:
