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])
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.