我正在尝试制作一个自动构建和保存图形的主循环,但是我发现这是不可能的,我需要单独选择每个图形,打开/显示它,然后手动保存。有谁知道如何自动化这个过程。该程序读取一个 csv 文件并从参数中指定的行生成图形。下面是代码,我看不出哪里出错了。
import matplotlib.pyplot as plt
import sys, csv, math
def main():
readAndChart('8to2Ant10Average', 0,1,2, '8to2Ant10: cumulative ethnic and political attacks')
readAndChart('8to2Ant10Average',0,8,9, '8to2Ant10: ethnic and political attacks per turn')
readAndChart('8to2Ant10Average',0,11,12, '8to2Ant10: ethnic and political attacks as a percentage of total attacks')
def roundUp(x,y):
roun = int(math.ceil(x/y))
k = int(roun*y)
return k
def readAndChart(readTitle, r1,r2,r3, graphTitle):
time = []
data1 = []
data2 = []
data3 = []
data4 = []
read = csv.reader(open(readTitle + '.csv', 'rb'))
legend1 = ''
legend2 = ''
for row in read:
if row[0] == 'turn':
legend1 = row[r2]
legend2 = row[r3]
if row[0] != 'turn':
a = row[r1]
b = row[r2]
c = row[r3]
a = float(a); b = float(b); c = float(c)
time.append(a)
data1.append(b)
data2.append(c)
axese = []
mt = max(time)
mph = max(data1)
mpd = max(data2)
axese.append(mph)
axese.append(mpd)
ax = max(axese)
print ax
if ax < 10 and ax > 1:
k = roundUp(ax, 10.0)
plt.axis([0,mt, 0, k])
if ax < 100 and ax > 10:
k = roundUp(ax, 10.0)
plt.axis([0,mt, 0, k])
if ax < 1000 and ax > 100:
k = roundUp(ax, 100.0)
plt.axis([0,mt, 0, k])
if ax < 10000 and ax > 1000:
k = roundUp(ax, 500.0)
plt.axis([0,mt, 0, k])
plt.xlabel('generation')
plt.ylabel('fequency')
plt.title(graphTitle)
plt.plot(time, data1, 'r' )
plt.plot(time, data2, 'b')
plt.legend((legend1, legend2),'upper center', shadow=True, fancybox=True)
plt.savefig(graphTitle + '.png')
if __name__=='__main__': main()