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

如何在ggplot2的stat_ellipse中显示中心点及计算其坐标

解决ggplot2 stat_ellipse显示中心点的问题

方法一:直接在ggplot2中添加中心点

stat_ellipse本身不会自动输出椭圆中心点,但可以结合stat_summary快速添加——它会自动计算x、y变量的均值(也就是椭圆的中心)并绘制:

library(ggplot2)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  stat_ellipse() +
  # 用红色填充的菱形标记均值中心
  stat_summary(fun = mean, geom = "point", shape = 23, size = 3, fill = "red")

方法二:手动计算中心点坐标

椭圆的中心点本质就是两个变量的样本均值。椭圆的形状由协方差矩阵(基于均值、标准差和相关系数)决定,但中心本身直接取变量均值即可,不需要复杂的矩阵运算。

手动计算并添加的代码示例:

library(ggplot2)

# 计算x和y的均值
center_x <- mean(mtcars$wt)
center_y <- mean(mtcars$mpg)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  stat_ellipse() +
  # 手动添加蓝色填充的菱形中心点
  geom_point(aes(x = center_x, y = center_y), shape = 23, size = 3, fill = "blue")

如果已经有协方差矩阵,也可以从计算结果中提取中心点:比如用cov.wt函数得到的结果里,center字段就是对应的均值向量,也就是椭圆中心坐标。

内容的提问来源于stack exchange,提问作者Scrooge Mike

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:40:19