用ggplot散布图

时间:2015-10-19 11:41:45

标签: r ggplot2

我想在熔化的数据框中对变量进行散点图(xy),如下所示。

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")

1 个答案:

答案 0 :(得分: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