我想繪制一個帶有分面和象限的散點圖 - 我想在每個分面 象限上顯示基本統計資料,例如平均值、中位數、每個象限中的點數等。我的搜索使我找到了 ggpubr 包中的 stat_mean() 函式、ggpp 包中的 geom_quadrant_lines 和 stat_quadrant_counts() 函式
但是,使用 stat_mean 函式,我只能列印整個方面的“平均值”,但無法繪制每個象限的平均值。我也無法找出正確的方法來獲得其他統計資料,如中位數、相關性等 - 無論是方面還是象限。
非常感謝您對此的任何幫助!
library(ggplot2)
library(ggpubr)
library(ggpp)
#>
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#>
#> annotate
data <- data.frame(
xlabel = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), ylabel = c(10, 12, 14, 16, 18, 6, 5, 4, 3, 2),
facets = c("a", "a", "a", "a", "a", "b", "b", "b", "b", "b")
)
ggplot(data = data, aes(x = xlabel, y = ylabel, color = facets))
geom_point()
facet_wrap(facets ~ ., )
stat_mean(color = "black")
stat_quadrant_counts(xintercept = 3, yintercept = 9)
geom_quadrant_lines(xintercept = 3, yintercept = 9)

由reprex 包(v2.0.1)于 2021 年 11 月 17 日創建
uj5u.com熱心網友回復:
非常尷尬地隱藏在這個包中的是函式which_quadrant,它有助于根據您的 x/y 坐標和截距找到象限。此資訊可用于簡單計算您所謂的“均值”(而不是:質心)。
另一方面,如果我是包維護者,我會將函式保持獨立,而不是作為 Stat$compute_panel 層的一部分,因為這對于除錯來說真的很痛苦。
library(tidyverse)
library(ggpp)
data <- data.frame(xlabel = 1:10, ylabel = c(seq(10,18,2), 6:2),
facets= rep(letters[1:2], each = 5))
## modified from StatQuadrantCounts$compute_panel
which_quadrant <- function(x, y, xintercept, yintercept, pool.along = "none") {
z <- ifelse(x >= xintercept & y >= yintercept,
1L,
ifelse(x >= xintercept & y < yintercept,
2L,
ifelse(x < xintercept & y < yintercept,
3L,
4L
)
)
)
if (pool.along == "x") {
z <- ifelse(z %in% c(1L, 4L), 1L, 2L)
} else if (pool.along == "y") {
z <- ifelse(z %in% c(1L, 2L), 1L, 4L)
}
z
}
quad_summary <-
data %>%
mutate(quadrant = which_quadrant(x = xlabel, y= ylabel, xintercept = 3, yintercept =9)) %>%
group_by(facets, quadrant) %>%
mutate(across(contains("label"), mean))
ggplot(data, aes(x=xlabel, y = ylabel))
geom_point(aes(color = facets))
facet_wrap(facets~.,)
stat_quadrant_counts(xintercept = 3, yintercept =9)
geom_quadrant_lines(xintercept = 3, yintercept =9)
geom_point(data = quad_summary, shape = 2, size = 2, aes(xlabel, ylabel))

由reprex 包(v2.0.1)于 2021 年 11 月 17 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/359578.html
