2013-12-20 43 views
1

我想從矩陣中創建一個箱形圖,其中幾個變量按兩個因子級別分組。矩陣的箱型圖由因子

一些樣本數據:

mymatrix = structure(list(Treatment = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 
1L, 2L, 1L, 2L, 2L), .Label = c("con", "treat"), class = "factor"), 
c1 = c(13L, 93L, 6L, 3L, 45L, 1L, 69L, 38L, 23L, 48L, 82L 
), c5 = c(33L, 79L, 3L, 5L, 17L, 22L, 94L, 99L, 85L, 74L, 
9L), c3 = c(96L, 52L, 0L, 6L, 60L, 14L, 69L, 96L, 57L, 99L, 
39L), c8 = c(40L, 27L, 94L, 68L, 76L, 73L, 88L, 45L, 67L, 
95L, 85L), c12 = c(20L, 14L, 53L, 9L, 93L, 1L, 12L, 45L, 
59L, 38L, 25L)), .Names = c("Treatment", "c1", "c5", "c3", 
"c8", "c12"), class = "data.frame", row.names = c("1a", "1b", 
"2a", "2b", "3a", "3b", "4a", "4b", "5a", "5b", "5c")) 

我能得到每個變量的箱線圖,但我不能在同一時間管理對他們組:提前

boxplot(as.matrix(mymatrix[,2:6])) 
boxplot(as.matrix(mymatrix[,2:6])~Treatment, data=mymatrix) 

感謝您的任何幫幫我。

+0

有沒有辦法讓代碼更易讀? –

+0

@LoïcFaure-Lacroix:這是將R數據發佈到SO的首選方式。這並不容易閱讀,但您可以將其複製並粘貼到您的R控制檯中並精確地再現對象。 –

+0

@DrewSteen不熟悉R.謝謝你會記住這一點。 –

回答

2
v <- stack(mymatrix[-1]) 
v$Treatment <- mymatrix$Treatment 
boxplot(values~Treatment+ind, v) 

第一部分將給予我們一個data.frame這樣的:

values ind 
1  13 c1 
2  93 c1 
... 
11  82 c1 
12  33 c5 
... 
22  9 c5 
23  96 c3 
... 
55  25 c12 

然後我們追加Treatment列,只是情節如常。使用reshapeas suggested by Drew

v <- melt(mymatrix, id.vars="Treatment") 
boxplot(value~Treatment+variable, v) 
+0

謝謝你解決了這個問題。其實想要繪製的是:boxplot(values〜Treatment + ind,v) – user2474427

1

我個人喜歡用ggplot2/reshape2的方法 - 它也許是有點艱難學習在第一,但一旦你得到它好,我認爲這讓事情變得更加簡單。

請注意,您的'矩陣'實際上不是一個矩陣,它是一個數據框架。這很方便,因爲我建議的方法只適用於數據框。

str(mymatrix) 
'data.frame': 11 obs. of 6 variables: 
... 

首先,「重塑」它「長」格式,其中每行代表一個不同的觀察

dfm <- melt(mymatrix, id.vars="Treatment") 

(我的慣例是將附加字母m任何熔融數據幀)。

接下來,使用ggplot2進行繪圖。我已經映射Treatment列於x軸,C1-C12列的填充顏色(重構而得名variable),但GGPLOT2的語法,讓您輕鬆改變了:

ggplot(dfm, aes(x=Treatment, y=value, fill=variable)) + 
    geom_boxplot() 

enter image description here

+0

+1:不知道'reshape'包 –