I am plotting an image with matplotlib, by far the best interpolation parameter for imshow
in my case is interpolation='None'
but if I also give an alpha
parameter, when saving the figure, the alpha is not kept.
Minimal example:
import matplotlib.pyplot as plt
import numpy as np
arr = np.abs(np.sin(np.linspace(0, 2*np.pi)))
x,y = np.meshgrid(arr,arr)
arr = x*y
plt.figure()
plt.imshow(arr,alpha=arr,interpolation='None')
plt.savefig("fig1.pdf")
expected result:
what I get:
I only experience this issue for this particular interpolation setting.
matplotlib version: 3.4.3
CodePudding user response:
@mapf suggestion to rasterize is good, but you can just rasterize the image, and not the whole axes; that keeps the axes labels etc as vectors.
import matplotlib.pyplot as plt
import numpy as np
arr = np.abs(np.sin(np.linspace(0, 2*np.pi)))
x,y = np.meshgrid(arr, arr)
arr = x*y
fig, ax = plt.subplots()
ax.imshow(arr, alpha=arr, interpolation='none', rasterized=True)
fig.savefig("fig1.pdf")
If you really want the image to be vectorized, then save as pcolormesh:
fig, ax = plt.subplots()
ax.pcolormesh(arr, alpha=arr)
fig.savefig("fig2.pdf")
If you want imshow's vertical orientation and aspect ratio:
ax.flipud()
ax.set_aspect(1)
CodePudding user response:
Even though pdf supports transparency (unlike eps), if you use interpolation='None'
, you need to force a rasterized (bitmap) drawing, by using ax.set_rasterized(True)
:
import matplotlib.pyplot as plt
import numpy as np
arr = np.abs(np.sin(np.linspace(0, 2*np.pi)))
x,y = np.meshgrid(arr, arr)
arr = x*y
fig, ax = plt.subplots()
ax.imshow(arr, alpha=arr, interpolation='None')
ax.set_rasterized(True)
fig.savefig("fig1.pdf")
Note that by doing this, you are no longer saving a vector graphic (and unfortunately loose all the benefits that come with it). Instead, you essentially generate a png that is then incorporated into a pdf. Thus to avoid pixelation, you will probably need to up the dpi.
Nevertheless, the easiest solution would probably be to just drop interpolation='None'
, unless you really need it.
Since you said that interpolation='None'
works best for your project, but for every other backend except Agg, ps, pdf and svg the interpolation defaults to 'nearest'
, what likely actually works best for your project is interpolation='nearest'
. So I would recommend to try that instead.