在matplotlib中保存子图 [英] Save a subplot in 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:
第二个子图的内部区域:
Area inside the second subplot:
第二个子图周围的区域在x方向上填充了10%,在y方向上填充了20%:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
这篇关于在matplotlib中保存子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!