如何使用Python读取多个CSV文件,存储数据并在一个图中绘图

How to read multiple CSV files, store data and plot in one figure, using Python

我有几个.csv文件,我想从此文件中绘制图形。
这些文件包含两列,每个csv文件的第一列均相同。

file1.csv:

1
2
3
4
5
20 -4.140462670
25 -4.140537060
30 -4.140571620
35 -4.140581580
40 -4.140584350

file2.csv:

1
2
3
4
5
20 -4.140468880
25 -4.140542900
30 -4.140577590
35 -4.140587560
40 -4.140590330

我尝试使用以下脚本,以绘制第一个脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

with open('file1.csv') as f:
    f=[x.strip() for x in f if x.strip()]
    data=[tuple(map(float,x.split())) for x in f[0:]]
    oX=[x[0] for x in data]
    oY=[x[1] for x in data]

plt.figure(figsize=(9,6))
ax = plt.subplot(111)

ax.yaxis.set_major_formatter(FormatStrFormatter('%.4f'))
ax.plot(oX, oY, color='blue', linestyle='dashdot', linewidth=2, marker='o', markerfacecolor='red', markeredgecolor='black',markeredgewidth=2, markersize=6)

plt.show()

结果如下:
enter image description here

但我想绘制一个包含两条曲线的图形(file1.csv和file2.csv)

在另一时间,使用以下命令(使用xmgrace软件)解决了问题:xmgrace -free -nxy *
enter image description here

我的问题是:读取多个文件后,我可以绘制包含多条曲线的图形吗? csv(file1.csv,file2.csv,file3.csv ....)。

我注意到我有:
1)n量的CSV(file1.csv,file2.csv,file3.csv ....)。
2)相同的X坐标
3)不同的Y坐标


这是我的代码,可以解决您的问题,使其功能强大,因此您可以更好地了解发生了什么。您还可以分析许多其他文件,例如.txt。另外,在某些情况下,您可能会发现CSV文件用';'分隔这是不正确的,因为那不是CSV文件的格式,但是您也可以分析该文件。只要确定每个值之间的分隔符是什么,您就可以在下面的第二行代码中更改该字符。例如,在给定的数据中,分隔符为''(每个值之间的空格)。请参阅下面的代码,以便您了解我的意思:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
numFiles = 2 #Number of CSV files in your directory
separator ="," #Character that separates each value inside file
fExtension =".csv" #Extension of the file storing the data

def MultiplePlots(xValues, allYValues):
    'Method to plot multiple times in one figure.'

    for yValues in allYValues:
        plt.plot(list(map(int, xValues)), list( map(float, yValues) ), label ="file" + str(i))

    plt.legend(loc = 'best')
    plt.show()
    return

def GetXandYValues(coordinates):
    'Method to get all coordinates from all CSV files.'
    xValues = []
    yValues = []
    allYValues = []
    fst = False
    for file in coordinates:
        for coordinate in file:
            if (fst == False):
                xValues.append(coordinate[0])
            yValues.append(coordinate[1])
        fst = True
        allYValues.append( yValues )
        yValues = []
    return xValues, allYValues

def GetCoordinates( n , separator , fExtension ):
    'Iterates through multiple CSV files and storing X values and Y values in different Lists'
    coordinates = [] #coordinates[0] = x values --- coordinates[1] = y values
    for i in range(n):
        coordinates.append( FillList( ReadFile("file" + str(i+1) + fExtension), separator ) )
    return coordinates

def ReadFile(path):
    'Function to read CSV file and store file data rows in list.'
    try:
        fileCSV = open(path,"r") #Opens file
        data = fileCSV.read() #Save file data in string
        listData = data.splitlines() #Split lines so you have List of all lines in file
        fileCSV.close() #Close file
    finally:
        return listData #Return list with file's rows

def FillList(myList, separator):
    'With this method you make a list containing every row from CSV file'
    valueTemp =""
    listTemp = []
    newList = []
    for line in myList:
        for c in line:
            if c != separator:
                valueTemp += c
            else:
                listTemp.append( valueTemp )
                valueTemp =""
        listTemp.append( valueTemp )
        newList.append(listTemp[:])
        valueTemp =""
        del listTemp[:]
    return newList

xValues = GetXandYValues( GetCoordinates( numFiles, separator , fExtension) )[0]
allYValues = GetXandYValues( GetCoordinates( numFiles, separator , fExtension) )[1]

MultiplePlots( xValues, allYValues )

结果图:

enter image description here

如果您想知道这里的每个方法都有什么,可以打印该方法(带有所需的参数),以便知道返回的内容,但是我认为仅通过变量名就可以清楚地知道。如果您有任何疑问,请随时在下面评论。我希望这对您有用。


解决问题的最简单方法是在for循环内使用Pandas read_csv函数读取.csv文件,在循环内创建线,在循环外创建线以生成图。

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import os
import pandas as pd
import matplotlib.pyplot as plt

### Set your path to the folder containing the .csv files
PATH = './' # Use your path

### Fetch all files in path
fileNames = os.listdir(PATH)

### Filter file name list for files ending with .csv
fileNames = [file for file in fileNames if '.csv' in file]

### Loop over all files
for file in fileNames:

    ### Read .csv file and append to list
    df = pd.read_csv(PATH + file, index_col = 0)

    ### Create line for every file
    plt.plot(df)

### Generate the plot
plt.show()

输出:

enter image description here


一般的策略是读取,存储和绘制所有数据,仅在绘制完所有内容后才调用plt.show()。作为一个简单的例子,考虑

1
2
3
4
plt.plot(range(10))
plt.plot(range(0, 20, 2))

plt.show()

结果如下:
enter image description here