python - 在 matplotlib 中的单独图中绘制子图轴

标签 python matplotlib

假设我有以下代码( 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()

结果

enter image description here

如何“提取”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/

相关文章:

python - 如何将 Pandas 绘图注释更改为整数?

python - 在 seaborn 中使用 Unicode 文本

javascript - 如何在 Bokeh/Python/Pywidgets 中使一个 slider /小部件更新多个绘图?

python - 子类化 Python 列表以验证新项目

Python 导入 matplotlib.pyplot 不起作用

python - Networkx:可视化 MultiGraph 时重叠边

python - 极坐标图 thetagrid 标签

python - 广播——将一个 (NxN) 数组乘以一个 (M) 数组得到一个 (NxNxM) 数组

python - 更改矩形的 X 值实际上并不会在 GUI 中移动它

python - 如何对 Pandas Series 中的每个元素运行条件并分成两行