Jenni
Jenni

Reputation: 21

Python Matplotlib: black squares when saving eps of plot of masked array, why?

When I run the following code:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

x_data = np.random.randn(10000)
y_data = np.random.randn(10000)
hist, xbins, ybins = np.histogram2d(x_data, y_data, bins=100)
hist_masked = np.ma.masked_where(hist<1e-3, hist)

cmap = matplotlib.cm.jet
#cmap.set_bad('w',1.)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.imshow(hist_masked.T, interpolation = 'none', cmap = cmap)
plt.savefig('test.eps',transparent=False)
plt.show()

the plot looks fine on screen but the eps file has extra black "squares". Why? These black squares are present only if I save the plot as eps and even with eps I can get rid of them by uncommenting the "set_bad" command in the code. Why is that command necessary for the plot to work if I am plotting a masked array?

Thanks!

Upvotes: 2

Views: 1641

Answers (1)

hitzg
hitzg

Reputation: 12701

The masked array hist_masked sets the bad values to np.nan and the colormaps in matplotlib have a predefined value for nans:

In [5]: plt.cm.jet._rgba_bad
Out[5]: (0.0, 0.0, 0.0, 0.0)

So it is set to black and fully transparent by default. However, when you set transparent=False upon saving, these points actually become visible (since the alpha is set to 1).

When you use:

cmap.set_bad('w',1.)

you set the bad color to white ('w'), and therefore you will not see them in the resulting eps file.

eps files can't handle transparency. However, you could consider saving to pdf and removing the flag transparency=False. This would also solve the issue.

Upvotes: 1

Related Questions