5

I'm trying to save the graphs of all 11 sectors from sectorlist to 1 pdf sheet. So far the code below gives me a graph on a separate sheet (11 pdf pages).

The daily return functions is the data I'm plotting. There are 2 lines on each graph.

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 Answer 1

9

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. 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. Here is one example modified from yours, which gives you 1 pdf page with 11 subplots:

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)
Sign up to request clarification or add additional context in comments.

4 Comments

also my data has a 63 day lag (bc of rolling average),where the first 63 days are empty values (hence empty on the graph). do you know how to get rid of this?
@thomas.mac What do you mean by "get rid of"? NaN won't be plotted. If you worried about the xlim, one suggestion (though I'm not sure if it's the best) will be to use pandas.DataFrame.first_valid_index to find out the first NaN. Then change xlim accordingly.
my graph starts halfway, as in the left side is completely empty, only the right half is graphing
@thomas.mac That's from the auto setting of x-axis range. As I said, you can use pandas.DataFrame.first_valid_index first to find out the first non-NaN value. Then you can either change xlim accordingly or trim you DataFrame accordingly. For Series, you have pandas.Series.first_valid_index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.