簡體   English   中英

如何使用 Python 讀取多個 CSV 文件、存儲數據並在一個圖中繪制

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

我有幾個 .csv 文件,我想從這些文件中繪制一個圖表。 這些文件包含兩列,每個 csv 文件的第一列都是相同的。

文件1.csv:

20 -4.140462670
25 -4.140537060
30 -4.140571620
35 -4.140581580
40 -4.140584350

file2.csv:

20 -4.140468880
25 -4.140542900
30 -4.140577590
35 -4.140587560
40 -4.140590330

我嘗試使用下面的腳本,以繪制第一個:

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()

結果如下: 在此處輸入圖片說明

但我想繪制一個包含兩條曲線(file1.csv 和 file2.csv)的圖形

在其他時間,使用命令解決問題(使用xmgrace軟件):xmgrace -free -nxy * 在此處輸入圖片說明

我的問題是:在讀取多個文件后,我可以繪制包含多條曲線的圖形嗎? csv(file1.csv、file2.csv、file3.csv ....)。

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

這是我的代碼來解決您的問題,使其健壯,以便您可以更好地了解正在發生的事情。 您還可以分析許多其他文件,例如.txt 此外,在某些情況下,您可能會發現 CSV 文件以“;”分隔這是不正確的,因為這不是 CSV 文件應該是什么,但是,您也可以分析該文件。 只要確定每個值之間的分隔符是什么,您就可以在下面的第二行代碼中更改該字符。 例如,在您提供的數據中,分隔符是 ' '(每個值之間有一個空格)。 請參閱下面的代碼,以便您知道我的意思:

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 )

結果圖

在此處輸入圖片說明

如果您想知道這里的每個方法都做什么,您可以打印該方法(帶有所需的參數),以便您知道返回的內容,但我認為僅通過變量名稱就很清楚。 如果您有任何疑問,請不要猶豫,在下面發表評論。 我希望這對你有用。

解決您的問題的最簡單方法是在 for 循環內使用 Pandas read_csv 函數來讀取 .csv 文件,在循環內創建行並在循環外生成繪圖。

示例:

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()

輸出:

在此處輸入圖片說明

一般策略是讀取、存儲和繪制所有數據,僅在繪制plt.show()所有數據后調用plt.show() 作為一個簡單的例子,考慮

plt.plot(range(10))
plt.plot(range(0, 20, 2))

plt.show()

結果如下: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM