【问题标题】:ggplot2:scatterplots for all possible combinations of variablesggplot2:所有可能的变量组合的散点图
【发布时间】:2023-03-24 06:01:01
【问题描述】:

我想为所有可能的变量组合绘制图表。我的代码如下:

 set.seed(12345)
a <- data.frame(Glabel=LETTERS[1:7],   A=rnorm(7, mean = 0, sd = 1),  B=rnorm(7, mean = 0, sd = 1),  C=rnorm(7, mean = 0, sd = 1))
T <- data.frame(Tlabel=LETTERS[11:20], A=rnorm(10, mean = 0, sd = 1), B=rnorm(10, mean = 0, sd = 1), C=rnorm(10, mean = 0, sd = 1))

library(ggplot2)
for(i in 2:(ncol(a)-1))
{
 for(j in (i+1):ncol(a))
 {
  r <- 0.08
  p <- ggplot(data=a, mapping=aes(x=a[, i], y=a[, j])) + geom_point() + theme_bw()
  p <- p + geom_text(data=a, mapping=aes(x=a[, i], y=a[, j], label=Glabel),
                 size=3, vjust=1.35, colour="black")
  p <- p + geom_segment(data = T, aes(xend = T[ ,i], yend=T[ ,j]),
                    x=0, y=0, colour="black",
                    arrow=arrow(angle=25, length=unit(0.25, "cm")))
  p <- p + geom_text(data=T, aes(x=T[ ,i], y=T[ ,j], label=Tlabel), size=3, vjust=0, colour="red")
dev.new()
  print(p)
} 
 }

此代码运行良好。但是这里使用的方法不推荐(See @baptiste comment),在功能上不起作用。我想知道完成此任务的最佳和推荐方法是什么。提前感谢您的帮助。

【问题讨论】:

  • 你看过 GGally 包中的 ggpairs 吗?
  • @Joran 的想法很好,但这个问题本身很有趣。我可以很容易地接近,但 ggplot 要求你必须提供数据集的一个对象,而且每次我应用它时,我都不能在函数调用中低效地制作一个假数据集。
  • 您可能可以使用我在下面的回复并将您添加的内容放入其中。除非您说您在线程中进行了编辑,否则请不要更改内容,因为以后的搜索者将无法理解为什么答案看起来与“原始”问题完全不同。

标签: r ggplot2


【解决方案1】:

好吧,这是垃圾,但我能做到的最好。这是超级低效的,因为它通过lapply 的每个循环重新创建部分数据。也许别人有更好的东西:

MAT <- outer(names(df)[-1], names(df)[-1], paste)
combs <- sapply(MAT[lower.tri(MAT)], function(x) strsplit(x, " "))
ind <- lapply(combs, function(x) match(x, names(df)))

plotter <- function(cn) { #start junky function
    NAMES <- colnames(df)[cn]
    df2 <- df[cn]
    names(df2)<- c('x1', 'x2')
    p <- ggplot(data=df2, aes(x1, x2)) + geom_point() + theme_bw() +
        scale_x_continuous(name=NAMES[1]) +
        scale_y_continuous(name=NAMES[2])
        dev.new()
        print(p)
} #end of junky function

lapply(ind,  function(x) plotter(cn=x))

编辑:这更好一点:

x <- match(names(df)[-1], names(df))
MAT <- outer(x, x, paste)
combs <- t(sapply(MAT[lower.tri(MAT)], function(x) as.numeric(unlist(strsplit(x, " ")))))

plotter <- function(cn) {
    NAMES <- colnames(df)[cn]
    df2 <- df[cn]
    names(df2)<- c('x1', 'x2')
    p <- ggplot(data=df2, aes(x1, x2)) + geom_point() + theme_bw() +
        scale_x_continuous(name=NAMES[1]) +
        scale_y_continuous(name=NAMES[2])
        dev.new()
        print(p)
}

apply(combs,  1, function(x) plotter(cn=x))

【讨论】:

  • 感谢您的回答。当您发布答案时,我正在编辑。请参阅我编辑的问题。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
相关资源
最近更新 更多