1

「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. 疑問 1:ご覧のとおり、基本的にプロットをクリアしてから、毎回新しいプロットを保存しています。Y軸の範囲を一定に保ちたいので、「plt.axis([0,500,0,180])」でそれをやろうとしています。しかし、うまくいかないようで、毎回自動的に設定されます。
  2. 疑問 2:ポイントが連続した線で結合されているデフォルトのプロットを取得する代わりに、「*」などのプロットを取得したいと思います。どうすればいいですか?
4

1 に答える 1

2

  • Tim Pietzcker が指摘しているように、文字列番号の書式設定を使用して、末尾のファイル名コードを短くすることができます。

    filename='plot%03d.png'%i
    

    最大 3 つのゼロで埋められ%03dた整数に置き換えられます。iPython2.6+ では、見た目は劣るがより強力な新しい文字列書式設定構文を使用して同じことを行うことができます。

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

  • 星でプロットされたポイントを取得するには、オプションを使用できますmarker='*'。接続線を取り除くには、 を使用しますlinestyle='none'
  • plt.plotfile(...) は Figure をプロットします。への呼び出しplt.plot()は、最初の図の上に重ねられた 2 番目の図をプロットします。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
于 2009-12-17T21:16:11.767 に答える