【问题标题】:Couple of matplotlib newbie doubts几个matplotlib新手的疑惑
【发布时间】:2010-12-27 19:34:15
【问题描述】:

我刚刚开始使用“matplotlib”,并且遇到了 2 个主要障碍,我似乎无法从文档/示例等中解决:这是 Python 源代码:

#!/usr/bin/python
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
for i in range(0,301):

    print "Plotting",i

    # Reading a single column data file
    l=plt.plotfile("gen"+str(i))

    plt.xlabel('Population')
    plt.ylabel('Function Value')
    plt.title('Generation'+str(i))
    plt.axis([0,500,0,180])

    plt.plot()

    if len(str(i)) == 1:
        plt.savefig("../images/plot00"+str(i)+".png")
    if len(str(i)) == 2:
        plt.savefig("../images/plot0"+str(i)+".png")
    if len(str(i)) == 3:
        plt.savefig("../images/plot"+str(i)+".png")

    plt.clf()
  1. 疑点一: 如你所见,我基本上是在清除剧情,然后每次都保存新的剧情。我想保持 Y 轴的范围不变,我试图通过“plt.axis([0,500,0,180])”来做到这一点。但它似乎不起作用,并且每次都会自动设置。
  2. 疑问 2: 我宁愿获得一个“*”的图,而不是获得点由连续线连接的默认图。我该怎么做?

【问题讨论】:

  • 与您的问题无关,但您可以使用字符串格式消除您的 ifs:"../images/plot"+str(i).zfill(3)+".png" 甚至更好(Python 2.6 及更高版本)"../images/plot{0:03d}.png".format(i)

标签: python matplotlib scientific-computing


【解决方案1】:

  • 正如 Tim Pietzcker 指出的那样,您可以缩短最后的 if 文件名代码 使用字符串数字格式。
    filename='plot%03d.png'%i
    

    %03d 替换为整数i,最多填充3 个零。 在 Python2.6+ 中,可以使用不太漂亮但更强大的新字符串格式化语法来做同样的事情:

    filename='plot{0:03d}.png'.format(i)
    

  • 要使用星号绘制点,您可以使用选项marker='*'。 要摆脱连接线,请使用linestyle='none'
  • plt.plotfile(...) 绘制图形。对plt.plot() 的调用会在第一个图形的顶部绘制第二个图形。对 plt.plot() 的调用似乎修改了轴尺寸,消除了plt.axis(...) 的影响。幸运的是,解决方法很简单:不要打电话给plt.plot()。你不需要它。
#!/usr/bin/env python
import matplotlib
import matplotlib.pyplot as plt

matplotlib.use('Agg')   # This can also be set in ~/.matplotlib/matplotlibrc
for i in range(0,3):
    print 'Plotting',i
    # Reading a single column data file
    plt.plotfile('gen%s'%i,linestyle='none', marker='*')

    plt.xlabel('Population')
    plt.ylabel('Function Value')
    plt.title('Generation%s'%i)
    plt.axis([0,500,0,180])
    # This (old-style string formatting) also works, especial for Python versions <2.6:
    # filename='plot%03d.png'%i
    filename='plot{0:03d}.png'.format(i)
    print(filename)
    plt.savefig(filename)
    # plt.clf()  # clear current figure

【讨论】:

  • 酷!万分感谢。我担心我可能需要对 Figure 类等做一些事情。非常感谢!
猜你喜欢
  • 2012-10-12
  • 2014-08-17
  • 1970-01-01
  • 2020-11-02
  • 2012-09-09
  • 2017-02-16
  • 2013-09-06
  • 2013-08-12
  • 2018-11-30
相关资源
最近更新 更多