繁体   English   中英

如何从CSV文件中提取数据列并将其定义为x和y变量,然后使用pylab在python中绘制它们?

[英]How can I extract columns of data from a CSV file and define them as x and y variables, then plot them in python using pylab?

我有一个CSV文件,其中包含以下数据

350, -0.042447984
349, -0.041671798
348, -0.04158416
347, -0.041811798
346, -0.041716855

虽然我有很多数据。 我想做的是将第一列(350、349等)定义为我的x值,第二列(-0.042447984,-0.041671798等)定义为我的y值。 到目前为止,这是我的代码:

import pylab
x=[350, 349, 348, 347, 346]
y=[-0.042447984, -0.041671798, -0.04158416, -0.041811798, -0.041716855]
pylab.plot(x, y)
pylab.show()

但是,不是尝试手动输入数字,而是尝试编写一个程序,该程序将从CSV文件中提取第1列作为x值,将第2列作为y值。 这可能比我尝试做的要简单得多。 我是python的新手,所以请多多包涵!

假设您的csv文件采用您所描述的格式,那么我可能会使用loadtxt

>>> d = numpy.loadtxt("plot1.csv", delimiter=",")
>>> d
array([[  3.50000000e+02,  -4.24479840e-02],
       [  3.49000000e+02,  -4.16717980e-02],
       [  3.48000000e+02,  -4.15841600e-02],
       [  3.47000000e+02,  -4.18117980e-02],
       [  3.46000000e+02,  -4.17168550e-02]])

并且有很多方法可以从中获得xy

>>> x,y = numpy.loadtxt("plot1.csv", delimiter=",", unpack=True)
>>> x
array([ 350.,  349.,  348.,  347.,  346.])
>>> y
array([-0.04244798, -0.0416718 , -0.04158416, -0.0418118 , -0.04171685])

x,y = dTd[:,0], d[:,1]等。

格式越复杂,直接使用csv模块的效果就越好。 尽管loadtxt有很多选项,但是通常您需要比它提供的更好的控制。

这将使您开始:

import csv

with open('data.txt') as inf:
    x = []
    y = []
    for line in csv.reader(inf):
        tx, ty = line
        x.append(int(tx))
        y.append(float(ty))

列表xy将分别包含:

[350, 349, 348, 347, 346]
[-0.042447984, -0.041671798, -0.04158416, -0.041811798, -0.041716855]

注意事项

使用with打开文件将在我们完成文件处理或遇到异常时将其关闭。 csv模块将逐行读取输入数据,并根据逗号分隔符将每行分成一个列表。 中的第一项被转换为int ,第二至float附加在各自的列表之前。

文件data.txt包含您的样本数据。

我知道这则帖子过时了。 但是,对于需要快速绘制csv数据的人来说,以下脚本将提供一个不错的解决方案。

它显示了如何从csv文件导入数据,以及如何使用matplotlib进行绘图,该绘图将生成png并进行绘图。

使用不带标题的休伦湖数据,您将获得一个不错的图。

import csv
import matplotlib.pyplot as plt
from numpy import arange

#####################################
# instatiation of variables

filehandle = "lake_huron.csv"
x_data = []                         # makes a list
y_data = []                         # makes a list
png_filename = 'LakeData.png'

#####################################
# opening csv file and reading

my_file = open(filehandle, "rb")    # opens file for reading
data = csv.reader(my_file)          # saves file to variable "data"

#####################################
# saves csv data to x_data and y_data

for row in data:
    x_data.append(eval(row[1]))     # selects data from the ith row
    y_data.append(eval(row[2]))     # selects data from the ith row

#####################################
# closes csv file
my_file.close()                     # closes file




#####################################
# makes plot (show) and saves png

fig = plt.figure()                  # calls a variable for the png info

# defines plot's information (more options can be seen on matplotlib website)
plt.title("Level of Lake Huron from 1875 to 1972")      # plot name
plt.xlabel('Year')                                      # x axis label
plt.ylabel('Lake Level (in feet)')                      # y axis label
plt.xticks(arange(1875,1973,10))                        # x axis tick marks
plt.axis([1875,1973,573,584])                           # x and y ranges

# defines png size
fig.set_size_inches(10.5,5.5)                           # png size in inches

# plots the data from the csv above
plt.plot(x_data,y_data)

#saves png with specific resolution and shows plot
fig.savefig(png_filename ,dpi=600, bbox_inches='tight')     # saves png
plt.show()                                                  # shows plot

plt.close()                                                 # closes pylab

暂无
暂无

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

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