I am trying to plot a spectra in R with a revered x axis using matplot:
matplot(x = colnames(aaaLowCarbonAbsorbanceSpec),
y = t(aaaLowCarbonAbsorbanceSpec),
main = "Low Carbon Absorbance", type = 'l',
xlab = "Wavenumber / cm-1", ylab = "Absorbance",
col = rgb(red = 1, green = 0.5, blue = 0.5, alpha = 1))
Plots the curve:
I used the rev()
function in:
matplot(x = rev(colnames(aaaLowCarbonAbsorbanceSpec)),
y = t(aaaLowCarbonAbsorbanceSpec),
main = "Low Carbon Absorbance Rev", type = 'l',
xlab = "Wavenumber / cm-1", ylab = "Absorbance",
col = rgb(red = 1, green = 0.5, blue = 0.5, alpha = 1))
and plotted:
But the x axis remains the same - how do I get it in descending order?
Thanks
Here is an image of my data frame:
Change the xlim=
for your plot.
set.seed(42)
dat <- setNames(as.data.frame(as.list(runif(10))), seq(4000, 3955, by=-5))
rownames(dat) <- "SOG130123"
dat
# 4000 3995 3990 3985 3980 3975 3970 3965 3960 3955
# SOG130123 0.914806 0.9370754 0.2861395 0.8304476 0.6417455 0.5190959 0.7365883 0.1346666 0.6569923 0.7050648
matplot(as.numeric(colnames(dat)), t(dat), type = "l")
matplot(as.numeric(colnames(dat)), t(dat), type = "l", xlim = c(4000, 3955))
More data:
set.seed(42)
dat <- setNames(data.frame(matrix(runif(30), ncol=10)), seq(4000, 3955, by=-5))
rownames(dat) <- c("SOG130123", "SOG130124", "SOG130125")
dat
# 4000 3995 3990 3985 3980 3975 3970 3965 3960 3955
# SOG130123 0.9148060 0.8304476 0.7365883 0.7050648 0.9346722 0.9400145 0.4749971 0.1387102 0.08243756 0.9057381
# SOG130124 0.9370754 0.6417455 0.1346666 0.4577418 0.2554288 0.9782264 0.5603327 0.9888917 0.51421178 0.4469696
# SOG130125 0.2861395 0.5190959 0.6569923 0.7191123 0.4622928 0.1174874 0.9040314 0.9466682 0.39020347 0.8360043
Reshape and plot:
library(dplyr)
# library(tibble) # rownames_to_column
library(tidyr) # pivot_longer
library(ggplot2)
dat %>%
tibble::rownames_to_column() %>%
pivot_longer(-rowname, names_to = "x", values_to = "y") %>%
mutate(x = as.numeric(x)) %>%
ggplot(aes(x, y)) +
geom_line(aes(group = rowname, color = rowname)) +
scale_x_reverse()
dplyr
is not required to do this, nor is tibble
, but they make it fairly simple to get things started. For reshaping data to support this, ggplot2
really wants "long" data, and the two best tools to support that are tidyr::pivot_longer
and reshape2::melt
(and data.table::melt
, nearly the same except for using data.table
instead of a data.frame
for data).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.