gpt4 book ai didi

r - 如何在 GGally 中使用您自己的密度函数创建较低密度图

转载 作者:行者123 更新时间:2023-12-02 05:53:26 25 4
gpt4 key购买 nike

使用以下代码:

library(GGally)
library(tidyverse)
library(viridis)


dat <- iris %>% select(-Species)

my_fn <- function(data, mapping, ...){
# Using default ggplot density function

p <- ggplot(data = data, mapping = mapping) +
stat_density2d(aes(fill=..density..), geom="tile", contour = FALSE) +
scale_fill_gradientn(colours=viridis::viridis(100, option="viridis"))
p
}


ggpairs(dat, lower=list(continuous=my_fn)) +
theme_void()

我可以创建这个图:

enter image description here

我的问题是如何使用以下方案更改 GGally 较低密度图:

library(MASS)
# Get density of points in 2 dimensions.
# @param x A numeric vector.
# @param y A numeric vector.
# @param n Create a square n by n grid to compute density.
# @return The density within each square.
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])
}



# Data wrangling method2 --------------------------------------------------
theme_set(theme_bw(base_size = 16))
tbl <- as.tibble(iris) %>%
select(-Species)


# tbl
dens_wrapper <- function (tbl=NULL, var1=NULL, var2=NULL) {
tbl_pair <- tbl %>%
select_(var1, var2)
x <- tbl_pair %>% pull(var1)
y <- tbl_pair %>% pull(var2)
tbl_pair$density <- get_density(x,y)
tbl_pair
}

feature1 = "Sepal.Length"
feature2 = "Petal.Length"
tbl_pair1 <- dens_wrapper(tbl=tbl, var1=feature1, var2=feature2)
ggplot(tbl_pair1) +
geom_point(aes_string(feature1, feature2, color = 'density')) +
scale_color_viridis()

产生这个:enter image description here

最佳答案

使用与 Change colors in ggpairs now that params is deprecated 类似的想法,您只需将计算添加到您自己定义的函数中即可。

my_fn <- function(data, mapping, N=100, ...){

get_density <- function(x, y, n ) {
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])
}

X <- eval_data_col(data, mapping$x)
Y <- eval_data_col(data, mapping$y)

data$density <- get_density(x=X, y=Y, n=N)

p <- ggplot(data, mapping) +
geom_point(aes(colour=density), ...) +
scale_color_viridis()
p
}

ggpairs(dat, lower=list(continuous=my_fn)) +
theme_bw()

产品:

enter image description here

关于r - 如何在 GGally 中使用您自己的密度函数创建较低密度图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44984822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com