Home > OS >  Pyplot claims that the Figure type does not have the attribute `add_subplot()`, but ONLY if the code
Pyplot claims that the Figure type does not have the attribute `add_subplot()`, but ONLY if the code

Time:09-27

The following code produces a canvas with two empty plots on it, which is exactly what it should do.

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec


class MakerOfTwoEmptyPlots(object):

    def __init__(self):

        self.fig = plt.figure()
        self.gs = GridSpec(1, 2, figure=self.fig)

        self.fig.add_subplot(self.gs[0, 0])
        self.fig.add_subplot(self.gs[0, 1])


plotter = MakerOfTwoEmptyPlots()
plt.show()

However, if I run the exact same code outside of a class, like so:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(1, 2, figure=fig)

fig.add_sublot(gs[0, 0])
fig.add_sublot(gs[0, 1])

plt.show()

I get the error AttributeError: 'Figure' object has no attribute 'add_sublot', despite the code being essentially identical and self.fig and fig being of the same type (I checked in the debugger). This is deeply confusing! Anybody know what's going on here?

Since this seems like the kind of problem that might depend on it, I'm using Python 3.9.1, MatPlotLib 3.3.3, and IntelliJ IDEA Community Edition 2020.3.

CodePudding user response:

It should be fig.subplot not fig.sublot:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(1, 2, figure=fig)

fig.add_subplot(gs[0, 0])
fig.add_subplot(gs[0, 1])

plt.show()

enter image description here

  • Related