matplotlib 使用垂直渐变填充多边形

2uluyalo  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(187)

我想用.set_facecolor()方法填充垂直渐变(白色到红色)的多边形。我使用matplotlib.colors.LinearSegmentedColormap定义了一个颜色Map图,但似乎不允许我直接将颜色Map图传递给.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()
t5zmwmid

t5zmwmid1#

您可以用途:

  1. ax.imshow以创建具有梯度的图像,该图像定位于绘图的特定区域。
  2. set_clip_path方法来掩蔽图像上的多边形区域。
    就像这样:
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()

相关问题