我正在尝试制作一个自动构建和保存图形的主循环,但我发现这是不可能的,我需要单独选择每个图形,打开/显示它然后手动保存。有谁知道如何自动化该过程。程序读取一个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()
答案 0 :(得分:4)
问题1 :
看来你在Windows上
Windows不允许您在文件名中放置冒号(:
)
参考上述支持声明:http://support.microsoft.com/kb/289627
即使您在* nix中,我也建议不要在文件名中使用冒号,因为某些软件可能无法正确处理它。
快速修复:
plt.savefig(graphTitle.replace(':','') + '.png')
问题2 :
如评论中所述,您还需要在保存后清除该图
示例:
plt.savefig(graphTitle.replace(':','') + '.png')
plt.clf()
plt.cla()
或者只是:
plt.savefig(graphTitle.replace(':','') + '.png')
plt.close() # call w/ no args to close current figure