改变 facecolor “alpha"值给出不需要的边缘(matplotlib pcolormesh) [英] changing facecolor "alpha" value gives unwanted edges (matplotlib pcolormesh)

查看:30
本文介绍了改变 facecolor “alpha"值给出不需要的边缘(matplotlib pcolormesh)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用pcolormesh引入一个非恒定的alpha值(imshow是先验的,不可能替代,因为我需要对数轴使用对数比例尺-因此沿每个坐标的坐标间距不规则.)

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:

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

解决方案

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])

这篇关于改变 facecolor “alpha"值给出不需要的边缘(matplotlib pcolormesh)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆