ggplot的散点图

问题描述:

我想在熔化的数据框中做变量散点图(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

正如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