0
import numpy as np
import matplotlib.pyplot as plt

D = 12
n = np.arange(1,4)
x = np.linspace(-D/2,D/2, 3000)
I = np.array([125,300,75])
phase = np.genfromtxt('8phases.txt')

I_phase = I*phase

for count,i in enumerate(I_phase):
    F = sum(m*np.cos(2*np.pi*l*x/D) for m,l in zip(i,n))
    f = plt.figure()
    ax = plt.plot(x,F)
    plt.savefig(str(count)+'.png')
plt.show()

This script generates 8 plots and also saves them. I want to give all the plots different titles. Is it possible that it will read a .txt or Excel file (.xls) and take the title directly from there for each plot? For example; I have titles like these (can be saved either as .txt or .xls file):

phase_01_water
phase_02_membrane
phase_03_water
phase_04_empty
phase_05_water
phase_06_water
phase_07_full
phase_08_water

How can I do that? The '8phases.txt' has the following 8 lines:

-1     1    -1
-1     1     1
 1     1     1
 1    -1     1
-1    -1    -1
 1     1    -1
 1    -1    -1
-1    -1     1
4

1 回答 1

2

如果标题位于示例中的简单 txt 文件中,则可以使用类似这样的内容加载它们

with open('titles_file.txt') as f:
    titlelist = f.readlines()

然后matplotlib.Axes有个方法set_title。我还以更面向对象的方式重写了你的 for 循环

for count,i in enumerate(I_phase):
    F = sum(m*np.cos(2*np.pi*l*x/D) for m,l in zip(i,n))
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title(titlelist[count])
    ax.plot(x,F)
    fig.savefig(str(count)+'.png')
于 2013-05-15T12:04:01.733 回答