使用 ggplot2 绘制 R 包 reshape2 的错误用法?

Wrong usage of R package reshape2 to plot with ggplot2?

我想用 ggplot2 绘制一些数据。 我的数据本来是宽格式的,所以我想先把它转换成长格式。

不知何故 "melt" 产生了 table 我无法按需要使用 ggplot2。 我想我用错了,但遗憾的是我找不到解决问题的方法。

我想绘制变量 s1 和 s2 与波长的关系图。 这是一个最小的半工作示例:

#Generate fake data:
data <- cbind(wavelength = seq(1,10), s1 = seq(21,30), s3 = seq(41,50))

#Convert to long format:
#install.packages("reshape2")
library(reshape2)
datLong <- melt(data          = data,
            id.vars       = c("wavelength"),
            measure.vars  = c("s1","s2"),
            variable.name = "variable",
            value.name    = "value")

#install.packages("ggplot2")
library("ggplot2")

#The following delivers the error "Error: Attempted to create layer with no stat."
 ggplot(data = datLong, mapping = aes(x = wavelength, y = value)) + layer(geom = "point") 

#This plots something, but it seems that "melt" produced a wrong format as wavelength, s1, s2 are on the x-axis.
ggplot() + layer(data = datLong, mapping = aes(x=Var2, y=value), geom = "point", stat = "identity", position_dodge(width = 3))

如能说明问题就太好了

非常感谢!

这是你的想法吗?

library(ggplot2)
library(dplyr)
library(tidyr)
#or just library(tidyverse)
as.tibble(data) %>% 
  gather("Var","Val",-wavelength) %>% 
  ggplot(mapping = aes(x = wavelength, y = Val,col=Var)) + geom_point()

使用 reshape2tidyverse

as.tibble(data) %>% 
  melt(id.vars=c("wavelength")) %>% 
  ggplot(mapping = aes(x = wavelength, y = value,col=variable)) + geom_point()