Issue
I am working on developing homework as a TA for a course at my university.
We are using Otter Grader (an extension of OKPy) to grade student submissions of guided homework we provide through Jupyter Notebooks.
Students are being asked to plot horizontal lines on their plots using matplotlib.pyplot.axhline()
, and I am hoping to use an assert
call to determine whether they added the horizontal line to their plots.
Is there a way to see all attributes that have been added to a pyplot in matplotlib?
Solution
I don't believe there is a way to see if the axhline
attribute has been used or not, but there is a way to see if the lines are horizontal by accessing all the line2D
objects using the lines
attribute.
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()
This code will raise the error if there is not at least one line2D
object that contains data in which all the y values are the same.
Note that in order for the above to work, the axhline
attribute has to be used instead of the hlines
method. The hlines
method does not add the line2D
object to the axes object.
Answered By - Gabe Morris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.