Python Forum
Python Matplotlib: How do I save (in pdf) all the graphs I create in a loop?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Matplotlib: How do I save (in pdf) all the graphs I create in a loop?

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"

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):

    y1 = [ws.cell_value(i, col) for i in range(1,ws.nrows)]

    'fig' + str(j), 'ax' + str(j) = plt.subplots()
    'ax'+str(j).plot(x1, y1)

pp = PdfPages('C:/Users/Desktop/Sample1.pdf')
del pp
Here's a simple example:
import matplotlib.pyplot as plt
import numpy as np

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])

Possibly Related Threads…
Thread Author Replies Views Last Post
  Create Dynamic For Loop quest 3 891 Apr-26-2021, 02:03 PM
Last Post: ibreeden
  Matplotlib: How do I convert Dates from Excel to use in Matplotlib JaneTan 1 1,017 Mar-11-2021, 10:52 AM
Last Post: buran
  Python Matplotlib: Create chart for every 4 columns in Excel file JaneTan 2 1,137 Feb-28-2021, 05:02 AM
Last Post: JaneTan
  Color Formatting for Bar Graphs in a for loop adamszymanski 1 954 Jan-31-2021, 01:06 PM
Last Post: jefsummers
  cannot create animation on 2D array using Matplotlib and FuncAnimation Caffeine_Addict 1 860 Jan-12-2021, 11:35 AM
Last Post: Caffeine_Addict
  how to create pythonic codes including for loop and if statement? aupres 1 729 Jan-02-2021, 06:10 AM
Last Post: Gribouillis
  create loop of subplot plotly dash without hardcode tonycat 0 2,062 Sep-23-2020, 08:40 AM
Last Post: tonycat
  How to merge strings through graphs Den 6 1,540 Jun-29-2020, 07:07 AM
Last Post: Den
  Create tempfile that use in loop for insert into DB Firsttimepython 2 909 May-29-2020, 04:15 PM
Last Post: Firsttimepython
  Create, assign and print variables in loop steven_tr 10 2,054 May-28-2020, 04:26 PM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020