Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot to Specific Axes in Matplotlib

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])
like image 746
dvreed77 Avatar asked Jun 13 '13 11:06

dvreed77


People also ask

How do you separate plots in python?

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.


2 Answers

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)
like image 170
tacaswell Avatar answered Oct 16 '22 08:10

tacaswell


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.

like image 31
Harpe Avatar answered Oct 16 '22 09:10

Harpe