Python pcolormesh,每个bin具有单独的alpha值 [英] Python pcolormesh with separate alpha value for each bin
问题描述
让我们说我有以下数据集:
Lets say I have the following dataset:
import numpy as np
import matplotlib.pyplot as plt
x_bins = np.arange(10)
y_bins = np.arange(10)
z = np.random.random((9,9))
我可以轻松地用
plt.pcolormesh(x_bins, y_bins, z, cmap = 'viridis)
但是,假设我现在为每个点添加一些alpha值:
However, let's say I now add some alpha value for each point:
a = np.random.random((9,9))
如何更改pcolormesh图中每个框的alpha值以匹配数组"a"中的相应值?
How can I change the alpha value of each box in the pcolormesh plot to match the corresponding value in array "a"?
推荐答案
由 pcolormesh
创建的网格只能为整个网格使用一个Alpha.要为每个单元格设置一个单独的Alpha,需要将这些单元格一一创建为矩形.
The mesh created by pcolormesh
can only have one alpha for the complete mesh. To set an individual alpha for each cell, the cells need to be created one by one as rectangles.
下面的代码显示 pcolormesh
,左边不带alpha,右边是带alpha的矩形网格.请注意,在矩形接触的点上,半透明会导致一些不相等的重叠.可以通过不绘制单元格边缘( edgecolor ='none'
)或通过较长的黑线分隔单元格来缓解这种情况.
The code below shows the pcolormesh
without alpha at the left, and the mesh of rectangles with alpha at the right. Note that on the spots where the rectangles touch, the semi-transparency causes some unequal overlap. This can be mitigated by not drawing the cell edge (edgecolor='none'
), or by longer black lines to separate the cells.
下面的代码更改了x尺寸,因此更容易验证没有将 x
和 y
混淆.需要 relim
和 autoscale
,因为使用matplotlib的默认行为,不会通过添加补丁来更改x和y限制.
The code below changes the x dimension so easier verify that x
and y
aren't mixed up. relim
and autoscale
are needed because with matplotlib's default behavior the x and y limits aren't changed by adding patches.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Patch
x_bins = np.arange(12)
y_bins = np.arange(10)
z = np.random.random((9, 11))
a = np.random.random((9, 11))
cmap = plt.get_cmap('inferno')
norm = plt.Normalize(z.min(), z.max())
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.pcolormesh(x_bins, y_bins, z, cmap=cmap, norm=norm)
for i in range(len(x_bins) - 1):
for j in range(len(y_bins) - 1):
rect = Rectangle((x_bins[i], y_bins[j]), x_bins[i + 1] - x_bins[i], y_bins[j + 1] - y_bins[j],
facecolor=cmap(norm(z[j, i])), alpha=a[j, i], edgecolor='none')
ax2.add_patch(rect)
# ax2.vlines(x_bins, y_bins.min(), y_bins.max(), edgecolor='black')
# ax2.hlines(y_bins, x_bins.min(), x_bins.max(), edgecolor='black')
ax2.relim()
ax2.autoscale(enable=True, tight=True)
plt.show()
这篇关于Python pcolormesh,每个bin具有单独的alpha值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!