![](/img/trans.png)
[英]“Density” curve overlay on histogram where vertical axis is frequency (aka count) or relative frequency?
[英]Integrating histogram and density curve, with one axis for frequency and the other for density
我正在使用hist()
和lines()
函數創建一個密度疊加的直方圖,並希望有一個顯示頻率而不是密度的y-axis
。
有沒有辦法使用hist()
和不使用ggplot
來做到這ggplot
? 將頻率軸作為右側的第二個y軸甚至更好。 這是我的代碼:
g <- rnorm(2000,5,1)
h<-hist(g, breaks=50, col="bisque",
border="black",ylab="Frequeny",yaxt='n',
main="Title",xlab=paste0("Cr","(mg/dL)"),prob=TRUE)
Axis(side=2, at=seq(0, 200, by=20))
lines(density(g),col="dimgray") #For Overlay
設置prob = FALSE
沒有幫助,因為那時線不適用於密度疊加。
讓我們首先生成數據和hist
對象:
set.seed(0) ## added for reproducibility
g <- rnorm(2000, 5, 1)
h <- hist(g, breaks = 50, plot = FALSE)
我通過plot = FALSE
暫時抑制了plot = FALSE
。
問題是,我們希望有兩個y軸:
基本上我們在兩個軸的密度值上添加刻度線,但是
hist
對象中的密度值是h$density
。 對於漂亮的圖形,我們應用pretty()
來獲得刻度標記位置:
pos <- pretty(h$density, n = 5)
# [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6
要在pos
找到相應的計數,我們會:
freq <- round(pos * length(g) * with(h, breaks[2] - breaks[1]))
# [1] 0 20 40 60 80 100 120
這里使用的round()
只是為了確保有限精度計算引入的數字被刪除,因此我們最終得到整數。
現在我們准備生成我們的集成直方圖。 請記住增加右邊距以為右軸的軸名稱保留一些空間。 在下文中,我們將右邊距設置為與左邊距相同。
new.mai <- old.mai <- par("mai")
new.mai[4] <- old.mai[2]
par(mai = new.mai)
graphics:::plot.histogram(h, freq = FALSE, col="bisque", main="Integrated Histogram",
xlab = paste0("Cr","(mg/dL)"), ylab="Frequeny",
border="black", yaxt='n')
Axis(side = 2, at = pos, labels = freq)
Axis(side = 4, at = pos, labels = pos)
mtext("Density", side = 4, line = 3)
lines(density(g), col="dimgray")
par(mai = old.mai)
注意我是如何使用graphics:::plot.histogram
繪制hist
對象,以及mtext
在邊緣添加文本。 閱讀?plot.histogram
和?mtext
了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.