【问题标题】:How can I line up graphs with a common x axis made using 2 different data frames when the x axis values are not identical?当 x 轴值不相同时,如何使用使用 2 个不同数据框制作的公共 x 轴排列图形?
【发布时间】:2019-08-25 19:13:55
【问题描述】:

我有 2 个数据集,都有深度列。但是 df1 有 ~400 行,而 df2 有 7000 行。 df1 的深度值(我想成为我的常用 x 轴)从 48-120 到 df2 48-133。当我制作地块时,范围内的这种差异会阻止地块排列。

df1 样本数据

深度 L F P Depo 67.48 1.003 1.063 1.066 涡轮 67.63 1.004 1.020 1.024 67.73 1.011 1.017 1.028 67.83 1.006 1.007 1.014 涡轮 67.92 1.003 1.029 1.032 临 68.06 1.004 1.007 1.011 专业版

df2 样本数据

深度钙钛 67.41 378 241 67.91 422 253 67.94 402 262 67.95 412 264 67.98 377 266 68.01 386 263 68.02 326 266 68.08 338 219

我尝试制作单独的绘图,然后使用 grid.draw 但这不起作用。

从 DF1 创建绘图

Lin <- ggplot(DF1, aes(x=depth, y=L)) + geom_line() + geom_point(data = DF1, aes(x=depth, y=L, color = Depo))
Fab <- ggplot(DF1, aes(x=depth, y=P)) + geom_path() + geom_point(data = DF1, aes(x=depth, y=P, color = Depo))
Fol <- ggplot(DF1, aes(x=depth, y=F)) + geom_path() + geom_point(data = DF1, aes(x=depth, y=F, color = Depo))

将绘图与 grid.draw 相结合适用于 df1 图表

grid.draw(rbind(ggplotGrob(Fol), ggplotGrob(Lin), ggplotGrob(Fab), size = "last"))

从 DF2 创建绘图

Ca1 <- ggplot(DF2, aes(x=depth, y=Ca)) + geom_path()

当我尝试合并来自 2 个数据帧的图时,它会引发错误,即 x 和 y 必须具有相同数量的列。

grid.draw(rbind(ggplotGrob(Fol), ggplotGrob(Lin), ggplotGrob(Fab), ggplotGrob(Ca1), size = "last"))

Cowplot 有效,但深度与我的 df2 图 (Ca1) 不一致

plot_grid(Fol, Lin, Fab, Ca1, align="h", axis="b", nrow = 4, rel_widths = c(1,2))

我尝试了其他一些排列图表的方法,但似乎它们都排列了图表,而不是 x 轴的实际值。我也尝试使用 facet wrap,但不知道如何组合 2 个 dfs。在我寻找解决这个问题的过程中,我一直看到将 2 个数据框组合起来,但我看不出这将如何处理我的数据? 有谁知道我如何排列这些图表?我有很多变量需要从两个数据集中进行比较。

【问题讨论】:

  • 尝试其他软件包,看看它是否适合你stackoverflow.com/a/48164920/786542
  • 谢谢。 egg 和 patchwork 都给了我同样的东西,df2 的情节没有正确对齐。不过我会继续努力的。

标签: r dataframe ggplot2


【解决方案1】:

要整合两个只有“深度”相同的数据集,您可以将剩余的数字列收集为“长”格式,我们将数据类型标记在一列(此处为“col”)和另一个值(此处为“val”)。

合并数据后,我们可以使用facet_wrap(~col, scales = "free_y") 为每个变量制作分面,但有一个共同的 x 轴。

library(tidyverse)
df_combo <- 
  bind_rows(
    df1 %>% gather(col, val, L:P),
    df2 %>% gather(col, val, Ca:Ti)
  )

ggplot(df_combo, aes(depth, val, color = Depo)) +
  geom_path() +
  facet_wrap(~col, scales = "free_y", ncol = 1)

【讨论】:

  • 如果没有看到你准备好的数据样本就很难回答。我建议逐步进行并确认您准备的每个表格看起来都正确。某处是否有嵌套数据或矩阵数据? gather 步骤使用的列范围是否适合您的数据?是否存在任何拼写错误,您所指的列在您的数据中并不完全以这种形式存在(包括大写)?
  • 抱歉,我发现问题后试图删除该评论。只是我的真实数据使用了名称深度,以及样本数据深度。您在上面提供的代码非常完美。我所做的唯一更改是分别添加 geom_point 来为点而不是线着色。现在我只需要弄清楚如何阻止我的 df2 中的 NA 点被着色,因为我失去了细节,因为有超过 7000 个点
  • ggplot(df_combo, aes(depth, val)) + geom_path() + geom_point(aes(color=Depo)) + facet_wrap(~col, scales = "free_y", ncol = 1)
猜你喜欢
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
相关资源
最近更新 更多