r - 使用 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 或调用密度函数时。
解决方案
由于您不提供示例数据,我将在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")
推荐阅读
- javascript - 上传内容后刷新引导模式对话框的主体
- javascript - 大写独立反应道具
- javascript - 我如何获取用户 ID 服务器端?
- php - 将“Ymd H:i:s”转换为“dmY H:i:s”
- jwt - 为什么使用 Auth0 的 CouchDB JWT 身份验证对我不起作用?
- python - Python 应用程序看不到 PSQL 更改
- octave - 在 Octave 返回错误中以 ' 作为版权符号的矩阵的转置
- java - 生命周期感知 LiveEvent 中的上下文为空
- python - 如何查看字符串中是否有任何ip
- python - 无法为大型数据集运行选择性 pandas 分析