Exporting a pdf shape using savefig () randomly overshadows the background in matplotlib

I am trying to change the axis background in a graph where several calls to imshow() render images in different places using the extent parameter.

When I save a pdf of a drawing using savefig() , I lose the background color if the axis displays more than one image. Please note that this does not happen when exporting the same image png.

Here is a minimal script illustrating the problem:

 import matplotlib.pyplot as plt from numpy.random import rand fig, ax = plt.subplots(nrows=3, ncols=1, sharex=True) ax[0].imshow(rand(15,15), extent=[0, 2, 15, 0], \ cmap=plt.cm.gray, aspect='auto', interpolation='Nearest') ax[0].set_axis_bgcolor('k') ax[1].imshow(rand(15,15), extent=[0, 2, 15, 0], \ cmap=plt.cm.gray, aspect='auto', interpolation='Nearest') ax[1].imshow(rand(15,15), extent=[4, 6, 15, 0], \ cmap=plt.cm.gray, aspect='auto', interpolation='Nearest') ax[1].set_axis_bgcolor('k') ax[2].imshow(rand(15,15), extent=[0, 2, 15, 0], \ cmap=plt.cm.gray, aspect='auto', interpolation='Nearest') ax[2].imshow(rand(15,15), extent=[4, 6, 15, 0], \ cmap=plt.cm.gray, aspect='auto', interpolation='Nearest') ax[2].imshow(rand(15,15), extent=[8, 10, 15, 0], \ cmap=plt.cm.gray, aspect='auto', interpolation='Nearest') ax[2].set_axis_bgcolor('k') ax[-1].set_xlim([0, 12]) fig.savefig('test.pdf', format='PDF') fig.savefig('test.png', format='PNG') 

This is the pdf output for the script (eps output is the same):

test.pdf

And this is the expected output of the script (saved as png):

test.png

Am I encountering a matplotlib error or is there some kind of command that I am missing to fix the PDF output?

EDIT: I redrawn the shapes with the default matplotlibrc .

+4
source share
2 answers

This turned out to be a matplotlib error.

When rendering more than one image on the same axes, a composite image is created that does not have a transparent background when rendering in pdf, so the background color of the axes is not displayed.

This was resolved as part of the problem that I discovered in the matplotlib replica of GitHub .

+4
source

Take a look at matplotlibrc . There is a options section starting with savefig that defines how your saved drawing will look. Even the default matplotlibrc has this section.

There is also a similar question: matplotlib savefig () graphics other than show ()

+1
source

All Articles