Roland
Roland

Reputation: 131

Wrong usage of R package reshape2 to plot with ggplot2?

I would like to plot some data with ggplot2. My data is originally in wide format, and so I would like to transform it to long format first.

Somehow "melt" produces a table I cannot use with ggplot2 as desired. I guess I am using it wrong, but I could sadly not find out, how to solve the problem.

I would like to plot the variables s1 and s2 vs the wavelength. This is a minimal half working example:

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

It would be very great if you could explain the problem.

Thank you very much!

Upvotes: 0

Views: 177

Answers (1)

NelsonGon
NelsonGon

Reputation: 13319

Is this what you had in mind?

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

Using reshape2 and the tidyverse

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

Upvotes: 1

Related Questions