使用match_original=True时PatchCollection无法保留hatch填充图案
Matplotlib PatchCollection 不保留 Hatch 填充图案的解决方法
当使用PatchCollection批量添加带hatch填充图案的Patch时,即使设置了match_original=True,填充图案也会消失,但单独用add_patch添加单个Patch时显示正常。
原因
match_original=True参数只会复制Patch的部分属性(如facecolor、edgecolor),hatch并不在默认复制的属性列表中,所以PatchCollection不会继承原Patch的hatch设置。
解决方法
方法1:所有Patch使用相同填充图案
如果所有Patch的hatch样式一致,直接在创建PatchCollection时显式指定hatch参数即可:
from matplotlib.collections import PatchCollection from matplotlib.patches import Wedge import matplotlib.pyplot as plt w = Wedge((0,0),1,0,360, facecolor="cyan", hatch="/") fig, ax = plt.subplots() # 显式设置hatch参数 collection = PatchCollection([w], match_original=True, hatch="/") ax.add_collection(collection) plt.show()
方法2:每个Patch使用不同填充图案
如果需要给每个Patch设置不同的hatch,需要手动遍历Patch列表,将每个Patch的hatch属性赋值给PatchCollection对应的元素:
from matplotlib.collections import PatchCollection from matplotlib.patches import Wedge, Rectangle import matplotlib.pyplot as plt # 创建多个带不同hatch的Patch patch1 = Wedge((0,0),1,0,180, facecolor="cyan", hatch="/") patch2 = Rectangle((-1,-1),2,1, facecolor="orange", hatch="\\") patch3 = Wedge((0,0),1,180,360, facecolor="green", hatch="x") patches = [patch1, patch2, patch3] fig, ax = plt.subplots() collection = PatchCollection(patches, match_original=True) # 手动传递每个Patch的hatch属性 for idx, patch in enumerate(patches): collection._paths[idx].hatch = patch.hatch ax.add_collection(collection) ax.set_xlim(-2,2) ax.set_ylim(-2,2) plt.show()
补充说明
如果你的matplotlib版本较旧,可能还存在其他属性不兼容的问题,建议升级到最新稳定版(3.5+),新版本对PatchCollection的属性继承支持更完善。
内容的提问来源于stack exchange,提问作者patha
相关产品推荐
相关产品推荐

