【问题标题】:Plot spectroscopic data (a matrix) with ggplot2 in R在 R 中使用 ggplot2 绘制光谱数据(矩阵)
【发布时间】:2015-09-17 23:37:10
【问题描述】:

我需要使用 R 中的 ggplot2(或 lattice)包绘制一个光谱数据矩阵,其中行由 2 个因子变量分组,因为它具有分面功能。

考虑使用来自pls 包的DS$NIR 光谱数据(矩阵)数据框DS

library(pls)
data(gasoline)
DS <-gasoline

让我们添加一些分组变量:

set.seed(0)
DS$Type <- as.factor(sample(c("Training set","Validation set","Others"),
                            nrow(DS),
                            replace = TRUE))

DS$Group <- cut(DS$octane,
                   breaks = c(80,86,88,90),
                   labels = c("Low","Medium","High"))

并查看数据:

str(DS)

'data.frame':   60 obs. of  4 variables:
 $ octane: num  85.3 85.2 88.5 83.4 87.9 ...
 $ NIR   : AsIs [1:60, 1:401] -0.050193 -0.044227 -0.046867 -0.046705 -0.050859 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr  "1" "2" "3" "4" ...
  .. ..$ : chr  "900 nm" "902 nm" "904 nm" "906 nm" ...
 $ Type  : Factor w/ 3 levels "Others","Training set",..: 1 2 3 3 1 2 1 1 3 3 ...
 $ Group : Factor w/ 3 levels "Low","Medium",..: 1 1 3 1 2 1 3 3 3 3 ...

我需要将DS$NIR 的每一行绘制为单独的一行。 X 轴值可以通过以下方式提取:

x <- as.numeric(gsub(" nm", "", dimnames(DS$NIR)[[2]]))
  1. 线条颜色应取决于因子Group 的水平。
  2. 线条应该是半透明的。
  3. 每个颜色组(即因子Group 的每个级别)都应该有一条不透明的实线,表示该组的平均值(或中位数)。
  4. 因子Type 的每个级别都应绘制在一个单独的方面。

我找到了example,它是如何绘制光谱数据的,但我很难理解并根据我的情况调整代码。

【问题讨论】:

  • 看看 hyperSpec 包,它在小插图中有很多详细的示例

标签: r matrix plot ggplot2


【解决方案1】:

在绘图之前,您的数据存在两个主要问题。

首先,NIR 列是一些奇怪的矩阵,不能很好地与其他函数配合使用。让我们解决这个问题:

DS <- cbind(DS, as.data.frame(unclass(DS$NIR)))
DS$NIR <- NULL

现在,数据很宽,而不是很长。让我们用一些dplyrtidyr 来解决这个问题:

library(dplyr)
library(tidyr)    
graphdat <- DS %>% mutate(row = row_number()) %>%
                   gather(nm, value, -octane, -Type, -Group, -row) %>% 
                   mutate(nm = extract_numeric(nm))

现在很容易绘制:

library(ggplot2)
ggplot(graphdat, aes(x = nm, y = value, group = row, color = Group)) + 
    geom_line() +
    facet_grid(Type~.)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 2013-03-25
    • 2021-02-10
    • 1970-01-01
    • 2018-04-08
    • 2016-10-20
    • 2012-10-26
    相关资源
    最近更新 更多