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

时间:2018-06-13 14:40:31

标签: r dataframe ggplot2 probability-density

我有一个包含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或调用密度函数时。

1 个答案:

答案 0 :(得分:0)

由于您未提供样本数据,我将在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")

enter image description here