Ger
Ger

Reputation: 9756

What matplotlib object should I send/receive through class method?

Using matplotlib, you can create figure, manage axes of this figure (subplot actually ?) but I do not understand why and how, at the end you do plt.show() to see the plot. Why this is not a method of the fig or ax object ? How does the module (plt) know what to plot ?

import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.randn(2, 100)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, "ro")
plt.show()

I ask this question because now, suppose you have a class with a method in order to make a plot of the data contained in the object. My question is what object I am suppose to return ? Axes, Figure or plt ? Is one of the followings method the right way to do that :

def get_plot(self):
    """ return plt """
    plt.plot(self.data.x, self.data.y)
    return plt

def get_plot(self):
    """ return fig """
    fig = plt.figure()
    plt.plot(self.data.x, self.data.y)
    return fig

def get_plot(self):
    """ return ax """
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(self.data.x, self.data.y)
    return ax

The last one is, maybe, the clearest because you see on each line the object on which you are working. But if I get a Figure or Axes object. How can I easily plot it ?

Upvotes: 1

Views: 114

Answers (1)

tmdavison
tmdavison

Reputation: 69173

plt.show will show all figures that have been created. So there's no need to for pyplot to "know" which one, since all will be displayed. From the docs:

Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt.

In non-interactive mode, display all figures and block until the figures have been closed

I would personally return the fig or ax, since then you can perform other functions on that object (e.g. ax.set_xlim, or fig.savefig() etc.). There's no need to return plt, since that is the pyplot module that you have already imported.

Upvotes: 1

Related Questions