在 matplotlib 中用垂直梯度填充多边形?

Fill polygon with vertical gradient in matplotlib?

我想使用 .set_facecolor() 方法填充垂直渐变(从白到红)的多边形。我使用 matplotlib.colors.LinearSegmentedColormap 定义了一个颜色图,但似乎不允许我将颜色图直接传递给颜色设置方法,如 .set_facecolor()。如果我只传递一种颜色,它会成功运行 - 我如何传递渐变以获得预期的行为,颜色范围从白色底部到红色顶部?

工作片段,固定颜色:

import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
from  matplotlib import colors, patches
import numpy as np

fig,ax = plt.subplots(1)

patches = []

verts = np.random.rand(3,2)
polygon = Polygon(verts,closed=True)
patches.append(polygon)

collection = PatchCollection(patches)

ax.add_collection(collection)

collection.set_color("blue")

ax.autoscale_view()
plt.show()

自定义渐变代码段无效:

cmap = colors.LinearSegmentedColormap.from_list('white_to_red', ['white', 'red'])

fig,ax = plt.subplots(1)

patches = []

verts = np.random.rand(3,2)
polygon = Polygon(verts,closed=True)
patches.append(polygon)

collection = PatchCollection(patches)

ax.add_collection(collection)

collection.set_facecolor(cmap)

ax.autoscale_view()
plt.show()

您可以使用:

  1. ax.imshow 创建具有渐变的图像,定位到绘图的特定区域。
  2. set_clip_path 方法屏蔽图像上的 polygon-region。

像这样:

import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
from  matplotlib import colors, patches
import matplotlib.cm as cm
import numpy as np

fig,ax = plt.subplots(1)

verts = np.random.rand(3, 2)
xmin, xmax = verts[:, 0].min(), verts[:, 0].max()
ymin, ymax = verts[:, 1].min(), verts[:, 1].max()

cmap = colors.LinearSegmentedColormap.from_list('white_to_red', ['white', 'red'])
grad = np.atleast_2d(np.linspace(0, 1, 256)).T
img = ax.imshow(np.flip(grad), extent=[xmin, xmax, ymin, ymax],interpolation='nearest', aspect='auto', cmap=cmap)
polygon = Polygon(verts, closed=True, facecolor='none', edgecolor='none')
ax.add_patch(polygon)
img.set_clip_path(polygon)

ax.autoscale_view()
plt.show()