changing facecolor "alpha" value gives unwanted edges (matplotlib pcolormesh)

Viewed 1252

I need to introduce a non-constant alpha value using pcolormesh (imshow is a priori not a possible substitue because I need to use log scale for the axes -- hence non-regular spacing along each coordinate).

Following this post, I tried to change a posteriori the alpha value of the faces. However, in the results, I can't get rid of edges that appear.

Here is a minimal example, where I plot a 2D gaussian bump (with very few points), with alpha increasing from the lower left to the upper right corner:

from matplotlib import pyplot as plt
import numpy as np

# start with coordinates, corresponding meshgrid to compute the "shading" value and 
# extended coordinate array for pcolormesh (center mesh)
xx = np.linspace(-4,4,7)
xmesh, ymesh = np.meshgrid(xx,xx)
xplot = np.pad(0.5*(xx[1:]+xx[:-1]),1,'reflect',reflect_type="odd") # center & extend
yy = np.exp(-xx[None,:]**2-xx[:,None]**2) # data to plot

# plot the data
fig = plt.figure()
hpc = plt.pcolormesh(xplot, xplot, yy, shading="flat", edgecolor=None)
plt.gca().set_aspect(1)

# change alpha of the faces: lower-left to upper-right  gradient
fig.canvas.draw()  # this generate face color array
colors = hpc.get_facecolor()
grad = ( (xmesh.ravel()+ymesh.ravel())/2. - xx.min() ) / ( xx.max()-xx.min() )
colors[:,3] = grad.ravel()  # change alpha
hpc.set_facecolor(colors)   # update face colors
fig.canvas.draw()           # make the modification appears

The result looks like this: 2D gaussian bump (with very few points), with alpha increasing from the lower left to the upper right corner: The result looks like this: 2D gaussian bump (with very few points), with alpha increasing from the lower left to the upper right corner

Is it possible to get rid of these edges ? My problem is that I don't even know where it comes from... I tried adding hpc.set_antialiased(True), hpc.set_rasterized(True), explicitely adding edges with hpc.set_facecolor(face), tuning the linewidth to very small values -- none of these worked.

Thanks a lot for your help

1 Answers

The problem is that the squares overlap a tiny bit, and they are somewhat transparent (you're setting their alpha values != 1) -- so at the overlaps, they're less transparent than they should be, and it looks like a line.

You can fix it by making the squares opaque, but with a colour as if they had the stated transparency, with a white background:

def alpha_to_white(color):
    white = np.array([1,1,1])
    alpha = color[-1]
    color = color[:-1]
    return alpha*color + (1 - alpha)*white

colors = np.array([alpha_to_white(color) for color in colors])

enter image description here

Related