使用变量在颜色图中设置 alpha 不透明度 [英] Use a variable to set alpha opacity in a colormap
问题描述
我想绘制 2 个输出变量,比如 map1 和 map2,作为 2 个输入变量的函数,比如 x 和y 使用颜色图.为此,我想使用颜色比例表示 map1 而 map2 将依赖于透明度比例.然而,alpha 选项不能将 np.array 作为参数,下面的代码注定会失败.
I would like to plot the 2 output variables, say map1 and map2, as a function of 2 input variables, say x and y using colormaps. So as to do so, I want to represent map1 using a color scale while map2 would rely on a transparency scale. Yet, the alpha option cannot take an np.array as an argument and the following code is doomed to failure.
fig=plt.figure(num=None, figsize=(21,12), dpi=80, facecolor='w', edgecolor='k')
ax1=plt.subplot(211)
im = ax1.pcolor(map1, cmap='Spectral_r', alpha=map2)
fig.colorbar(im)
有人会看到做到这一点的方法吗?我不想使用其他重叠的色标,并且确实希望用透明功能表示 map2 ,例如背景网格的可见性将告诉读者 map2的幅度.
Would anybody see a way to do this? I don't want to use another overlapped color scale and really want map2 to be represented with a transparency function so as the visibility of a background grid for instance would tell the reader the amplitude of map2.
推荐答案
您可以使用 pcolormesh
进行此操作,并为的面孔设置
之后.例如: alpha
QuadMesh
You could do this with pcolormesh
, and set the alpha
for the faces of the QuadMesh
afterwards. For example:
import numpy as np
import matplotlib.pyplot as plt
fig,ax = plt.subplots(1)
ax.set_aspect('equal')
# The data array
m1 = np.random.rand(5,5)
# The alpha array. Normalize your map2 to the range 0,1
m2 = np.linspace(0,1,25).reshape(5,5)
p = ax.pcolormesh(m1)
plt.savefig('myfig.png') # or fig.canvas.draw()
for i,j in zip(p.get_facecolors(),m2.flatten()):
i[3] = j # Set the alpha value of the RGBA tuple using m2
plt.savefig('myfig.png')
注意:您似乎必须在pcolormesh命令之后保存图形(或 plt.show()
或 fig.canvas.draw()
),以生成 p.get_facecolors
数组;这就是为什么我两次保存数字.可能有一个更优雅的解决方案,但我无法立即想到它.这是输出;注意 alpha
从左下角到右上角的增加:
Note: you seem to have to save the figure (or plt.show()
or fig.canvas.draw()
) after the pcolormesh command, to generate the p.get_facecolors
array; that's why I save the figure twice. There is probably a more elegant solution to that, but I can't think of it off the top of my head. Here's the output; notice the alpha
increase from the bottom left towards the top right:
这篇关于使用变量在颜色图中设置 alpha 不透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!