2017-02-28 90 views
0

我有一個隨機向量,並嘗試使用ggplot 這裏,使這密度圖是如何提取和情節密度使用GGPLOT2

fridayKlient1<-c(134 ,135, 133, 137, 136) 

然後我用密度比它

res<-density(data) 
矢量

然後我嘗試的density結果轉換爲data.frame爲ploting準備:

framer<-function(data){return (data.frame(y=data$y, x=data$x)) } 

然後繪製它

res<-framer(density(fridayKlient1)) 
ggplot() + 
    geom_density(aes(x=x,y=y), colour="red" , data=res) 

。 但抱怨有:

ggplot2: object 'y' not found 
+0

返回的對象是一個列表,除了密度估計的x和y值(運行'str(res)'以查看列表中還有什麼)之外,還包含多個組件。我想你只需要'res1 = data.frame(res $ x,res $ y)'。 – eipi10

+0

或者如果你真的只想繪製它,'plot(density(data))' – G5W

+0

@ G5W不,我想覆蓋一些圖層,所以我需要使用'ggplot()+ geom_density' – Salman

回答

0

所有組件見str(res)

> head(data.frame(x = res$x, y = res$y)) 
     x   y 
1 130.0792 0.0009454737 
2 130.0985 0.0010042050 
3 130.1178 0.0010641591 
4 130.1370 0.0011299425 
5 130.1563 0.0011970552 
6 130.1755 0.0012693376 

但繪製在GGPLOT2密度的對象,你會做

ggplot(data.frame(x = fridayKlient1), aes(x = x)) + 
    geom_density() 
+0

@Salman它似乎你已經正確地回答了你的問題。 –

+0

是的,謝謝你 – Salman

0
ggplot(data = res, aes(x=x)) + 
    geom_density(colour="red") 

這應該解決您的問題。請參閱ggplot2文檔中的geom_density()。否則,去here

+0

那麼'y'呢? – Salman