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

标签 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。它生成的图不正确,因为每个水处理都有一行,而不是每个“Mother”“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 中绘制这种类型的宽格式数据?转换/熔化数据所需的时间是巨大的,我想知道这是否值得,或者是否有某种解决方法可以消除熔化时产生的冗余单元。

感谢您的帮助,如果您需要更清楚地了解此问题,请告诉我,我可以进行编辑。

最佳答案

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

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

考虑到这一点,您可能需要搜索:[r] matplot ggplot2,就像我所做的那样,以及 see if this 看看这个或任何其他点击是否有效。

关于r - 在 R 中,使用 ggplot2 或基本图绘制宽格式数据。有没有办法在不熔化宽格式数据框的情况下使用 ggplot2 ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23230515/

相关文章:

r - 来自 dplyr/tidyverse 的 Complete() 函数不适用于 Shiny 交互变量

在循环中通过 ggplot 中的名称引用列

r - 在Windows机器上使用fread中的unix命令预处理文件

r - 在R中,有一种方法可以使用带有任意参数的pivot_longer作为cols规范

r - 在ggplot map 上叠加多边形

r - 将熔化的 table 变回 table

用melt reshape 数据

R:当维度超过 2 时 reshape 数据框

r - 将数值转换为二进制 (0/1)

R - 填充区域到 ggplot2 中的绘图顶部