1

我正在尝试制作一个自动构建和保存图形的主循环,但是我发现这是不可能的,我需要单独选择每个图形,打开/显示它,然后手动保存。有谁知道如何自动化这个过程。该程序读取一个 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()  
4

1 回答 1

5

问题 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
于 2012-05-25T19:53:21.053 回答