如何使用Python 2从20个CSV文件创建叠加图?

时间:2019-03-14 12:58:19

标签: python csv matplotlib plot overlay

我在python 2中进行的每个长计算都会生成20个CSV文件。从每个文件的所有数据集中,这里有2个重要的数据集。第一组为x轴上的row [0],第三组为y轴上的row [2]。第一组(row [0])始终相同,因此一个条目就足够了,但是第三组(row [2])由文件更改,需要根据(row [0])进行绘制从所有叠加的文件中绘制出所有第三组。

我不是程序员,但是我可以按照以下步骤分别绘制它们:

import matplotlib.pyplot as plt
import csv

x = []
y = []

with open('energy.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        x.append(row[0])
        y.append(row[2])

plt.plot(x,y, label='Energies')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Energy Graph\n per particle')
plt.legend()
plt.savefig('energy.png')
plt.savefig('energy.pdf')

plt.show()

但是要叠加所有数据集,我想尝试“在文件中使用file_name:”,将数据集作为变量附加到文件名中,并在一张图中将它们全部绘制在末尾:

for dirpath, dirnames, files in os.walk('.'):
    for file_name in files:
            if file_name.endswith('.csv'):
                    print(file_name)
                    with open(file_name,'r') as csvfile:
                            plots = csv.reader(csvfile, delimiter=',')
                            for row in plots:
                                    x.append(row[0])
                                    file_name.append(row[2])
            plt.plot(x,file_name, label='Loaded from file!')
            plt.xlabel('x')
            plt.ylabel('y')
            plt.title('Energy')
            plt.legend()
            plt.savefig('1.png')
            plt.savefig('1.pdf')

            plt.show()

然后我得到这个错误:

  

file_name.append(row [1])   AttributeError:“ str”对象没有属性“ append”

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

要创建叠加图,请反复调用plt.plot()


for dirpath, dirnames, files in os.walk('.'):
    for file_name in files:
        if file_name.endswith('.csv'):
            print(file_name)
            x = []
            y = []
            with open(file_name,'r') as csvfile:
                plots = csv.reader(csvfile, delimiter=',')
                for row in plots:
                    x.append(row[0])
                    y.append(row[2])
            plt.plot(x,y, label=file_name)

plt.xlabel('x')
plt.ylabel('y')
plt.title('Energy')
plt.legend()
plt.show()

示例:
a.csv

1,3,4,3,5
3,2,5,2,5

b.csv

1,3,2,3,5
3,2,6,2,5

然后您将获得此图:

plot example

但是,如果CSV文件包含数字数据,我建议使用NumPy,因为它速度很快。 :

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

for dirpath, dirnames, files in os.walk('.'):
    for file_name in files:
        if file_name.endswith('.csv'):
            print(file_name)
            data = np.loadtxt(file_name, delimiter=',').transpose()
            plt.plot(data[0], data[2], label=file_name)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Energy')
plt.legend()
plt.show()