Search code examples
pythonmatplotlibaxes

Why a figure's Axes is not created?


I'm trying not to use pyplot, but with the code below I only print a completely white figure.

I found with 'fig.axes' that no axes at all is created for 'fig', although 'ax' is a 'matplotlib.axes._axes.Axes' instance. I'm wondering why...

(I know that there are other ways to do obtain the plot, but my question is "what is wrong/missing here?").

from matplotlib.figure import Figure
from matplotlib.axes import Axes

from matplotlib.backends.backend_agg import FigureCanvasAgg
from numpy import random 

data = [random.randn(5) for i in range(5)]

fig = Figure(figsize = (20,10))
canvas = FigureCanvasAgg(fig)

ax = Axes(fig, [0.1,0.1,0.5,0.7])

ax.pcolormesh(data)

canvas.print_figure('test')

Solution

  • The problem is that the axes is not added to the figure. Usually you would add an axes via any of the figure's methods, like fig.add_axes() or fig.add_subplot()

    Doing that here, e.g.

    ax = fig.add_subplot(111)  # instead of ax = Axes(fig, [0.1,0.1,0.5,0.7])
    

    gives you the desired output.

    There is really no reason not to use those methods. If you instantiate the Axes yourself, you need to call it

    ax = Axes(fig, [0.1,0.1,0.5,0.7])
    fig.add_axes(ax)
    

    but this is really just one extra line and no benefit compared to

    ax = fig.add_axes([0.1,0.1,0.5,0.7])