我正在為我大學的一門課程開發家庭作業作為助教。
我們正在使用 Otter Grader(OKPy 的擴展)對我們通過 Jupyter Notebooks 提供的指導作業的學生提交進行評分。
學生被要求在他們的地塊上繪制水平線matplotlib.pyplot.axhline(),我希望使用一個assert電話來確定他們是否將水平線添加到他們的地塊中。
有沒有辦法查看已添加到 matplotlib 中的 pyplot 的所有屬性?
uj5u.com熱心網友回復:
我不相信有一種方法可以查看該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物件添加到坐標區物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/406725.html
標籤:
