1

我有 CSV 文件,其中包含以下条目

id, A, B    #first line.
1, 1 2 3 4 5 6 7 8(and many more), 0 9 8 7 6 5 4 3 2(and many more) #line 1
...
...
(many more lines like this)

这是绘制每条线的图形并将其保存到文件的脚本。例如,要绘制的对将是 {1,0};{2,9};{3,8};...

import numpy as np
import matplotlib.pyplot as plt
import csv

def plot( fileName, x, y):
    fileNameWithExt=fileName
    fileNameWithExt+='.png'
    print fileNameWithExt
    plt.plot( x, y )
    plt.xlabel( "X values" )
    plt.ylabel( "Y values" )
    plt.savefig(fileNameWithExt)

if __name__=="__main__":
    with open('test', 'r')  as csvfile:
        next(csvfile)
        spamreader = csv.reader(csvfile, delimiter=',')
        for row in spamreader:
            print (row[1].strip()).split(" ")
            x = map(int, (row[1].strip()).split(" "))
            y = map(int, (row[2].strip()).split(" "))
            plot(row[0], x, y)

示例文件(test)如下:

id, A, B
train1, 1 2 3 4 5 6 7 8, 2 9 8 7 6 5 4 3
train2, 8 5 6 9 3 2 0 1, 2 4 6 8 6 9 1 6

火车1.png 火车2.png

正如人们所看到的,第二个图也包含第一个图的值。即使我在绘图后删除了列表,我也不明白为什么会发生这种情况。我犯了什么错误。

任何帮助表示赞赏。

4

1 回答 1

2

您需要关闭或清除循环之间的情节:

例如。plt.close()

cla()清除一个轴,即当前图形中的当前活动轴。它使其他轴保持不变。

clf()清除整个当前图形及其所有轴,但使窗口保持打开状态,以便可以将其重新用于其他绘图。

close()关闭一个窗口,如果没有另外指定,它将是当前窗口。

于 2013-06-08T13:54:00.003 回答