如何将散点图象限标签从观测计数改为百分比并调整指定标签位置
解决方案
1. 将象限标签改为百分比格式
ggpmisc的stat_quadrant_counts默认输出n=数值的计数标签,要改成p=数值%的百分比形式,只需自定义label参数,结合总观测数计算占比,再用scales::percent()格式化:
library(ggplot2) library(ggpmisc) library(gginnards) # 示例数据集 set.seed(123) df <- data.frame(x = rnorm(100), y = rnorm(100)) # 先计算总观测数 total_n <- nrow(df) ggplot(df, aes(x, y)) + geom_point() + # 自定义象限计数标签为百分比 stat_quadrant_counts( quadrants = 4, label = function(quadrant_n) sprintf("p=%s", scales::percent(quadrant_n / total_n)), geom = "text", color = "blue" ) + # 保留原蓝色象限线 geom_vline(xintercept = 0, color = "blue") + geom_hline(yintercept = 0, color = "blue")
核心逻辑是给label传入自定义函数,用每个象限的计数除以总观测数,转成百分比格式后拼接成p=XX%的形式。
2. 微调指定标签的位置
要只移动原n=27(对应新标签p=27%)和n=22(对应p=22%)的标签,有两种实用方法:
方法一:按象限编号条件偏移
默认象限编号规则:右上1、左上2、左下3、右下4。如果这两个标签分别在象限2和3,直接用position_nudge加条件判断设置偏移量:
ggplot(df, aes(x, y)) + geom_point() + stat_quadrant_counts( quadrants = 4, label = function(quadrant_n) sprintf("p=%s", scales::percent(quadrant_n / total_n)), geom = "text", color = "blue", # 象限2、3的标签向左移0.5,其余不动(偏移量可按需调整) position = position_nudge( x = ifelse(stat(quadrant) %in% c(2, 3), -0.5, 0) ) ) + geom_vline(xintercept = 0, color = "blue") + geom_hline(yintercept = 0, color = "blue")
方法二:用gginnards直接修改标签数据
如果不确定象限编号,直接通过标签文本定位要调整的元素,修改其x坐标:
# 先绘制基础图形 p <- ggplot(df, aes(x, y)) + geom_point() + stat_quadrant_counts( quadrants = 4, label = function(quadrant_n) sprintf("p=%s", scales::percent(quadrant_n / total_n)), geom = "text", color = "blue" ) + geom_vline(xintercept = 0, color = "blue") + geom_hline(yintercept = 0, color = "blue") # 修改指定标签的位置 p_adjusted <- p %>% modify_geom("text", data = function(data) { # 定位p=27%和p=22%的标签,向左移0.5 target_labels <- c("p=27%", "p=22%") data$x[data$label %in% target_labels] <- data$x[data$label %in% target_labels] - 0.5 data } ) print(p_adjusted)
偏移量-0.5可根据图形实际尺寸自行调整,直到标签位置满意为止。
内容的提问来源于stack exchange,提问作者Robin
相关产品推荐
相关产品推荐

