【问题标题】:Saving a plot from multiple subplots从多个子图中保存一个图
【发布时间】:2022-01-10 23:41:25
【问题描述】:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,foo-function)

现在我需要一种方法将 4 个绘图中的每一个保存到一个文件中,如下所示:

plt1=topleft_plot.saveNOTfigBUTplot('quadfunction.pdf')

怎么做?

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    在这里使用答案:https://stackoverflow.com/a/4328608/16299117

    我们可以执行以下操作以从整体图中保存 SINGLE 个子图:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig,ax=plt.subplots(2,2,figsize=(15,10))
    
    x=np.linspace(-3,3)
    
    ax[0,0].plot(x,x**2) # This is just to make an actual plot.
    
    # I am not using jupyter notebook, so I use this to show it instead of %inline
    plt.show()
    
    # Getting only the axes specified by ax[0,0]
    extent = ax[0,0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    
    # Saving it to a pdf file. 
    fig.savefig('ax2_figure.pdf', bbox_inches=extent.expanded(1.1, 1.2))
    

    编辑:我相信我可能误解了你想要什么。如果您想单独保存 EACH 图,例如 pdf 中的 4 个不同页面,您可以根据此答案执行以下操作:https://stackoverflow.com/a/29435953/16299117

    这会将图中的每个子图保存为单个 pdf 中的不同页面。

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.backends.backend_pdf import PdfPages
    
    fig,ax=plt.subplots(2,2,figsize=(15,10))
    
    x=np.linspace(-3,3)
    
    ax[0,0].plot(x,x**2) # This is just to make an actual plot.
    
    
    with PdfPages('foo.pdf') as pdf:
       for x in range(ax.shape[0]):
           for y in range(ax.shape[1]):
               extent = ax[x, y].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
               pdf.savefig(bbox_inches=extent.expanded(1.1, 1.2))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2021-12-08
      • 1970-01-01
      • 2012-12-24
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      相关资源
      最近更新 更多