如何在图形之间移动(或复制)补丁matplotlib
?
我正在处理一组腌制的人物,并想将它们合并到一个情节中。
使用线图时这没有问题,因为我可以通过以下方式访问数据ax.get_lines
.
然而,在使用直方图时,ax.get_lines
回报<a list of 0 Line2D objects>
。据我所知,访问绘制数据的唯一方法是通过ax.patches
。
如果我尝试使用以下命令将补丁从一个图形设置为另一个图形ax.add_patch
, I get RuntimeError: Can not put single artist in more than one figure
.
Edit
我在用着matplotlib2.0.0
。
下面的例子说明了问题
import numpy as np
import matplotlib.pylab as plt
import copy
# Creating the two figures
x = np.random.rand(20)
fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()
nr = 0
for color, ax in zip(("red", "blue"), (ax1, ax2)):
x = np.random.rand(20) + nr
ax.hist(x, color=color)
nr += 0.5
# Copying from ax1 to ax2
for patch in ax1.patches:
patch_cpy = copy.copy(patch)
# del patch # Uncommenting seems this makes no difference
ax2.add_patch(patch_cpy)
# RuntimeError: Can not put single artist in more than one figure
I would like to copy the red patches to the figure with the blue patches.
Edit 2
尽管 @ImportanceOfBeingErnest 的答案适用于上述情况,但它不适用于我遇到的现实生活问题。
我最终制作了一个新轴,并手动创建了新补丁,如下所示:
import numpy as np
import matplotlib.pylab as plt
from matplotlib import patches
# Creating the two figures
x = np.random.rand(20)
fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()
nr = 0
for color, ax in zip(("red", "blue"), (ax1, ax2)):
x = np.random.rand(20) + nr
ax.hist(x, color=color)
nr += 0.5
# Create another axis
fig3, ax3 = plt.subplots()
# Copy the properties of the patches to the new axis
for p in ax1.patches:
ax3.add_patch(patches.Rectangle(p.get_xy(),\
p.get_width(),\
p.get_height(),\
color = "red"))
for p in ax2.patches:
ax3.add_patch(patches.Rectangle(p.get_xy(),\
p.get_width(),\
p.get_height(),\
color = "blue"))
ax3.autoscale()
plt.show()