2015-10-19 105 views
0

我想在熔化的數據框中做變量散點圖(xy),如下所示。ggplot的散點圖

df 
class var mean   
0  x 4.25 
0  y 6.25 
1  x 2.00 
1  y 11.00 

我試過這個,但它繪製了4點。如何繪製x和y?

library(ggplot2) 

ggplot(df, aes(x=mean, y=mean, group=var, colour=class)) + 
geom_point(size=5, shape=21, fill="white") 
+5

這種罕見的,但你的數據的格式是「太」長。對於每個觀察,您需要在同一行上使用x和y值。 – Heroka

回答

3

正如Heroka指出的那樣,您需要的數據是更寬類型的格式。如果數據是這樣讀取的,則可以使用以下內容對其進行轉換。

## you don't need this since you already have df 
text = "class var mean 
0 x 4.25 
0 y 6.25 
1 x 2.00 
1 y 11.00" 
df = read.delim(textConnection(text),header=TRUE,strip.white=TRUE,  
stringsAsFactors = FALSE, sep = " ");df2 

## use this library to switch from long-wide 
library(reshape2) 

df2 = dcast(df, class ~ var, value.var = "mean") 

library(ggplot2) 
ggplot(df2, aes(x=x, y=y, colour=class)) + 
    geom_point(size=5, shape=21, fill="white") 

enter image description here

+1

它應該是'df2 = dcast(df,class〜var,value.var =「mean」)'? – torm

+0

感謝您的支持。 –

+1

我會將課程轉換爲因子;目前的規模是不必要的/令人困惑的。 – Heroka