Python 在 matplotlib 中保存子图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4325733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:16:43  来源:igfitidea点击:

Save a subplot in matplotlib

pythonmatplotlib

提问by Robert Franke

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

是否可以在 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])

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?

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

I am using version 1.0.0 of matplotlib on RHEL 5.

我在 RHEL 5 上使用 matplotlib 1.0.0 版。

Thanks,

谢谢,

Robert

罗伯特

采纳答案by Joe Kington

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

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

Here's a quick example:

这是一个快速示例:

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: Full Example Figure

完整图: 完整示例图



Area insidethe second subplot: Inside second subplot

第二个子图的区域: 在第二个子图内



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

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

回答by Matt Gibson

Applying the full_extent()function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox()which gives a little tighter bounding box

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)

I'd post a pic but I lack the reputation points

我会发布一张照片,但我缺乏声望点