假设我有以下代码(matplotlib gridspec tutorial的修改版本)
import matplotlib.pyplot as plt
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
for tl in ax.get_xticklabels() + ax.get_yticklabels():
tl.set_visible(False)
plt.figure(0)
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2, 0))
plt.subplot2grid((3,3), (2, 1)) # OOPS! Forgot to store axes object
plt.suptitle("subplot2grid")
make_ticklabels_invisible(plt.gcf())
plt.show()
导致
如何在一个单独的数字中提取'ax5
并将其绘制为'全屏',而不必重新创建情节?
答案 0 :(得分:2)
我无法在官方文档中找到任何内容来支持我所说的内容,但我的理解是,无法克隆"现有轴到新图上。实际上,在一个轴上定义的艺术家(线,文本,图例)可能不会添加到另一个轴。 This discussion on Github may explain it to some degree
例如,尝试将fig1
上定义的轴添加到不同图形fig2
上的轴上会产生错误:
import matplotlib.pyplot as plt
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
line, = ax1.plot([0,1])
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.add_line(line)
>>>RuntimeError: Can not put single artist in more than one figure`
尝试将ax1
中绘制的线添加到相同图上的第二个轴ax2
会引发错误:
fig1 = plt.figure()
ax1 = fig1.add_subplot(121)
line, = ax1.plot([0,1])
ax12 = fig1.add_subplot(122)
ax12.add_line(line)
>>>ValueError: Can not reset the axes. You are probably trying to re-use an artist in more than one Axes which is not supported
我可以提出的最佳建议是从您想要复制的轴中提取数据,然后手动将其绘制到根据您的喜好调整大小的新轴对象中。下面的内容证明了这一点。请注意,这适用于通过Line2D
绘制的ax.plot
个对象。如果数据是使用ax.scatter
绘制的,那么您需要更改一些内容并refer you here for instructions on how to extract data from a scatter。
import matplotlib.pyplot as plt
import numpy as np
def rd(n=5):
# Make random data
return np.sort(np.random.rand(n))
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
# Plot three lines on one axes
ax1.plot(rd(), rd(), rd(), rd(), rd(), rd())
xdata = []
ydata = []
# Iterate thru lines and extract x and y data
for line in ax1.get_lines():
xdata.append( line.get_xdata() )
ydata.append( line.get_ydata() )
# New figure and plot the extracted data
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
for X,Y in zip(xdata,ydata):
ax2.plot(X,Y)
希望它有所帮助。