Use savefig with string and iterative index in the name
Asked Answered
M

3

9

I need to use the "savefig" in Python to save the plot of each iteration of a while loop, and I want that the name i give to the figure contains a literal part and a numerical part. This one comes out from an array or is the number associated to the index of iteration. I make a simple example:

# index.py

from numpy import *
from pylab import *
from matplotlib import *
from matplotlib.pyplot import *
import os

x=arange(0.12,60,0.12).reshape(100,5)
y=sin(x)

i=0

while i<99
  figure()
  a=x[:,i]
  b=y[:,i]
  c=a[0]
  plot(x,y,label='%s%d'%('x=',c))

  savefig(#???#)      #I want the name is: x='a[0]'.png
                      #where 'a[0]' is the value of a[0]
Menard answered 3/12, 2012 at 11:48 Comment(0)
M
6

Well, it should be simply this:

savefig(str(a[0]))

This is a toy example. Works for me.

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
Muth answered 3/12, 2012 at 12:11 Comment(2)
Did you mean savefig('%s.png' % (str(a[0]))) ?Fasten
well, savefig(str(a[0])) doesn't produce anything. It is correct the use of savefig('%s.png' % (str(a[0]))) , but in this case the name of the images will be "0.12.png", "0.24.png", etc. I want the names are "x=0.12.png" "x=0.24.png", etc. thanks again for your helpMenard
D
4

Since python 3.6 you can use f-strings to format strings dynamically:

import matplotlib.pyplot as plt

for i in range(99):
    plt.figure()
    a = x[:, i]
    b = y[:, i]
    c = a[0]
    plt.plot(a, b, label=f'x={c}')

    plt.savefig(f'x={c}.png')
Desexualize answered 11/3, 2020 at 22:57 Comment(0)
V
3

I had the same demand recently and figured out the solution. I modify the given code and correct several explicit errors.

from pylab import *
import matplotlib.pyplot as plt

x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0

while i < 99:
    figure()
    a = x[i, :]                   # change each row instead of column
    b = y[i, :]                   

    i += 1                        # make sure to exit the while loop

    flag = 'x=%s' % str(a[0])     # use the first element of list a as the name
    plot(a, b, label=flag)
    plt.savefig("%s.png" % flag)

Hope it helps.

Vibrator answered 18/2, 2016 at 2:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.