How can I plot to a specific axes in matplotlib? I created my own object which has its own plot method and takes standard args and kwargs to adjust line color, width, etc, I would also like to be able to plot to a specific axes too.
I see there is an axes property that accepts an Axes object but no matter what it still only plots to the last created axes.
Here is an example of what I want
fig, ax = subplots(2, 1)
s = my_object()
t = my_object()
s.plot(axes=ax[0])
t.plot(axes=ax[1])
To create multiple plots use matplotlib. pyplot. subplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid.
As I said in the comment, read
How can I attach a pyplot function to a figure instance? for an explanation of the difference between the OO and state-machine interfaces to matplotlib
.
You should modify your plotting functions to be something like
def plot(..., ax=None, **kwargs):
if ax is None:
ax = gca()
ax.plot(..., **kwargs)
You can use the plot function of a specific axes:
import matplotlib.pyplot as plt
from scipy import sin, cos
f, ax = plt.subplots(2,1)
x = [1,2,3,4,5,6,7,8,9]
y1 = sin(x)
y2 = cos(x)
plt.sca(ax[0])
plt.plot(x,y1)
plt.sca(ax[1])
plt.plot(x,y2)
plt.show()
This should plot to the two different subplots.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With