【问题标题】:ggplot2 scatter plot of data in long format with unknown/variable site namesggplot2 长格式数据散点图,具有未知/可变站点名称
【发布时间】:2020-06-24 01:31:32
【问题描述】:

我正在尝试制作散点图,用于比较以长格式输入的不同站点的值。

我可以使用固定的站点名称轻松地做到这一点,但我希望能够在输入数据中使用不同的站点名称来运行它。目前脚本将数据转换为宽格式然后绘制它们,但这意味着我必须手动更改站点名称。

最初,如果我在输入数据中有 2 个站点时它可以正常工作,我会很高兴,但如果它有 3 个站点来进行所有站点组合并将它们组合起来,就像我在下面所做的那样。

ggplot 中是否有任何功能可以从长数据帧创建散点图?

我发现了一个类似的问题Scatter plot in ggplot, one numeric variable across two groups,但它的答案基本上是我的出发点,但它没有相关名称可能改变的问题。

下面的代码给了我我想要的,但是如果我改变了输入数据(例如将站点更改为rep(letters[4:6],each = 10),它将变得无用。

  library(tidyverse)

set.seed(2)
testdf <- tibble(Site = rep(letters[1:3], each = 10), x = rep(1:10,3), y = rnorm(30, mean = 1, sd = 0.05)*x)


testdf_w <- pivot_wider(testdf, names_from = Site, values_from = y)

p1 <- ggplot(testdf_w, aes(x = a, y = b))+
  geom_point()

p1 # This is all I'd need if there were only 2 sites


library(patchwork)
#> Warning: package 'patchwork' was built under R version 3.5.3

p2 <- ggplot(testdf_w, aes(x = a, y = c))+
  geom_point()

p3 <- ggplot(testdf_w, aes(x = b, y = c))+
  geom_point()

p1 + p2 + p3

reprex package (v0.3.0) 于 2020 年 3 月 12 日创建

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以遍历唯一站点名称的组合并使用aes_string 将列名称指定为字符串。

    library(tidyverse)
    
    set.seed(2)
    testdf <- tibble(Site = rep(letters[1:3], each = 10),
                     x = rep(1:10,3),
                     y = rnorm(30, mean = 1, sd = 0.05)*x)
    testdf_w <- pivot_wider(testdf, names_from = Site, values_from = y)
    
    
    library(patchwork)
    sites <- unique(testdf$Site)
    p <- NULL
    for (s1 in sites) {
      for (s2 in sites) {
        if (s1 >= s2) next
    
        tmp <- ggplot(testdf_w, aes_string(x = s1, y = s2)) +
          geom_point()
        if (is.null(p)) {
          p <- tmp
        } else {
          p <- p + tmp
        }
      }
    }
    p
    

    此外,您可能还喜欢 ggpairs 以获取此特定应用程序。

    library(GGally)
    ggpairs(select(testdf_w, -x))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-24
      • 2023-03-09
      • 2019-07-19
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      相关资源
      最近更新 更多