简体   繁体   English

如何使用matplotlib读取文本文件和绘图

[英]How to read a text file and plot using matplotlib

This is my first time using python and matplotlib and I'd like to plot data from a CSV file. 这是我第一次使用python和matplotlib,我想从CSV文件中绘制数据。

The CSV file is in the form of: CSV文件的格式为:

10/03/2018 00:00,454.95,594.86

with about 4000 rows. 大约有4000行 I'd like to plot the data from the second column vs the datetime for each row and the data from the third column vs the datetime for each row, both on the same plot. 我想在同一图上绘制第二列的数据与每一行的日期时间,第三列的数据与每一行的日期时间。

This is my code so far but it's not working: 到目前为止,这是我的代码,但无法正常工作:

import matplotlib.pyplot as plt
import csv
import datetime
import re
T = []
X = []
Y = []
with open('Book2.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:

        datetime_format = '%d/%m/%Y %H:%M'
        date_time_data = datetime.datetime.strptime(row[0],datetime_format)
        T.append(date_time_data)
        X.append(float(row[1]))
        Y.append(float(row[2]))

        plt.plot(T,X, label='second column data vs datetime')
        plt.plot(T,Y, label='third column data vs datetime')

        plt.xlabel('DateTime')
        plt.ylabel('Data')
        plt.title('Interesting Graph\nCheck it out')
        plt.legend()
        plt.show()

Any help or guidance would be great. 任何帮助或指导都会很棒。 Many thanks! 非常感谢! :) :)

You could use pandas to read the CSV file 您可以使用熊猫来读取CSV文件

import pandas as pd

data = pd.read_csv('file_name.txt', header = None)

From there you can use the pandas dataframe as your input for matplot. 从那里,您可以将pandas数据框用作matplot的输入。 A good tutorial can be found here 一个很好的教程可以在这里找到

I hope this help you: 希望对您有所帮助:

import csv
import numpy as np


a = []
with open('table.csv') as f:  # Let's say your data is at 'table.csv'
    f_csv = csv.reader(f)
    for row in f_csv:
        a.append(row)  # Get each line

b = np.array(a)  # Make it as a numpy array
c = b[:,[1,2]]  # Filter it by column

print(c)
import matplotlib.pyplot as plt
import csv

x = []
y = []

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

plt.plot(x,y, label='Loaded from file!')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

dont forget to change the name of the file in my exemple or put the correct path if you are opening the file from different location if your file have float value change x.append(int(row[0])) to x.append(float(row[0])) and same for y 如果您要从其他位置打开文件(如果文件具有浮点值),请将x.append(int(row [0]))更改为x.append( float(row [0]))和y相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM