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

5

我正在尝试将来自sectorlist的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()
1个回答

9

不确定你的缩进是否有误,但关键在于你需要在将图形保存为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)

我的数据由于滚动平均值有63天的滞后期,因此前63天是空值(因此在图表上为空)。您知道如何消除这个问题吗? - thomas.mac
@thomas.mac 你的 "get rid of" 意味着什么? NaN 不会被绘制。如果你担心 xlim,一个建议(虽然我不确定是否是最好的)是使用 pandas.DataFrame.first_valid_index 找出第一个 NaN。然后相应地更改 xlim - Y. Luo
我的图表从一半开始,就像左侧完全为空,只有右半部分在绘制。 - thomas.mac
@thomas.mac 这是由于x轴范围的自动设置。正如我所说,您可以首先使用pandas.DataFrame.first_valid_index找到第一个非NaN值。然后,您可以相应地更改xlim或相应地修剪您的DataFrame。对于Series,您可以使用pandas.Series.first_valid_index - Y. Luo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接