pythonmatplotlib

rasterized, dpi, bbox_inches='tight' and axins mess up the plot in a pdf


When I run the code below, the plot in the PDF is messed up. The content of the plot and the colorbar are shifted down to the left, as shown in the attached screenshot of the PDF.

import matplotlib.pyplot as plt
import numpy as np
import os
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

fig, ax = plt.subplots()

# create random image
image = np.arange(100).reshape((10,10))
xaxis = np.arange(10)
yaxis = np.arange(100)[::10]

im = ax.pcolormesh(xaxis, yaxis, image, shading='auto', rasterized=True)

axins = inset_axes(ax,
                    width=0.06,
                    height='100%',
                    loc='center right',
                    borderpad=-0.75
                    )
cbar = fig.colorbar(im, cax=axins, orientation='vertical')

filename = 'test.pdf'
fig.savefig(filename,
            dpi=300,
            bbox_inches='tight')

enter image description here

This problem does not occur if I do any of the following:

My matplotlib version is 3.9.2.

Any help is greatly appreciated!


Solution

  • This is a known bug that will be fixed in the upcoming Matplotlib v3.11 release. However, there are two different inset_axes functions within Matplotlib. The more modern axes method one does not have this problem.

    axins = ax.inset_axes([1.01, 0, 0.02, 1])
    

    With Matplotlib v3.10.5, this gives me: enter image description here