I am trying to replicate this plot using ggplot
pacman::p_load(tidyverse, pls, remotes)
install_github("rwehrens/ChemometricsWithR")
data(gasoline)
wavelengths <- seq(900,1700, 2)
matplot(wavelengths, t(gasoline$NIR), type = "l", lty = 1, xlab = "Wavelength (nm)", ylab = "1/R")
but cannot seem to make it work. The gasoline dataset is a tricky one: one of the two variables is a matrix which I have never encountered before. How can I clean up this dataset to make it tidy? I tried the following:
gasoline2 <- as.data.frame(as.matrix(gasoline)) %>%
pivot_longer(cols = -c(octane),
names_to = "wavelength",
values_to = "1/R")
but cannot seem to This code:
ggplot(gasoline, mapping = aes(x = wavelengths, y = t(gasoline$NIR)))+
geom_line(mapping = aes(color = octane))
is returning this error:
Error in `geom_line()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (60)
✖ Fix the following mappings: `x` and `y`
Backtrace:
1. base (local) `<fn>`(x)
2. ggplot2:::print.ggplot(x)
4. ggplot2:::ggplot_build.ggplot(x)
5. ggplot2:::by_layer(...)
12. ggplot2 (local) f(l = layers[[i]], d = data[[i]])
13. l$compute_aesthetics(d, plot)
14. ggplot2 (local) compute_aesthetics(..., self = self)
15. ggplot2:::check_aesthetics(evaled, n)



