【发布时间】:2018-06-13 14:40:31
【问题描述】:
我有一个包含 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 或调用密度函数时。
【问题讨论】:
-
您可以发布您的数据吗?
标签: r dataframe ggplot2 probability-density