Aliasing when saving matplotlib filled contour plot to .pdf or .eps

arne picture arne · Apr 4, 2013 · Viewed 7k times · Source

I'm generating a filed contour plot with the matplotlib.pyplot.contourf() function. The arguments in the call to the function are:

contourf(xvec,xvec,w,levels,cmap=matplotlib.cm.jet)

where

xvec = numpy.linspace(-3.,3.,50)
levels = numpy.linspace(-0.01,0.25,100)

and w is my data.

The resulting plot looks pretty good on screen, but when I save to pdf using a call to matplotlib.pyplot.savefig(), the resulting pdf has a lot of aliasing (I think that is what it is) going on. The call to savefig is simply savefig('filename.pdf'). I have tried using the dpi argument, but without luck. A call to matplotlib.get_backend() spits out 'TkAgg'.

I will attach a figure saved as pdf, compared to a figure saved as png (similar to what it looks like on screen) to demonstrate the problem:

png wihtout aliasing: https://dl.dropbox.com/u/6042643/wigner_g0.17.png

pdf with aliasing: https://dl.dropbox.com/u/6042643/wigner_g0.17.pdf

Please let me know if there are any other details I could give to help you give an answer. I should mention that saving as .eps gives similar bad results as saving to pdf. But the pdf shows the problem even clearer. My goal is to end up with a production quality .eps that I can attach to a latex document to be published as a scientific paper. I would be happy with some kind of work around where I save in one format, then convert it, if I can find a way that gives satisfying results.

Best,

Arne

Answer

divenex picture divenex · Oct 2, 2015

After using the useful answer by @pelson for a while, I finally found a proper solution to this long-standing problem (currently in Matplotlib 2.0), which does not require multiple calls to contour or rasterizing the figure.

I refer to my original answer here for a more extensive explanation and examples.

In summary, the solution consists of the following lines:

cnt = plt.contourf(x, y, z)

for c in cnt.collections:
    c.set_edgecolor("face")

plt.savefig('test.pdf')