Python Matplotlib: How do I save (in pdf) all the graphs I create in a loop? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Python Matplotlib: How do I save (in pdf) all the graphs I create in a loop? (/thread-32717.html) |
Python Matplotlib: How do I save (in pdf) all the graphs I create in a loop? - JaneTan - Feb-28-2021 Hi, Refer to the entire code appended at the end. Thanks 1) I meet with "Cannot assign to operator (pyflakes E)" when I try to assign a variable(j) to the name of another variable 'fig' + str(j), 'ax' + str(j) = plt.subplots()2) How can I create a loop to save all the plots I created in the loop to a single pdf file? Thank you import xlrd import openpyxl import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages file_location = "C:/Users/Desktop/Sample1.xlsx" j=0 wb = xlrd.open_workbook(file_location) ws = wb.sheet_by_index(0) x1 = [int(ws.cell_value(i, 0)) for i in range(1,ws.nrows)] x2 = [int(ws.cell_value(i, 0)) for i in range((ws.nrows-10),ws.nrows)] for col in range(1,ws.ncols,4): j+=j y1 = [ws.cell_value(i, col) for i in range(1,ws.nrows)] #plt.figure(0) 'fig' + str(j), 'ax' + str(j) = plt.subplots() 'ax'+str(j).plot(x1, y1) pp = PdfPages('C:/Users/Desktop/Sample1.pdf') pp.savefig(fig1) pp.savefig(fig2) pp.close() del pp RE: Python Matplotlib: How do I save (in pdf) all the graphs I create in a loop? - Larz60+ - Feb-28-2021 Here's a simple example: import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) data = np.random.randn(2, 100) fig, axs = plt.subplots(2, 2, figsize=(5, 5)) axs[0, 0].hist(data[0]) axs[1, 0].scatter(data[0], data[1]) axs[0, 1].plot(data[0], data[1]) axs[1, 1].hist2d(data[0], data[1]) plt.show() plt.savefig("mypdf.pdf") |