Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

python - Use a variable to set alpha opacity in a colormap

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)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...