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

如何将自定义类传入Matplotlib进行绘图?

用自定义类实例数组在Matplotlib中绘图的优化方案

方案1:列表推导式直接提取字段

无需修改自定义类,调用plt.plot时通过列表推导式直接提取time字段,代码简洁直观:

from dataclasses import dataclass
import matplotlib.pyplot as plt

@dataclass
class TestCase:
    name: str
    time: float

# 实例化测试用例
d1 = TestCase("Case1", 2.5)
d2 = TestCase("Case2", 4.3)
d3 = TestCase("Case3", 1.8)

# 提取time字段绘图
plt.plot([tc.time for tc in [d1, d2, d3]])
plt.ylabel('Execution Time')
plt.show()

方案2:给自定义类添加数值转换方法

如果想实现plt.plot([d1, d2])这种直接传入实例列表的调用方式,给TestCase类添加__float__方法,让Matplotlib自动将实例转换为对应的time数值:

from dataclasses import dataclass
import matplotlib.pyplot as plt

@dataclass
class TestCase:
    name: str
    time: float

    def __float__(self):
        return self.time

# 实例化测试用例
d1 = TestCase("Case1", 2.5)
d2 = TestCase("Case2", 4.3)
d3 = TestCase("Case3", 1.8)

# 直接传入实例列表绘图
plt.plot([d1, d2, d3])
plt.ylabel('Execution Time')
plt.show()

方案3:使用map函数提取字段

习惯函数式编程的话,可以用map函数结合lambda表达式提取time字段:

# 基于方案1的类定义和实例
plt.plot(list(map(lambda tc: tc.time, [d1, d2, d3])))
plt.ylabel('Execution Time')
plt.show()

内容的提问来源于stack exchange,提问作者Matthieu Raynaud de Fitte

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:50:24