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

如何自动获取散点图绿点的ax.inset_axes()坐标以嵌入子图

解决方案

核心是把散点的数据坐标转换成inset_axes需要的轴域归一化坐标(范围0-1,对应轴的左下角到右上角),具体实现如下:

实现步骤

  • 用ax.transData.transform()将绿点的(x,y)数据坐标转为屏幕像素坐标
  • 用ax.transAxes.inverted().transform()把屏幕坐标转回轴域归一化坐标
  • 基于转换后的坐标调整子图位置(避免遮挡散点),再创建内嵌子图

完整示例代码

import numpy as np
import matplotlib.pyplot as plt

# 生成椭圆分布的模拟绿点数据
np.random.seed(42)
green_x = np.random.normal(0, 2, 5)
green_y = np.random.normal(0, 1, 5)

fig, ax = plt.subplots(figsize=(8,6))
# 绘制绿点
scatter = ax.scatter(green_x, green_y, marker="o", s=50, edgecolors="green", c="green")

# 遍历每个绿点添加内嵌子图
for x, y in zip(green_x, green_y):
    # 坐标转换:数据坐标 → 屏幕坐标 → 轴域归一化坐标
    screen_pos = ax.transData.transform((x, y))
    ax_norm_pos = ax.transAxes.inverted().transform(screen_pos)
    
    # 设置内嵌子图的尺寸和位置偏移
    inset_size = 0.1
    # 让子图在散点上方居中,避免遮挡
    ins_x = ax_norm_pos[0] - inset_size / 2
    ins_y = ax_norm_pos[1] + 0.02
    ins = ax.inset_axes([ins_x, ins_y, inset_size, inset_size])
    
    # 绘制子图内容(示例为直线)
    xxx = np.arange(10)
    yyy = np.arange(10)
    ins.plot(xxx, yyy)
    # 隐藏子图坐标轴(可选,优化视觉效果)
    ins.set_xticks([])
    ins.set_yticks([])

plt.show()

关键说明

  • transData和transAxes是Matplotlib的坐标变换工具,能自动适配轴的缩放和位置变化,散点移动时子图位置会同步更新
  • 可根据需求调整inset_size和位置偏移量,比如子图过大时缩小尺寸,或调整ins_y让子图在散点下方/左侧
  • 若散点数量较多,建议添加重叠检测逻辑,避免子图互相遮挡

内容的提问来源于stack exchange,提问作者The Dude

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:06:27