假设我有以下代码( 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
并在单独的图形中“全屏”绘制它而无需重新创建绘图?
最佳答案
我在官方文档中找不到任何内容来支持我所说的,但我的理解是不可能将现有轴“克隆”到新图形上。事实上,在一个轴中定义的任何艺术家(线条、文本、图例)都不能添加到另一轴中。 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
我能提出的最佳建议是从要复制的轴中提取数据,然后手动将其绘制到大小适合您喜欢的新轴对象中。下面的内容证明了这一点。请注意,这适用于通过 ax.plot 绘制的 Line2D 对象。如果数据是使用 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)
希望有帮助。
关于python - 在 matplotlib 中的单独图中绘制子图轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44780452/