8

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])
dvreed77
  • 2,217
  • 2
  • 27
  • 42
  • I suggest you read this: http://stackoverflow.com/questions/14254379/how-can-i-attach-a-pyplot-function-to-a-figure-instance/14261698#14261698 – tacaswell Jun 13 '13 at 13:47

2 Answers2

8

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)
Community
  • 1
  • 1
tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • 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. – dvreed77 Jun 14 '13 at 11:52
  • 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? – tacaswell Jun 14 '13 at 15:39
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.

Harpe
  • 316
  • 1
  • 9
  • 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. – dvreed77 Jun 13 '13 at 11:42
  • 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. – Harpe Jun 13 '13 at 12:42
  • 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. – Rutger Kassies Jun 13 '13 at 12:52
  • 2
    gah, that is a really round about way to do this! The pre-edited version is far preferable. – tacaswell Jun 13 '13 at 13:49