在 matplotlib 中保存子情节

有可能在 matplotlib 图形中保存(到 png)一个单独的子情节吗

import pyplot.matplotlib as plt
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)
ax1.plot([1,2,3],[4,5,6])
ax2.plot([3,4,5],[7,8,9])

是否有可能将这两个子图中的每一个保存到不同的文件中,或者至少将它们分别复制到一个新图中以保存它们?

我正在 RHEL 5上使用 matplotlib 的1.0版本。

188975 次浏览

虽然@Eli 说得很对,通常没有太多必要这样做,但这是可能的。savefig采用一个 bbox_inches参数,该参数可用于有选择地将图形的一部分保存到图像中。

这里有一个简单的例子:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np


# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')


ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')


# Save the full figure...
fig.savefig('full_figure.png')


# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)


# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

完整数字: Full Example Figure


在里面区第二个次要地段: Inside second subplot


第二个子图周围的面积在 x 方向填充了10% ,在 y 方向填充了20% : Full second subplot

应用 full_extent()函数在3年后从 给你得到的@Joe 的回答中,您可以得到 OP 所寻找的确切结果。或者,您可以使用 Axes.get_tightbbox(),它提供了一个更紧密的边界框

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox


def full_extent(ax, pad=0.0):
"""Get the full extent of an axes, including axes labels, tick labels, and
titles."""
# For text objects, we need to draw the figure first, otherwise the extents
# are undefined.
ax.figure.canvas.draw()
items = ax.get_xticklabels() + ax.get_yticklabels()
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
items += [ax, ax.title]
bbox = Bbox.union([item.get_window_extent() for item in items])


return bbox.expanded(1.0 + pad, 1.0 + pad)


# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')


ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')


# Save the full figure...
fig.savefig('full_figure.png')


# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

我想发张照片,但我缺乏声誉点