在matplotlib中保存一个子图

Rob*_*nke 45 python 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])
Run Code Online (Sandbox Code Playgroud)

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

我在RHEL 5上使用版本1.0.0的matplotlib.

谢谢,

罗伯特

Joe*_*ton 75

虽然@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))
Run Code Online (Sandbox Code Playgroud)

完整的数字: 完整示例图


区域的第二次要情节: 在第二个子图中


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

  • +1:哇!我希望在试图了解Matplotlib的更多信息时遇到过这些方法!如果官方文档将感兴趣的读者引导到Matplotlib的这些有用的角落,并且相关概念的呈现更加结构化,那将是很好的.:) (6认同)

小智 21

运用full_extent()由@Joe在3年后从应答功能在这里,你可以得到什么的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)
Run Code Online (Sandbox Code Playgroud)

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