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?
#1
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
Reply
#2
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")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,684 Nov-07-2023, 09:49 AM
Last Post: buran
  how to save to multiple locations during save cubangt 1 543 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  How do you create a scatterplot of dataframe using matplotlib? asdad 2 856 Dec-07-2022, 04:53 PM
Last Post: Larz60+
  Plot several graphs on the same row Menthix 1 1,030 Mar-18-2022, 05:47 PM
Last Post: deanhystad
  How to save specific variable in for loop in to the database? ilknurg 1 1,143 Mar-09-2022, 10:32 PM
Last Post: cubangt
  grouped bar graphs tobiasfw 1 1,401 Feb-22-2022, 02:25 PM
Last Post: deanhystad
  Create Dynamic For Loop quest 3 4,379 Apr-26-2021, 02:03 PM
Last Post: ibreeden
  Matplotlib: How do I convert Dates from Excel to use in Matplotlib JaneTan 1 3,220 Mar-11-2021, 10:52 AM
Last Post: buran
  Python Matplotlib: Create chart for every 4 columns in Excel file JaneTan 2 2,761 Feb-28-2021, 05:02 AM
Last Post: JaneTan
  Color Formatting for Bar Graphs in a for loop adamszymanski 1 2,931 Jan-31-2021, 01:06 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

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