使用stat_dots按第三变量着色导致分位数点图分布拆分问题
解决方案
问题出在color映射会自动加入分组依据,导致每个变量下的不同相关强度被拆分为独立组,进而被分散排列。只需强制指定分组仅基于variable,同时保留颜色映射即可解决:
library(dplyr) library(ggplot2) library(ggdist) set.seed(123) data <- data.frame( variable = rep(c("Variable1", "Variable2", "Variable3"), each = 300), correlation = c(rnorm(300, 0.2, 0.1), rnorm(300, 0.4, 0.1), rnorm(300, 0.6, 0.1)) ) data <- data %>% mutate(correlation_strength = case_when( abs(correlation) < 0.3 ~ "Small", abs(correlation) >= 0.3 & abs(correlation) < 0.5 ~ "Medium", abs(correlation) >= 0.5 ~ "Strong" )) # 核心修改:明确指定分组为variable,颜色仅用于映射不参与分组 ggplot(data, aes(x = variable, y = correlation, group = variable)) + stat_dots(aes(color = correlation_strength), quantiles = 50) + scale_color_manual(values = c("Small" = "blue", "Medium" = "green", "Strong" = "red")) + theme_minimal() + labs(title = "Posterior Draws of Correlation Coefficients", subtitle = "Dots colored by correlation strength", x = "Variable", y = "Correlation Coefficient", color = "Correlation Strength")
关键说明
- 全局
aes中指定group=variable,强制stat_dots仅按变量分组计算点的排列位置,避免color变量干扰分组逻辑。 - 将
color=correlation_strength移至stat_dots的aes内部,仅实现颜色映射,不参与分组拆分。 - 移除了
position=position_dodge(width=0.8),默认的点排列逻辑会在每个x轴类别下紧凑排列所有点,无需额外 dodge。
内容的提问来源于stack exchange,提问作者bfoste01
相关产品推荐
相关产品推荐

