在R中,使用ggplot2或基本绘图绘制宽格式数据。有没有办法在不融合宽格式数据框架的情况下使用ggplot2?

时间:2014-04-22 21:25:10

标签: r ggplot2 melt

我有一个看起来像这样的数据框(虽然大了几千倍)。

df<-data.frame(sample(1:100,10,replace=F),sample(1:100,10,replace=F),runif(10,0,1),runif(10,0,1),runif(10,0,1), rep(c("none","summer","winter","sping","allyear"),2))
names(df)<-c("Mother","ID","Wavelength1","Wavelength2","Wavelength3","WaterTreatment")
df
   Mother ID Wavelength1 Wavelength2 Wavelength3 WaterTreatment
1       2 34   0.9143670  0.03077356  0.82859497           none
2      24 75   0.6173382  0.05958151  0.66552338         summer
3      62 77   0.2655572  0.63731302  0.30267893         winter
4      30 98   0.9823510  0.45690437  0.40818031          sping
5       4 11   0.7503750  0.93737900  0.24909228        allyear
6      55 76   0.6451885  0.60138475  0.86044856           none
7      97 21   0.5711019  0.99732068  0.04706894         summer
8      87 14   0.7699293  0.81617911  0.18940531         winter
9      92 30   0.5855559  0.70152698  0.73375917          sping
10     93 44   0.1040359  0.85259166  0.37882469        allyear

我想在y轴上绘制波长值,在x上绘制波长。我有两种方法可以做到这一点:

第一种方法有效,但使用基础图并需要更多代码:

colors=c("red","blue","green","orange","yellow")
plot(0,0,xlim=c(1,3),ylim=c(0,1),type="l")
for (i in 1:10) {
  if      (df$WaterTreatment[i]=="none"){
    a<-1
  } else if (df$WaterTreatment[i]=="allyear") {
    a<-2
  }else if (df$WaterTreatment[i]=="summer") {
    a<-3
  }else if (df$WaterTreatment[i]=="winter") {
    a<-4
  }else if (df$WaterTreatment[i]=="spring") {
    a<-5
  }
  lines(seq(1,3,1),df[i,3:5],type="l",col=colors[a])
}

第二种方法:我试图将数据融合成长格式,然后使用ggplot2。它产生的图是不正确的,因为每个水处理都有一条线,而不是每个“母”“ID”的一条线(唯一标识符,原始数据框中的行是什么)。

require(reshape2)
require(data.table)
df_m<-melt(df,id.var=c("Mother","ID","WaterTreatment"))
df_m$variable<-as.numeric(df_m$variable)  #sets wavelengths to numeric
qplot(x=df_m$variable,y=df_m$value,data=df_m,color=df_m$WaterTreatment,geom = 'line')

ggplot2可能缺少一些简单的东西来修复线条的绘图。我是ggplot的新手,但我正在努力学习它,并希望在这个应用程序中使用它。

但更广泛地说,有没有一种有效的方法在ggplot2中绘制这种类型的宽格式数据?转换/融化数据所需的时间是巨大的,我想知道它是否值得,或者是否有某种解决办法可以消除融化时产生的冗余单元。

感谢您的帮助,如果您需要更清楚这个问题,请告诉我,我可以编辑。

2 个答案:

答案 0 :(得分:1)

我想指出你基本上是在重新发明现有的基础绘图功能,即matplot。这可以取代你的情节和for循环:

matplot(1:3, t( df[ ,3:5] ), type="l",col=colors[ as.numeric(df$WaterTreatment)] )

考虑到这一点,您可能需要像我一样搜索SO:[r] matplot ggplot2see if this 看看这个或任何其他点击是否有效。

答案 1 :(得分:1)

您似乎希望每个ID都有一个单独的行,但您希望根据WaterTreatment的值着色。如果是这样,你可以在ggplot中这样做:

ggplot(df_m, aes(x=variable, y=value, group=ID, colour=WaterTreatment)) + 
       geom_line() + geom_point()

您还可以使用刻面来更轻松地查看不同级别的水处理

ggplot(df_m, aes(x=variable, y=value, group=ID, colour=WaterTreatment)) + 
    geom_line() + geom_point() + 
    facet_grid(WaterTreatment ~ .)

回答你的一般问题:ggplot设置为使用“长”(即融化)数据帧最容易和最有效地工作。我猜你可以使用“宽”数据框,并为你想要绘制的每个因子组合绘制单独的图层。但与单个melt命令相比,这将是一项额外的工作,可以使您的数据格式正确。