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

tho*_*mac 2 python matplotlib yahoo-finance pandas

我正在尝试将所有 11 个扇区的图形从扇区列表保存到 1 个 pdf 表。到目前为止,下面的代码在单独的工作表(11 个 pdf 页)上给了我一个图表。

每日回报函数是我正在绘制的数据。每个图形上有 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()
Run Code Online (Sandbox Code Playgroud)

Y. *_*Luo 7

不确定您的问题中的缩进是否错误,但关键是您需要在将无花果保存为 pdf 之前完成所有子图的绘制。具体来说,您需要移动fig = plt.figure(figsize=(12,12))pdf.savefig(fig)您的外for循环,并保持他们的内with声明。这是从您的示例中修改的一个示例,它为您提供 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)
Run Code Online (Sandbox Code Playgroud)