创建函数以绘制到特定轴
您通常会将绘图放入一个函数中,该函数将要绘制的轴作为参数。然后你可以在任何你喜欢的地方重复使用这个函数。
import numpy as np
import matplotlib.pyplot as plt
def myplot1(data, ax=None, show=False):
if not ax:
_, ax = plt.subplots()
ax.plot(data[0], data[1])
if show:
plt.show()
def myplot2(data, ax=None, show=False):
if not ax:
_, ax = plt.subplots()
ax.hist(data, bins=20, density=True)
if show:
plt.show()
x = np.linspace(-3, 3, 100)
y = np.exp(-x**2/2)/np.sqrt(2*np.pi)
a = np.random.normal(size=10000)
# create figure 1
myplot1((x,y))
#create figure 2
myplot2(a)
# create figure with both
fig, ax = plt.subplots()
myplot1((x,y), ax=ax)
myplot2(a, ax=ax)
plt.show()
将艺术家转移到新形象
要回答这个问题,是的,您可以将艺术家从未腌制的人物中移出,但这涉及一些黑客行为,并且可能导致不完美的结果:
import matplotlib.pyplot as plt
import numpy as np
import pickle
x = np.linspace(-3, 3, 100)
y = np.exp(-x**2/2)/np.sqrt(2*np.pi)
a = np.random.normal(size=10000)
fig, ax = plt.subplots()
ax.plot(x, y)
pickle.dump(fig, open("figA.pickle","wb"))
#plt.show()
fig, ax = plt.subplots()
ax.hist(a, bins=20, density=True, ec="k")
pickle.dump(fig, open("figB.pickle","wb"))
#plt.show()
plt.close("all")
#### No unpickle the figures and create a new figure
# then add artists to this new figure
figA = pickle.load(open("figA.pickle","rb"))
figB = pickle.load(open("figB.pickle","rb"))
fig, ax = plt.subplots()
for figO in [figA,figB]:
lists = [figO.axes[0].lines, figO.axes[0].patches]
addfunc = [ax.add_line, ax.add_patch]
for lis, func in zip(lists,addfunc):
for artist in lis[:]:
artist.remove()
artist.axes=ax
artist.set_transform(ax.transData)
artist.figure=fig
func(artist)
ax.relim()
ax.autoscale_view()
plt.close(figA)
plt.close(figB)
plt.show()
在这里,我们循环遍历未腌制图形中的所有线条和补丁,将它们从旧图形中删除并将它们添加到新图形中。为此,我们需要设置轴、变换和图形以正确匹配新图形。
这当然会随着图中不同类型的艺术家而变得越来越复杂,并且需要even more complex methods if those artists have transforms other than the data transform associated with them。