2013-02-25 42 views
1

假設我熔化iris數據幀用於與GGPLOT2繪製如下:提到與ggplot元件使用熔化dataframes中的R

meltediris <- melt(iris) 

我現在可以通過從variable列中選擇出來繪製Petal.Width值:

ggplot(meltediris) + geom_density(aes(x=meltediris[meltediris$variable == 
                  "Petal.Width",]$value)) 

我想再由Species繪製Petal.Width值,所以我所做的:

ggplot(meltediris) + geom_density(aes(x=meltediris[meltediris$variable == 
              "Petal.Width",]$value, colour=Species)) 

它似乎工作,但我很驚訝它!數據幀meltediris[meltediris$variable == "Petal.Width",]$value的選定子集與整個融化數據幀(它只是一個子集)沒有相同的索引,那麼ggplot如何知道選擇正確的Species值?現在看來似乎應該要求我做的,而不是:

ggplot(meltediris) + geom_density(aes(x=meltediris[meltediris$variable == 
            "Petal.Width",]$value, 
        colour=meltediris[meltediris$variable == "Petal.Width",]$Species)) 

其中挑選融化數據框的選擇的子集的Species值。再舉一個例子,如果我這樣做:

ggplot(meltediris) + geom_density(aes(x=meltediris[meltediris[meltediris$variable == "Petal.Width",]$Species == "virginica",]$value, colour=Species)) 

好像ggplot應該只知道一個物種,因爲我選擇了非virginicas。當我這樣做時,它只能正確繪製一個物種,但仍然在圖例中顯示另外兩個Species值。它如何知道要做到這一點?我確信當我通過x=時,它無法讀取剩餘的數據幀值。 有人可以解釋ggplot如何從融化的數據框中挑選這些變量嗎?謝謝。

+1

你不使用子集代碼也物種提供了不一樣的長度的誤差 - 因此它不適合我至少工作 - GGPLOT2版本0.9.3,x86_64的,蘋果darwin9.8.0/x86_64的 – 2013-02-25 06:14:13

+0

它的工作原理在這裏 - 哪一行特別是你執行有問題? – user248237dfsf 2013-02-25 06:20:41

+0

我在兩個例子中都遇到了錯誤,其中你也沒有子類也物種(只是使用顏色=物種)。 – 2013-02-25 06:23:25

回答

2

就像是在評論說,當我試試這個:

ggplot(meltediris) + geom_density(
         aes(x=meltediris[meltediris$variable == 
               "Petal.Width",]$value, colour=Species)) 

我得到這個錯誤:

Error: Aesthetics must either be length one, 
     or the same length as the dataProblems: 
        meltediris[meltediris$variable == "Petal.Width", ]$value 

由於錯誤提示你必須給AES具有相同的長度。這裏沒有必要給data說法,因爲你給的所有值在AES(您AES是矢量)

例如,

X <- meltediris[meltediris$variable =="Petal.Width",]$value 
Col <- meltediris[meltediris$variable == "Petal.Width",]$Species 
ggplot() + geom_density(aes(x=X,colour=Col)) 

但我這是更好地子集中的所有data.frame meltediris在這種情況下。

ggplot(meltediris) + geom_density(aes(x=variable,colour=Species), 
       subset=.(variable=="Petal.Width"))