【问题标题】:Plot subplot axes in separate figure in matplotlib [duplicate]在matplotlib中的单独图中绘制子图轴[重复]
【发布时间】:2017-06-27 12:35:10
【问题描述】:

假设我有以下代码(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 并将其“全屏”绘制在单独的图中不必重新创建绘图?

【问题讨论】:

  • 请发布您用于生成上面看到的绘图的代码。始终发布您的代码,这样其他人可以更轻松地帮助您。
  • 感谢您的提示。我重新提出了这个问题。干杯!

标签: python matplotlib


【解决方案1】:

我在官方文档中找不到任何东西来支持我所说的话,但我的理解是不可能将现有轴“克隆”到新图形上。事实上,在一个轴中定义的任何艺术家(线条、文本、图例)都不能添加到另一个轴。 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)

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 2013-08-12
    • 2022-08-16
    • 1970-01-01
    • 2015-04-04
    • 2014-06-09
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    相关资源
    最近更新 更多