11

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])
1

2 Answers 2

10

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, thats pretty close to what I ended up doing. Can you tell me why there is an axes property though? Setting this property should associate the line artists with that axes according to the documentation, but I don't see that.
I think it is an artifact of the way that the documentation is generate, the Line2D object has an axes property, but it is set by the code in plot and the value you pass in is ignored. Can you point me to where the documentation says it should have that behavior?
3

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.

4 Comments

Yeah, I understand that I can do that, but that won't work for my plot function within my class definition. I guess I can manually look to see if a axes property is set, but I guess I'm confused as to why the plot function takes an axes property if its not to plot to that axes.
I have edited the example to use the function sca() which sets the currenty active axes. It should work now with the normal plot function, so that you can use that one in your class.
How does the plot function of your class work? For me your example works fine for the plot command of matplotlib.pyplot. The plot is made in the specified axes.
gah, that is a really round about way to do this! The pre-edited version is far preferable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.