【问题标题】:Use savefig in Python with string and iterative index in the name在名称中使用字符串和迭代索引的 Python 中的 savefig
【发布时间】:2012-11-20 21:10:11
【问题描述】:

我需要在 Python 中使用“savefig”来保存 while 循环的每次迭代的绘图,并且我希望我给该图的名称包含文字部分和数字部分。这个来自一个数组,或者是与迭代索引相关的数字。我举个简单的例子:

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

非常感谢。

【问题讨论】:

    标签: python image indexing save figure


    【解决方案1】:

    嗯,应该是这样的:

    savefig(str(a[0]))
    

    这是一个玩具示例。对我有用。

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

    【讨论】:

    • 您的意思是savefig('%s.png' % (str(a[0]))) 吗?
    • 好吧,savefig(str(a[0])) 不会产生任何东西。使用 savefig('%s.png' % (str(a[0]))) 是正确的,但在这种情况下,图像的名称将是“0.12.png”、“0.24.png”等。我希望名称是“x=0.12.png”“x= 0.24.png”等再次感谢您的帮助
    【解决方案2】:

    我最近有同样的需求并想出了解决方案。我修改了给定的代码并更正了几个显式错误。

    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)
    

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

      由于python 3.6,您可以使用f-strings 动态格式化字符串:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        • 2022-06-22
        • 1970-01-01
        • 1970-01-01
        • 2010-10-07
        • 1970-01-01
        相关资源
        最近更新 更多