问题
Lets say I have the following code:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.arange(10)
z = np.sum(np.meshgrid(x,y), 0)
qm = plt.pcolormesh(x, y, z[:-1, :-1])
qm
is now a QuadMesh object. Now, I want to covert this QuadMesh to an RGBA array, in this case a 9x9x4 array giving the red, green, blue, and alpha values at each point.
The QuadmEsh object does have a to_rgba()
subroutine, but I am having trouble interpreting the documentation. to_rgba()
requires some x value, where x is described as "a 1-D or 2-D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable". But I'm not sure what any of that means...
回答1:
I am not convinced that there is no better way to address this before plotting pcolormesh but I assume this is what you intend to do:
from matplotlib import pyplot as plt
import numpy as np
fig, (ax1, ax2) = plt.subplots(1, 2)
x = np.arange(10)
y = np.arange(10)
z = np.sum(np.meshgrid(x,y), 0)
qm1 = ax1.pcolormesh(x, y, z[:-1, :-1], cmap="plasma")
ax1.axes.set_aspect("equal")
#retrieve rgba values of the quadmesh object
rgbas = qm1.to_rgba(qm1.get_array().reshape(z[:-1, :-1].shape))
#modify the alpha values
rgbas[:, :, 3] = np.linspace(0, 1, z[:-1, :-1].size).reshape(z[:-1, :-1].shape)
#plot back with imshow
qm2 = ax2.imshow(rgbas, origin="lower")
ax1.set_title("pcolormesh")
ax2.set_title("imshow after alpha modification")
plt.tight_layout()
plt.show()
Sample output:
来源:https://stackoverflow.com/questions/65634008/convert-quadmesh-generated-by-pcolormesh-to-an-rgba-array