1

我有一个数据框(df1),格式如下:

           x1         y1         x2          y2
1 0.745779796  0.5728328 2.04029482 -0.71989471
2 0.008949224  0.8318262 1.01426596  1.20956795
3 2.390108913  0.8041999 1.63621459  0.19979352
4 1.478310218 -0.7179949 1.52394275  0.96091747
5 1.051357060  0.9700232 0.00546977  0.03604669
6 0.123499864  2.0340036 0.08231778  1.29889103

我最难使用 ggpplot 2 创建一个散点图,该散点图同时具有系列 1(y1 与 x1)和 2(y2 与 x2)。我已经尝试melt使用数据框来获得一个“因素”来使用 in aes(),但我确定我使用的 melt 错误,并且无法弄清楚为什么:

df<-melt(df,id.var)

我的主要问题是:有没有更简单的方法来组织这些数据,以便在一个ggplot命令中,我可以将每个 xy 对绘制为散点图上的单独系列?

4

1 回答 1

3

这里是基础包中的一个解决方案。但我很确定这是一份工作reshape。这里使用按列设置子集并创建 2 个 data.frames 并rbind聚合 data.frame 的解决方案。

data <-  do.call(rbind,lapply(1:2,function(i)
   {
     res <- data.frame(dat[,paste0(c('x','y'),i)],group=i)
     setNames(res,nm=c('x','y','group'))
   }))
rbind(head(data,3),tail(data,3))
             x          y group
1  0.745779796 0.57283280     1
2  0.008949224 0.83182620     1
3  2.390108913 0.80419990     1
41 1.523942750 0.96091747     2
51 0.005469770 0.03604669     2
61 0.082317780 1.29889103     2

然后我用geom_line这样的方式绘制它:

ggplot(data)+
  geom_line(aes(x=x,y=y,col=factor(group),group=group))

使用重塑编辑解决方案

dat.reshape <- reshape(dat, direction="long",  varying=list(c(1, 3), c(2, 4)), 
                       sep="", v.names=c("x", "y"))
ggplot(dat.reshape)+
  geom_line(aes(x=x,y=y,col=factor(time),group=time))+
  scale_color_discrete(name  ="Line Type",
                   breaks=c(1, 2),
                   labels=c("Woman", "Man"))

在此处输入图像描述

于 2013-04-10T16:58:40.860 回答