为何无法在多个matplotlib.axes复用同一patch?正确实现方式是什么?
如何在Matplotlib的不同Axes上重复绘制相同Patch?
问题场景
尝试在两个并排的子图中绘制完全相同的正方形Patch时,直接复用同一个Polygon对象会触发错误,提示无法重复使用Artist。
触发错误的代码
import matplotlib.pyplot as plt import matplotlib.patches as patches fig = plt.figure() ax_1 = fig.add_subplot(1,2,1) ax_2 = fig.add_subplot(1,2,2) thing = patches.Polygon([[0,0],[0,1],[1,1],[1,0]], closed = True) # Add patches ax_1.add_patch(thing) ax_2.add_patch(thing) # 取消注释后触发错误 plt.show()
错误信息
ValueError: Can not reset the axes. You are probably trying to re-use an artist in more than one Axes which is not supported
原因说明
Matplotlib中的所有绘图元素(包括Patch)都属于Artist类,每个Artist对象只能绑定到一个Axes。当你把Artist添加到Axes时,它的axes属性会被设置为该Axes,重复添加到其他Axes会导致属性冲突,因此Matplotlib禁止这种操作。
正确实现方式
你后来尝试的重复创建独立Patch对象的方法是正确的,此外还有更简洁的复制方式:
方法1:创建独立的Patch实例
直接为每个Axes创建新的Patch对象,适用于参数简单的场景:
import matplotlib.pyplot as plt import matplotlib.patches as patches fig = plt.figure() ax_1 = fig.add_subplot(1,2,1) ax_2 = fig.add_subplot(1,2,2) # 为第一个Axes创建并添加Patch thing1 = patches.Polygon([[0,0],[0,1],[1,1],[1,0]], closed = True) ax_1.add_patch(thing1) # 为第二个Axes创建并添加相同参数的Patch thing2 = patches.Polygon([[0,0],[0,1],[1,1],[1,0]], closed = True) ax_2.add_patch(thing2) plt.show()
方法2:复制已有的Patch对象
使用copy模块的深拷贝功能,复用已有Patch的参数,避免重复编写代码:
import matplotlib.pyplot as plt import matplotlib.patches as patches import copy fig = plt.figure() ax_1 = fig.add_subplot(1,2,1) ax_2 = fig.add_subplot(1,2,2) # 创建原始Patch并添加到第一个Axes original_thing = patches.Polygon([[0,0],[0,1],[1,1],[1,0]], closed=True) ax_1.add_patch(original_thing) # 深拷贝原始Patch并添加到第二个Axes copied_thing = copy.deepcopy(original_thing) ax_2.add_patch(copied_thing) plt.show()
两种方法的核心都是为每个Axes提供独立的Artist实例,这样就不会触发重复绑定的错误。
内容的提问来源于stack exchange,提问作者Plop
相关产品推荐
相关产品推荐

