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

如何查找matplotlib内部结构中scatter散点图的对应数据?

matplotlib scatter()散点图内部数据访问方法

plt.plot()返回的是Line2D对象,存储在Axes.lines列表中;而plt.scatter()返回的是PathCollection类型实例,相关数据存储在Axes对象的collections列表中。

访问示例代码

和你给出的plot()示例逻辑对应,散点图数据访问代码如下:

import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt

np.random.seed(1)

size = 10
a = np.random.random(size)
b = np.random.random(size)
df = pd.DataFrame({'a': a, 'b': b, })

# 绘制散点图,返回PathCollection实例
g = plt.scatter(df.a, df.b, marker='o')

# 方法1:直接通过scatter返回的对象获取数据
offsets = g.get_offsets()
print("x轴数据:", offsets[:, 0])
print("y轴数据:", offsets[:, 1])

# 方法2:通过Axes的collections列表访问(适合没有返回对象的场景)
print("通过axes访问x轴数据:", g.axes.collections[0].get_offsets()[:,0])

# 其他散点属性也可以通过对应方法获取
print("散点大小列表:", g.get_sizes())
print("散点填充色列表:", g.get_facecolors())

plt.show()

事件回调场景使用说明

你开发canvas.mpl_connect('axes_leave_event', leave_axes)功能时,可以直接在回调函数中通过事件对象拿到Axes实例,再访问对应数据:

def leave_axes(event):
    if not event.inaxes:
        return
    # 按绘制顺序取对应索引的collection即可
    scatter_data = event.inaxes.collections[0].get_offsets()
    x_data = scatter_data[:,0]
    y_data = scatter_data[:,1]
    # 后续业务逻辑处理

提示:如果同一Axes下绘制了多个散点图、等高线图等collection类型的可视化元素,按绘制先后顺序对应collections列表的索引,按需调整索引值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:54:00