Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

White lines in matplotlib's pcolor

Tags:

In some pdf viewers such as Preview on OSX, plots made with matplotlib's pcolor have white lines (see image below). How can I get rid of them?

The source code is very simple (choose any data for x,y,z):

import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as pl pl.figure() pl.pcolormesh(x,y,z,cmap="Blues",linewidth=0)  pl.savefig("heatmap.pdf") 

enter image description here

like image 441
hanno Avatar asked Nov 23 '14 19:11

hanno


2 Answers

The comments have a good solution that utilizes imshow. When imshow is not appropriate for the input data (e.g. it is not uniformly spaced) this generally solves this problem,

pcol = pl.pcolormesh(x,y,z,cmap="Blues",linewidth=0,) pcol.set_edgecolor('face') 

If that approach does not reduce the lines sufficiently, you can also try this:

pl.pcolormesh(x,y,z,cmap="Blues",linewidth=0,rasterized=True) 

In addition to reducing the lines between squares this approach also tends to reduce file size a bit, which is sometimes useful. In this case you may want to tune the dpi setting when saving (e.g. pl.savefig("heatmap.pdf", dpi=300)) until you get something that is satisfactory.

like image 173
farenorth Avatar answered Sep 18 '22 12:09

farenorth


The accepted answer didn't work very well for me. I seemed to have gotten closer by using antialiased=True, in addition to linewidth=0. This was with matplotlib version 3.0.2. Note the middle plot corresponds to the best version.

fig, axes = plt.subplots(1,3, figsize=(15,5)) axes[0].pcolormesh(XX, YY, ZZ_r, zorder=-1, norm=norm, cmap='magma', alpha=0.5, antialiased=True) axes[1].pcolormesh(XX, YY, ZZ_r, zorder=-1, norm=norm, cmap='magma', alpha=0.5, antialiased=True, linewidth=0.0) axes[2].pcolormesh(XX, YY, ZZ_r, zorder=-1, norm=norm, cmap='magma', alpha=0.5, antialiased=False, linewidth=0.0) 

enter image description here

like image 43
eqzx Avatar answered Sep 20 '22 12:09

eqzx