使用 ggplots 绘制一个数据框列与所有其他列的对比,并在 R 中显示密度

Plot one data frame column against all other columns using ggplots and showing densities in R

我有一个包含 20 列的数据框,我想针对数据框中的每一列绘制一个特定的列(称为 BB)。我需要的图是概率密度图,我使用以下代码生成一个图(以绘制列 BB 与 AA 为例):

mydata = as.data.frame(fread("filename.txt")) #read my data as data frame

#function to calculate density
get_density <- function(x, y, n = 100) {
  dens <- MASS::kde2d(x = x, y = y, n = n)
  ix <- findInterval(x, dens$x)
  iy <- findInterval(y, dens$y)
  ii <- cbind(ix, iy)
  return(dens$z[ii])
}
set.seed(1)

#define the x and y of the plot; x = column called AA; y = column called BB
xy1 <- data.frame(
  x = mydata$AA,
  y = mydata$BB
)

#call function get_density to calculate density for the defined x an y
xy1$density <- get_density(xy1$x, xy1$y) 

#Plot
ggplot(xy1) + geom_point(aes(x, y, color = density), size = 3, pch = 20) + scale_color_viridis() +
  labs(title = "BB vs. AA") +
  scale_x_continuous(name="AA") +
  scale_y_continuous(name="BB")

如果有人可以建议使用上面的密度函数和 ggplot 命令生成多个 BB 图的方法,我们将不胜感激。我尝试添加一个循环,但发现它太复杂了,尤其是在定义要绘制的 x 和 y 或调用密度函数时。

由于您不提供示例数据,我将在 mtcars 上进行演示。我们将数据转换为长格式,计算密度,并绘制多面图。我们将 mpg 列与所有其他列进行对比。

library(dplyr)
library(tidyr)
mtlong = gather(mtcars, key = "var", value = "value", -mpg) %>%
    group_by(var) %>%
    mutate(density = get_density(value, mpg))

ggplot(mtlong, aes(x = value, y = mpg, color = density)) +
    geom_point(pch = 20, size = 3) +
    labs(x = "") +
    facet_wrap(~ var, scales = "free")