首页 > 解决方案 > 使用 ggplots 绘制一个数据框列与所有其他列并在 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 或调用密度函数时。

标签: rdataframeggplot2probability-density

解决方案


由于您不提供示例数据,我将在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")

在此处输入图像描述


推荐阅读