简体   繁体   English

使用matplotlib在单个pdf页面上保存多个图

[英]Saving multiple plots on a single pdf page using matplotlib

I'm trying to save the graphs of all 11 sectors from sectorlist to 1 pdf sheet. 我正在尝试将所有11个扇区的图形从扇区列表保存到1个pdf表中。 So far the code below gives me a graph on a separate sheet (11 pdf pages). 到目前为止,下面的代码在单独的纸上为我提供了一张图形(11 pdf页面)。

The daily return functions is the data I'm plotting. 每日返回函数是我正在绘制的数据。 There are 2 lines on each graph. 每个图上有2条线。

with PdfPages('test.pdf') as pdf:
n=0
for i in sectorlist:
    fig = plt.figure(figsize=(12,12))
    n+=1
    fig.add_subplot(4,3,n)
    (daily_return[i]*100).plot(linewidth=3)
    (daily_return['^OEX']*100).plot()
    ax = plt.gca()
    ax.set_ylim(0, 100)
    plt.legend()
    plt.ylabel('Excess movement (%)')
    plt.xticks(rotation='45')
    pdf.savefig(fig)
plt.show()

Not sure if your indentation is wrong just in your question, but the key is you need to finish plotting all subplots before save your fig as pdf. 不确定只是在您的问题中您的缩进是否错误,但是关键是您需要先完成所有子图的绘制,然后再将无花果另存为pdf。 Specifically, you need to move fig = plt.figure(figsize=(12,12)) and pdf.savefig(fig) outside your for loop and keep them within your with statement. 具体来说,您需要将fig = plt.figure(figsize=(12,12))pdf.savefig(fig) for循环之外for并将其保留在with语句中。 Here is one example modified from yours, which gives you 1 pdf page with 11 subplots: 这是您修改后的一个示例,为您提供1个pdf页面,其中包含11个子图:

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np

with PdfPages('test.pdf') as pdf:
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2*np.pi*t)
    s = s * 50

    fig = plt.figure(figsize=(12,12))
    n=0
    for i in range(11):
        n += 1
        ax = fig.add_subplot(4,3,n)
        ax.plot(t, s, linewidth=3, label='a')
        ax.plot(t, s / 2, linewidth=3, label='b')
        ax.set_ylim(0, 100)
        ax.legend()
        ax.yaxis.set_label_text('Excess movement (%)')
        plt.setp(ax.xaxis.get_ticklabels(), rotation='45')
    pdf.savefig(fig)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM