Search code examples
pythonmatplotlibaxes

Default Matplotlib Axes children


I just want to understand what the last 4 entries of

plt.gca().get_children()

are. I know the first text is the plot label, but don't know what the other two are. I've looked elsewhere and it seems that they are always located at 0,1 and 1,1. Lastly, I am asuming that the last rectangle is actually the "surface" where everything is placed/plotted in the Axes.

[<matplotlib.lines.Line2D at 0x7fa18484dba8>,
 <matplotlib.spines.Spine at 0x7fa1848992b0>,
 <matplotlib.spines.Spine at 0x7fa1848994e0>,
 <matplotlib.spines.Spine at 0x7fa1848996d8>,
 <matplotlib.spines.Spine at 0x7fa1848998d0>,
 <matplotlib.axis.XAxis at 0x7fa184899a90>,
 <matplotlib.axis.YAxis at 0x7fa184824860>,
 <matplotlib.text.Text at 0x7fa1848c2a58>,
 <matplotlib.text.Text at 0x7fa1848c2c50>,
 <matplotlib.text.Text at 0x7fa1848c24e0>,
 <matplotlib.patches.Rectangle at 0x7fa1848c2518>]

I saw examples of this in here (https://liujing.neocities.org/newworld/datascience/Python/plotting/1.%20Basic%20Plotting%20with%20matplotlib.html), and here (https://www.google.com/amp/s/www.geeksforgeeks.org/matplotlib-axes-axes-get_children-in-python/amp/ )


Solution

  • Matplotlib supports 3 titles for each subplot. The default title is at the center, but additional a title at the left and/or at the right be set. (Internally, those two titles would be accessed by the private attributes _left_title and _right_title. The correct way to set these titles is ax.set_title(..., loc='left') or plt.title(..., loc=...))

    The last of the children is the background rectangle. It is usually accessed as ax.patch and can serve to change the background.

    The following code illustrates these concepts:

    import matplotlib.pyplot as plt
    
    plt.title('central title', size=14)
    plt.title('⟵ left title', loc='left')
    plt.title('right title ⟶', loc='right')
    plt.gca().patch.set_hatch('xx')
    plt.gca().patch.set_edgecolor('NavajoWhite')
    plt.gca().get_children()[-1].set_facecolor('LemonChiffon')
    for child in plt.gca().get_children():
        print(child)
    

    Output:

    Spine
    Spine
    Spine
    Spine
    XAxis(80.0,52.8)
    YAxis(80.0,52.8)
    Text(0.5, 1.0, 'central title')
    Text(0.0, 1.0, '⟵ left title')
    Text(1.0, 1.0, 'right title ⟶')
    Rectangle(xy=(0, 0), width=1, height=1, angle=0)
    

    left and right title