我可以在不显示图形的情况下查看 pyplot 的所有属性吗?

Can I see all attributes of a pyplot without showing the graph?

我正在为我大学的一门课程做助教。

我们正在使用 Otter Grader(OKPy 的扩展)对我们通过 Jupyter Notebooks 提供的指导作业的学生提交进行评分。

学生被要求使用 matplotlib.pyplot.axhline() 在他们的地块上绘制水平线,我希望使用 assert 调用来确定他们是否将水平线添加到他们的地块。

有没有办法在matplotlib中查看已添加到pyplot的所有属性?

我不相信有办法查看是否使用了 axhline 属性,但是有一种方法可以通过访问所有 line2D 使用 lines 属性的对象。

import matplotlib.pyplot as plt
import numpy as np


def is_horizontal(line2d):
    x, y = line2d.get_data()
    y = np.array(y)  # The axhline method does not return data as a numpy array
    y_bool = y == y[0]  # Returns a boolean array of True or False if the first number equals all the other numbers
    return np.all(y_bool)


t = np.linspace(-10, 10, 1000)

plt.plot(t, t**2)
plt.plot(t, t)
plt.axhline(y=5, xmin=-10, xmax=10)

ax = plt.gca()

assert any(map(is_horizontal, ax.lines)), 'There are no horizontal lines on the plot.'

plt.show()

如果没有至少一个 line2D 对象包含所有 y 值都相同的数据,此代码将引发错误。

请注意,为了使上述工作正常,必须使用 axhline 属性而不是 hlines 方法。 hlines 方法不会将 line2D 对象添加到坐标区对象。