Skip to content Skip to sidebar Skip to footer

Creating A Class To Product Subplots

I was wondering about how to design a nice class in order to produce a matplotlib plot suitable for my purpose. The first thing that I want to obtain is a class that could be call

Solution 1:

Essentially, you can't, or at least shouldn't. The return of a class should be an instance of itself.

However you may call a class, e.g.

import matplotlib.pyplot as plt

classMyClass():
    def__init__(self, **parameters):
        self.fig, self.axs = plt.subplots(**parameters)

    def__call__(self):
        return self.fig, self.axs

fig, axs = MyClass(figsize=(6,5))()

The drawback of this is that you directly loose any handler for the created class instance. This means that the above would be much simpler being written as function,

import matplotlib.pyplot as plt

defmyfunction(**parameters):
    fig, axs = plt.subplots(**parameters)
    return fig, axs

fig, axs = myfunction(figsize=(6,5))

So in order for the use of a class to make any sense, one would probably want to store it somehow and then make use of its attributes or methods.

import matplotlib.pyplot as plt

classMyClass():
    def__init__(self, **parameters):
        self.fig, self.axs = plt.subplots(**parameters)

myclass = MyClass(figsize=(6,5))
fig = myclass.fig
axs = myclass.axs

Solution 2:

Adding on to the other answer, you can also create a class that implements the __iter__ function which emulates the class as a tuple, allowing it to return fig, axs:

classMyClass:def__init__(self, params):
        self.fig, self.axs = plt.subplots()
        # Do stuff heredef__iter__(self):
        for e in (self.fig, self.axs):
            yield e

fig, axs = MyClass(params)

However this is rather unorthodox, as described by @ImportanceOfBeingErnest.

Post a Comment for "Creating A Class To Product Subplots"