breeden
breeden

Reputation: 735

Pixelated fonts when plot is saved as jpeg

When I save a matplotlib figure as a jpeg the tick fonts are pixelated. I'm not sure what is going on or if there is any hack to fix this. Does anyone have any insight?

%matplotlib nbagg

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1.2,1.2,1000,endpoint=True)
y = np.copy(x)

x,y = np.meshgrid(x,y)
z   = -x**2 + y**2 - y**3

fig = plt.figure()

ax  = fig.add_subplot(111)

CS = plt.contour(x,y,z, [0,-0.1,0.1], colors=['black','blue', 'gray'])
plt.clabel(CS, fontsize=14, inline=1, fmt='%1.1f', manual=[(-0.15,0), (-0.4,0), (0.25,0.5)])

plt.savefig('plot.png', format='png')
plt.savefig('plot.jpg', format='jpg')
plt.savefig('plot.tiff', format='tiff')

Here is plot.png:

enter image description here

Here is plot.jpg:

enter image description here

Here is the plot.tiff:

enter image description here

I believe this is related to a previous question I had: Anti-aliased Fonts in Animations

Upvotes: 3

Views: 1234

Answers (1)

breeden
breeden

Reputation: 735

As noted above, this situation appears is dependent on the backend used. You can avoid the issue by using:

import matplotlib
matplotlib.use('webagg')

as opposed to:

%matplotlib nbagg

I believe the issue has to do with PIL trying to save a jpeg of a figure with transparency. If you insist on using nbagg, it appears that if you set:

matplotlib.rcParams['nbagg.transparent'] = False

Your jpeg image fonts won't be pixelated and will look nearly identical to the png and tiff files shown in the question. Unfortunately using the rcParams:

matplotlib.rcParams['savefig.transparent'] = False

is not sufficient. It appears that the 'savefig.transparent' rcParam will control the transparency of the plot inside the figure and the 'nbagg.transparent' will control the transparency outside of the figure (ie: axis, ticks, titles, etc..). There is probably an easy work by ensuring the backend forces transparency = False for when saving to file formats that don't support transparency.

Some of the other backends may not support transparency which is why it appears to fix the problem when you change backends.

I will report this to github as a bug.

Upvotes: 3

Related Questions