如何提取每個密度圖的值矩陣?
例如,我感興趣的是當 weight = 71 時,橙子、蘋果、梨子、香蕉的密度是多少?
下面是最小的例子:
library(ggplot2)
set.seed(1234)
df = data.frame(
fruits = factor(rep(c("Orange", "Apple", "Pears", "Banana"), each = 200)),
weight = round(c(rnorm(200, mean = 55, sd=5),
rnorm(200, mean=65, sd=5),
rnorm(200, mean=70, sd=5),
rnorm(200, mean=75, sd=5)))
)
dim(df) [1] 800 2
ggplot(df, aes(x = weight))
geom_density()
facet_grid(fruits ~ ., scales = "free", space = "free")

uj5u.com熱心網友回復:
將繪圖保存在變數中,使用ggplot_build面板構建資料結構并按面板拆分資料。然后插值approx以獲取新值。
g <- ggplot(df, aes(x = weight))
geom_density()
facet_grid(fruits ~ ., scales = "free", space = "free")
p <- ggplot_build(g)
# These are the columns of interest
p$data[[1]]$x
p$data[[1]]$density
p$data[[1]]$PANEL
p$data[[1]]按面板拆分串列成員,但僅保留x和density值。然后回圈遍歷拆分資料以按水果組進行插值。
sp <- split(p$data[[1]][c("x", "density")], p$data[[1]]$PANEL)
new_weight <- 71
sapply(sp, \(DF){
with(DF, approx(x, density, xout = new_weight))
})
# 1 2 3 4
#x 71 71 71 71
#y 0.04066888 0.05716947 0.001319164 0.07467761
或者,在不事先拆分資料的情況下,使用by.
b <- by(p$data[[1]][c("x", "density")], p$data[[1]]$PANEL, \(DF){
with(DF, approx(x, density, xout = new_weight))
})
do.call(rbind, lapply(b, as.data.frame))
# x y
#1 71 0.040668880
#2 71 0.057169474
#3 71 0.001319164
#4 71 0.074677607
uj5u.com熱心網友回復:
我認為底層densityinggplot2類似于stats::density,因此我們可以使用它來構建相同的資訊
df %>%
group_by(fruits) %>%
nest() %>%
ungroup() %>%
mutate(density = data %>% map(. %>%
`[[`("weight") %>%
density.default)) %>%
hoist(density, "x", "y") %>%
select(-density, -data) %>%
unnest(c(x,y)) %>%
group_by(fruits) %>%
slice_min(abs(x - 71), n = 1) %>%
ungroup() %>%
identity()
# A tibble: 5 x 3
fruits x y
<fct> <dbl> <dbl>
1 Apple 71.0 0.0409
2 Banana 71.0 0.0574
3 Orange 71.0 0.00131
4 Pears 71.0 0.0747
5 Pears 71.0 0.0747
如果您認為這還不夠,那么這是從您指定的情節中提取的內容:
gg_density_plot %>%
ggplot_build() %>%
`[[`("data") %>%
`[[`(1) %>%
as_tibble() %>%
# glimpse() %>%
# count(PANEL) # panel is fruit
group_by(PANEL) %>%
slice_min(abs(x - 71), n = 1) %>%
ungroup() %>%
select(PANEL, x, y, density)
# A tibble: 4 x 4
PANEL x y density
<fct> <dbl> <dbl> <dbl>
1 1 71.0 0.0410 0.0410
2 2 71.0 0.0568 0.0568
3 3 71.0 0.00135 0.00135
4 4 71.0 0.0747 0.0747
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335781.html
