本文介绍了在 matplotlib 中保存子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 matplotlib 图形中保存(到 png)单个子图?假设我有

Is it possible to save (to a png) an individual subplot in a matplotlib figure? Let's say I have

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])

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

Is it possible to save each of the two subplots to different files or at least copy them separately to a new figure to save them?

我在 RHEL 5 上使用 matplotlib 1.0.0 版.

I am using version 1.0.0 of matplotlib on RHEL 5.

推荐答案

虽然@Eli 是非常正确的,通常不需要这样做,但这是可能的.savefig 接受一个 bbox_inches 参数,该参数可用于选择性地仅将图形的一部分保存到图像中.

While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig takes a bbox_inches argument that can be used to selectively save only a portion of a figure to an image.

这是一个简单的例子:

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))

完整图:


The full figure:

区域 inside 第二个子图:

第二个子图周围的区域在 x 方向填充 10%,在 y 方向填充 20%:

Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:

这篇关于在 matplotlib 中保存子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:56