在多个文件的图中循环“ savefig”和“ title”

时间:2018-12-20 20:15:36

标签: python loops for-loop matplotlib plot

我有几个文件.txt,我创建了一个循环以读取该文件,并在不同的图中绘制了每个文件,这很好,我的问题是循环的功能'savefig'和'title'该图,因为这些只是保存了最后一个文件。我的代码是这样的:

enter code here

frames = np.linspace(10,49,40)

filelist = []

for i in frames:
    filelist.append("xyz_%s.txt" %i)

plotlist = []

for i in frames:
    plotlist.append("proy_%s.png" %i)

timelist = []

for i in frames:
    timelist.append("TIME = %s [Myr]" %i)

plt.rcParams.update({'figure.max_open_warning': 0})

for fname in filelist:
    data = np.loadtxt(fname)
    x = data[:,0]
    y = data[:,1]
    z = data[:,2]

fig = plt.figure()

gs = gridspec.GridSpec(1, 3) 
gs.update(left=0.07, right=0.98, bottom=0.3, top=0.6, wspace=0.3)

ax0 = plt.subplot(gs[0])
line0, = ax0.plot(x,y,'r.')

ax1 = plt.subplot(gs[1], sharey = ax0)
line1, = ax1.plot(x,z,'b.')


ax2 = plt.subplot(gs[2], sharey = ax0)
line2, = ax2.plot(y,z,'g.')

plt.gca().yaxis.set_major_locator(MaxNLocator())

ax0.xaxis.set_major_locator(plt.MaxNLocator(3))
ax1.xaxis.set_major_locator(plt.MaxNLocator(3))
ax2.xaxis.set_major_locator(plt.MaxNLocator(3))

ax0.yaxis.set_major_locator(plt.MaxNLocator(3))
ax1.yaxis.set_major_locator(plt.MaxNLocator(3))
ax2.yaxis.set_major_locator(plt.MaxNLocator(3))

ax0.set_xlabel('x[pc]', size=10)
ax0.set_ylabel('y[pc]', size=10)
ax1.set_xlabel('x[pc]', size=10)
ax1.set_ylabel('z[pc]', size=10)
ax2.set_xlabel('y[pc]', size=10)
ax2.set_ylabel('z[pc]', size=10)

ax0.set_xlim(-15,15)
ax0.set_ylim(-15,15)
ax1.set_xlim(-15,15)
ax1.set_ylim(-15,15)
ax2.set_xlim(-15,15)
ax2.set_ylim(-15,15)

plt.subplots_adjust(hspace=0)

for ftime in timelist:
    ax0.set_title(r'$ftime$',fontsize=12,horizontalalignment='left',verticalalignment='bottom')

for fplot in plotlist:
    plt.savefig('fplot',facecolor=fig.get_facecolor(), transparent=True) 
    plt.cla()
    plt.clf()
    plt.close()

Ps:我在读取xyz_02.0txt之类的文件时遇到了问题,因为'linspace'不会以零开始,有什么建议吗?

2 个答案:

答案 0 :(得分:1)

要回答第一个问题,plt.savefig('fplot',facecolor=fig.get_facecolor(), transparent=True)始终会覆盖名为fplot的文件。您需要在for循环中进行更改。

要回答您的Ps问题,请使用zfill进行零填充。例如,

filelist.append("xyz_" + str(int(i)).zfill(2) + ".txt")

答案 1 :(得分:0)

如果您只是想通过“ xyz_49.txt”获取诸如“ xyz_10.txt”,“ xyz_11.txt”之类的文件名,则使用“ proy_10.png”进行类似的处理,等等。 ,则不一定需要一个Numpy数组。标准的Python列表即可解决问题。 Just set frames = range(10,50)。或者:

frames = range(10,50)
filelist = [ "xyz_%s.txt" % str(i) for i in frames ]
plotlist = [ "proy_%s.png" % str(i) for i in frames ]

如果您希望frames列表是字符串“ 01”,“ 02”,以此类推,直到“ 40”,则可以使用.zfill命令来填充一位数字数字加0:

frames = [ str(i).zfill(2) for i in range(1,41) ] # This is ["01", "02", ... "40"]
filelist = [ "xyz_%s.txt" % c for c in frames ] # We don't need str(c) here; c is already a string
plotlist = [ "proy_%s.png" % c for c in frames ]