2016-10-10 88 views
1

我是完全新的R,並希望插入一個簡單的彩色框圖例識別每個分配爲「data.1」和「data.2」,在下面qplot繪圖功能(從ggplot2包):如何插入密度圖中的圖例與Qplot在R

> V1 <- matrix(unlist(rnorm(200,-0.2,1))) 
> V2 <- matrix(unlist(rnorm(200,0.3,4))) 
> m <- data.frame(V1,V2) 
> qplot(V1, main="Observed distr.", data=m, 
geom='density',xlab="x",ylab="count",fill=I('green'), alpha=I(.5)) + 
geom_density(aes(V2),data=m,fill='red', alpha=I(.5)) 

我已經找到了解決方案,爲ggplot,但沒有爲qplotgeom='density'。曲線很好繪製,但沒有傳說出現。
我會接受任何解決方案,爲我提供帶有透明度的密度圖,標記爲座標軸,標題和彩色方塊圖例。謝謝。

+0

恕我直言:忘了'qplot',使用'ggplot':'庫(tidyverse); ggplot(M%>%聚集,AES(值,填充=鍵))+ geom_density(alpha = .5)+ scale_fill_manual(values = c(「green」,「red」),labels = c(「V1」=「myV1」))''。我想這將是他們的方式[在將來](https://blog.rstudio.org/2015/12/21/ggplot2-2-0-0/):_「使用qplot()在這個例子中已經被縮減了,這與ggplot2書的第2版是一致的,它消除了qplot(),而是有利於ggplot()。「_ – lukeA

+0

@lukeA:是的,我開始看到了這一點。我用'qplot'完成了。謝謝。 – Cbhihe

回答

1

作爲someone把它放在「ggplot喜歡'長'格式的數據:即每個維度的列和每個觀察的行」。因此,我們meltdata.frame

require(ggplot2) 
require(data.table) 
set.seed(10) # this is so you get the same numbers from rnorm. 
m <- data.frame(V1 = matrix(unlist(rnorm(200, -0.2, 1))), 
       V2 = matrix(unlist(rnorm(200, 0.3, 4)))) 

m <- melt(m) # This comes from data.table, yet, many alt. ways to achieve this 
head(m) 
    variable  value 
1  V1 -0.18125383 
2  V1 -0.38425254 
3  V1 -1.57133055 
4  V1 -0.79916772 
5  V1 0.09454513 
6  V1 0.18979430 

ggplot(data = m, aes(value, fill = variable)) + 
    geom_density(alpha = 0.5) 

enter image description here

+0

謝謝你snoram。正是我需要的。乾杯。 – Cbhihe