2013-02-10 24 views
9

我還是很新的R,並碰到了一個繪圖的問題,我無法找到答案。我如何可以繪製多個變量並排側作爲R點陣圖?

我有看起來像這樣的一個數據幀(雖然很多大):

df <- data.frame(Treatment= rep(c("A", "B", "C"), each = 6), 
       LocA=sample(1:100, 18), 
       LocB=sample(1:100, 18), 
       LocC=sample(1:100, 18)) 

而且我想,看起來像在Excel中製作this one散點圖。這正是我想要的格式:爲每個並排側每個位置的治療點陣圖,與一起在一個圖中多個位置的數據。 (深表歉意不能夠在這裏張貼的圖片;發佈圖像需要10聲譽。)

enter image description here

這是沒有問題的,使每個位置的情節,用點顏色編碼,等上:

ggplot(data = df, aes(x=Treatment, y=LocA, color = Treatment)) + geom_point() 

但我不知道如何將位置B和C添加到同一圖表。

任何建議,將不勝感激!

+0

重塑數據爲長表則刻面的情節。 – mnel 2013-02-10 23:47:40

回答

10

作爲一對夫婦的人都提到,你需要「融化」的數據,得到它變成一個「長」的形式。

library(reshape2) 
df_melted <- melt(df, id.vars=c("Treatment")) 
colnames(df_melted)[2] <- "Location" 

在ggplot術語中,通過「閃避」來實現像並排治療這樣的不同組。通常對於像barplots你可以說position="dodge"geom_point似乎需要多一點手工規格:

ggplot(data=df_melted, aes(x=Location, y=value, color=Treatment)) + 
    geom_point(position=position_dodge(width=0.3)) 

enter image description here

+0

無需手動閃避,只需要使用'position_dodge'調用'geom_point'內。 (DF,aes(y = value,x = variable))+ geom_point(aes(color = Treatment),position = position_dodge(width = 1) ))' – mnel 2013-02-11 00:06:28

+0

媽,'位置=「躲閃」'沒有工作,所以我以爲躲着不是爲點執行。現在編輯我的答案。 – Marius 2013-02-11 00:09:09

+1

謝謝!這正是我正在尋找的。坦率地說,我寧願使用boxplot,但我的老闆確信點圖很好,因爲她喜歡看到點集羣並看到異常值(是的,我知道所有的信息都存在於boxplot中,沒有,我無法解釋爲什麼看到單個點是「更好的」,除非我進入一些非常花哨的東西,比如試圖給每個人(原始數據框中的行)一個特定的符號,在這種情況下,你可以試着看看是否有一個這在所有地區都一直很高)。 – phosphorelated 2013-02-11 00:12:05

3

你需要重塑數據。這裏使用reshape2

library(reshape2) 
dat.m <- melt(dat, id.vars='Treatment') 
library(ggplot2) 
ggplot(data = dat.m, 
     aes(x=Treatment, y=value,shape = Treatment,color=Treatment)) + 
        geom_point()+facet_grid(~variable) 

enter image description here

既然你想有一個dotplot一個例子,我還提出了一個格子的解決方案。我認爲這種情況更適合。

dotplot(value~Treatment|variable, 
     groups = Treatment, data=dat.m, 
     pch=c(25,19), 
     par.strip.text=list(cex=3), 
     cex=2) 

enter image description here