2017-10-12 48 views
3

想要繪製density對象時,我有一個問題。例如,考慮發行繪製`density`當對象

require(grDevices) 

set.seed(43) 
d0 = density(rexp(1e5,rate=1)) 
d1 = density(rexp(1e5,rate=1.8)) 


plot(d1, col="white", xlab = "x", ylab="Density", main = "") 
polygon(d1, col=adjustcolor("blue", alpha.f=0.2)) 
lines(d0, col="white") 
polygon(d0, col=adjustcolor("red", alpha.f=0.2)) 

enter image description here

目前,它看起來如我所料。縮放Y軸的低值時出現問題。考慮例如

plot(d1, col="white", xlim=c(2.5,3), xlab = "x", ylab="Density", main = "", 
ylim=c(0,0.02)) 
polygon(d1, col=adjustcolor("blue", alpha.f=0.2)) 
lines(d0, col="white", xlim=c(2.5,3), ylim=c(0,0.02)) 
polygon(d0, col=adjustcolor("red", alpha.f=0.2)) 

enter image description here

奇怪的是,多邊形的下部未達到密度= 0。此外,一個多邊形結束其中一個比另一個低。設置yaxs="i"xaxs="i"時,問題仍然存在。

這是怎麼回事,如何解決這個問題呢?


有了一些個人資料,我得到的東西像

enter image description here

回答

2

另一種選擇是延長密度估計有點超出的數據的範圍的x範圍,使得所述密度估計真的會在兩端實際上爲零。這避免了需要人爲地改變密度估計值中的任何值。例如:

set.seed(43) 
d0 = density(rexp(1e5,rate=1)) 
d1 = density(rexp(1e5,rate=1.8)) 

d1$y[c(1, length(d1$y))] 

[1] 2.987316e-03 1.235864e-06

set.seed(43) 
d1 = rexp(1e5,rate=1.8) 
d1 = density(d1, from=min(d1) - 0.05*diff(range(d1)), to=max(d1) + 0.05*diff(range(d1))) 

d1$y[c(1, length(d1$y))] 

[1] 6.334144e-17 3.797333e-17

+2

此解決方案有點「更好地處理原因」有;) – AkselA

1

你能僅僅通過兩端錨定y值爲零作弊?

set.seed(43) 
d0 = density(rexp(150,rate=1)) 
d1 = density(rexp(150,rate=1.8)) 

d0$y[c(1, length(d0$y))] <- 0 
d1$y[c(1, length(d1$y))] <- 0 

plot(d1, col="white", xlim=c(2.5,3), xlab = "x", ylab="Density", main = "", 
ylim=c(0,0.02)) 
polygon(d1, col=adjustcolor("blue", alpha.f=0.2)) 
lines(d0, col="white", xlim=c(2.5,3), ylim=c(0,0.02)) 
polygon(d0, col=adjustcolor("red", alpha.f=0.2)) 

enter image description here

略有改善是降低整個多邊形,以使端部中的一個觸摸基線,然後將下一個零:

set.seed(43) 
d0 = density(rexp(150,rate=1)) 
d1 = density(rexp(150,rate=1.8)) 

ends0 <- d0$y[c(1, length(d0$y))] 
ends1 <- d1$y[c(1, length(d1$y))] 

d0$y <- d0$y - min(ends0) 
d1$y <- d1$y - min(ends1) 

d0$y[c(1, length(d0$y))] <- 0 
d1$y[c(1, length(d1$y))] <- 0 


plot(d1, col="white", xlim=c(2.5,3), xlab = "x", ylab="Density", main = "", 
ylim=c(0,0.02)) 
polygon(d1, col=adjustcolor("blue", alpha.f=0.2)) 
lines(d0, col="white", xlim=c(2.5,3), ylim=c(0,0.02)) 
polygon(d0, col=adjustcolor("red", alpha.f=0.2)) 

enter image description here

這裏是一個沒有修正,進行比較。

enter image description here

+0

哦...我現在大致瞭解了這個問題和簡單的解決方法。它看起來像一個糟糕的工作,它的解決方案,但它解決了這一問題,可能是最簡單的解決方案。 +1 –

+0

@ Remi.b:是的,如果在圖中包含x值端點,則最終會出現一個尷尬的鋸齒狀邊緣 – AkselA