You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R ggplot展示两个变量的概率分布情况

优化方案:直观展示变量分位数概率

1. 增强累积分布图(ECDF)的可读性

原有的ECDF图可以通过添加分位点标注,让目标概率对应的数值一目了然。修改后的代码如下:

# 计算X变量的95%分位数
x_95 <- quantile(df$FLUID_TOT, 0.95)

plot1 <- df %>% 
  ggplot(aes(x = FLUID_TOT)) +
  stat_ecdf(geom = "step", size = 1) +
  # 添加95%分位点的垂直线和文字标注
  geom_vline(xintercept = x_95, color = "red", linetype = "dashed") +
  geom_text(aes(x = x_95, y = 0.95), 
            label = paste0("95% of X < ", round(x_95)),
            hjust = -0.1, color = "red") +
  labs(title = "累积分布函数(ECDF)- X变量",
       x = "X (FLUID_TOT)", y = "累积概率") +
  theme_bw()

修改后,ECDF图会用红色虚线标出95%分位点的位置,并直接显示对应的数值,完美匹配你想要展示的“约95%的X值低于8000”的信息。

2. 在散点图中加入Y变量的分位数标注

针对Y变量,我们可以同样计算95%分位数,然后在散点图中添加水平线和标注,同时结合X的分位点,展示双变量的联合分布特征:

# 计算Y变量的95%分位数
y_95 <- quantile(df$y, 0.95)

plot2 <- df %>% 
  ggplot(aes(x = FLUID_TOT, y = y)) +
  geom_point(alpha = 0.6) +
  # 添加X和Y的95%分位点参考线
  geom_vline(xintercept = x_95, color = "red", linetype = "dashed") +
  geom_hline(yintercept = y_95, color = "blue", linetype = "dashed") +
  # 添加对应标注
  geom_text(aes(x = x_95, y = max(df$y)), 
            label = paste0("95% of X < ", round(x_95)),
            hjust = -0.1, color = "red") +
  geom_text(aes(x = max(df$FLUID_TOT), y = y_95), 
            label = paste0("95% of Y < ", round(y_95)),
            vjust = -0.5, color = "blue") +
  labs(title = "X与Y散点图(含95%分位点标注)",
       x = "X (FLUID_TOT)", y = "Y") +
  theme_bw()

这个散点图既保留了原始的变量关系展示,又清晰标出了两个变量各自95%分位点的位置,读者能直观看到同时满足X<8000和Y<6500的样本分布情况。

3. 可选:合并两张图(用patchwork包)

如果想要把两张图放在同一画布对比展示,提升信息传递效率,可以使用patchwork包:

library(patchwork)

# 合并两张图为横向布局
combined_plot <- plot1 + plot2 + plot_layout(ncol = 2)

# 显示合并后的图
print(combined_plot)

内容的提问来源于stack exchange,提问作者Brent B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:19:44