Search code examples
pythonmatplotlibjupyter-notebookjupyteraxis

Weird margins when using curvilinear axis


This example comes from Matplotlib's documentation. I'm running it inside Jupyter Lab. Here I attach the output figure:

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import Axes, HostAxes, angle_helper
from mpl_toolkits.axisartist.grid_helper_curvelinear import \
    GridHelperCurveLinear


def curvelinear_test1(fig):
    """
    Grid for custom transform.
    """

    def tr(x, y): return x, y - x
    def inv_tr(x, y): return x, y + x

    grid_helper = GridHelperCurveLinear((tr, inv_tr))

    ax1 = fig.add_subplot(1, 2, 1, axes_class=Axes, grid_helper=grid_helper)
    # ax1 will have ticks and gridlines defined by the given transform (+
    # transData of the Axes).  Note that the transform of the Axes itself
    # (i.e., transData) is not affected by the given transform.
    xx, yy = tr(np.array([3, 6]), np.array([5, 10]))
    ax1.plot(xx, yy)

    ax1.set_aspect(1)
    ax1.set_xlim(0, 10)
    ax1.set_ylim(0, 10)

    ax1.axis["t"] = ax1.new_floating_axis(0, 3)
    ax1.axis["t2"] = ax1.new_floating_axis(1, 7)
    ax1.grid(True, zorder=0)

fig = plt.figure()
curvelinear_test1(fig)
plt.show()

enter image description here

Note the weird top/bottom margins. Left/Right margins seems ok. If I execute this code inside a standard python interpreter, the picture looks like this:

enter image description here

Here, maybe there is too much top/bottom margin, and definitely too much right margin.

I've tried plt.tight_layout() just before plt.show(), but it does nothing in this case. I've looked at the source code of Axes/HostAxes but I couln't find anything obvious that would help fix these margins.

What can I try?


Solution

  • Change:

    ax1 = fig.add_subplot(1, 2, 1, axes_class=Axes, grid_helper=grid_helper)
    

    to

    ax1 = fig.add_subplot(1, 1, 1, axes_class=Axes, grid_helper=grid_helper)
    

    i.e., the Matplotlib example expects you to be adding two axes (with 1 row and 2 columns) but you're only adding one. I'm not sure why in Jupyterlab it looks more like it's trying to add 2 rows and 1 column though!