【问题标题】:How to read multiple CSV files, store data and plot in one figure, using Python如何使用 Python 读取多个 CSV 文件、存储数据并在一张图中绘图
【发布时间】:2018-06-15 23:29:05
【问题描述】:

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

file1.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坐标

【问题讨论】:

  • 是的,您可以在一个图中多次绘制,请参阅:stackoverflow.com/questions/21254472/… 如果对您没有帮助,请告诉我。
  • 谢谢C。 Colin,是的,我知道我们将 plt.plot (x, y) 线相乘以在同一图中绘制不同的曲线。但问题在于读取 csv 文件,因为文件的数量并不总是相同。
  • 好的,那么您的问题是“如何读取多个 CSV 文件、存储数据并在一个图中绘图?”?另外,如果您有 n 个 CSV 文件,它们都会给您相同的 X 坐标(我已经知道 Y 坐标不同)?
  • 你是对的。
  • 是的,确实如此。 n CSV 数量;相同的 X 坐标;不同的Y坐标

标签: python csv matplotlib


【解决方案1】:

这是我的代码来解决你的问题,使它变得健壮,这样你就可以更好地理解正在发生的事情。您还可以分析许多其他文件,例如 .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 )

结果图

如果您想知道这里的每个方法是做什么的,您可以打印该方法(使用所需的参数),这样您就知道返回了什么,但我认为仅通过变量名称就很清楚了。如果您有任何疑问,请不要犹豫在下面发表评论。我希望这对你有用。

【讨论】:

  • C。 Colin,谢谢,谢谢,谢谢.....谢谢,谢谢......谢谢= (谢谢)^n(其中:n =天数) 我不相信自己的眼睛。它运作良好。感谢您的时间和精力。
【解决方案2】:

解决问题的最简单方法是在 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()

输出:

【讨论】:

  • 感谢亲爱的 Asamoah,我还不太明白,我会尝试像这样使用 glob:stackoverflow.com/questions/8017003/… 但暂时没有结果,我尝试
  • 这应该是投票最多的答案,简单且完全可参数化。
【解决方案3】:

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

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

plt.show()

结果如下:

【讨论】:

    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 2018-09-01
    • 2020-11-15
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    相关资源
    最近更新 更多