如何绘制 (ggplot) 同一图 R 中的两个图表

How to plot (ggplot) two charts in the same plot R

提问人:oceanpath 提问时间:1/6/2023 最后编辑:fatihyildizhanoceanpath 更新时间:1/7/2023 访问量:51

问:

我需要通过将两个图表放在同一个图中来比较 2 个光谱。

我不能使用 Melted 函数,因为我的两个数据集是 2 个 FTIR 光谱,x 个数字(波数)不完全相同。

我用它来单独绘制图表:

sacola57 <-read_excel("57.xlsx", sheet=1)

ggplot(sacola57, aes(x=Wavenumber,
                 y=Absorbance)) +
geom_line() +
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

PADRAO <-read_excel("padrao.xlsx", sheet=1)
ggplot(PADRAO, aes(x=Wavenumber,
               y=Absorbance)) +
geom_line() +
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

萨科拉57:

Sacola SS

帕德拉奥:

Padrao SS

我试过这个:

sacola58 <- read_excel("58.xlsx", sheet=1)
padrao <-read_excel("padrao.xlsx", sheet=1)
head(sacolas58)
head(padrao)

sacolas = merge(sacola58, padrao, by="Wavenumber")

sacolasMelted <- reshape2::melt(sacolas, id.var='Wavenumber')
head(sacolasMelted)

ggplot(sacolasMelted, aes(x=Wavenumber, y=value, col=variable,)) + geom_line() + theme_bw() +
labs( x = "Comprimento de onda (cm-1)", y = "Absorbância", color = "Amostra")+
scale_color_manual(labels = c("sacola branca", "sacola transparente", "sacola verde"), values = c("palevioletred2", "paleturquoise4", "red"))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

并返回:

1 波数吸光度.x 吸光度.y <0 行> ( row.names 长度 0)

head(sacola58
 +      )
# A tibble: 6 × 2
 Wavenumber Absorbance
   <dbl>      <dbl>
 1       650.     0.0341
 2       652.     0.0316
 3       654.     0.0285
 4       656.     0.0288
 5       658.     0.0306
 6       660.     0.0341
> head(padrao)
# A tibble: 6 × 2
 Wavenumber Absorbance
   <dbl>      <dbl>
1       650.      0.176
2       653.      0.180
3       656.      0.178
4       659.      0.171
5       662.      0.179
6       665.      0.173
r ggplot2 图表 线

评论


答:

0赞 Jon Spring 1/6/2023 #1

这对你有用吗?我不认为你需要重塑你的数据,你可以把行堆叠起来,只要你做一列来区分每行与哪个光谱相关。

sacola58 <- read_excel("58.xlsx", sheet=1)
sacola58$Src = "sacola58"
padrao <-read_excel("padrao.xlsx", sheet=1)
padrao$Src = "padrao"
combo <- rbind(sacola58, padrao)

我希望这会变成这样的东西:

data.frame(
  stringsAsFactors = FALSE,
               Src = c("sacola58","sacola58",
                       "sacola58","sacola58","sacola58","sacola58","padrao",
                       "padrao","padrao","padrao","padrao","padrao"),
        Wavenumber = c(650L,652L,654L,656L,658L,
                       660L,650L,653L,656L,659L,662L,665L),
        Absorbance = c(0.0341,0.0316,0.0285,0.0288,
                       0.0306,0.0341,0.176,0.18,0.178,0.171,0.179,0.173)
) -> combo

你可以这样绘制:

ggplot(combo, aes(x=Wavenumber, y=Absorbance, col=Src))) +
  geom_line()

enter image description here