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

如何从CSV文件中提取数据列并将它们定义为x和y变量,然后使用pylab在python中绘制它们?,python,csv,matplotlib,plot,Python,Csv,Matplotlib,Plot,我有一个CSV文件,其中包含如下数据 350, -0.042447984 349, -0.041671798 348, -0.04158416 347, -0.041811798 346, -0.041716855 虽然我有更多的数据。我要做的是将第一列(350349等)定义为我的x值,将第二列(-0.042447984,-0.041671798等)定义为我的y值。这是我目前的代码: import pylab x=[350, 349, 348, 347, 346] y=[-0.04244798

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

350, -0.042447984
349, -0.041671798
348, -0.04158416
347, -0.041811798
346, -0.041716855
虽然我有更多的数据。我要做的是将第一列(350349等)定义为我的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新手,所以请容忍我

这将让您开始:

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))
列表
x
y
将分别包含:

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

使用
打开文件将在处理完文件或遇到异常时负责关闭文件。模块将逐行读取输入数据,并根据逗号分隔符将每行拆分为一个列表。第一项转换为
int
,第二项转换为
float
,然后再添加到相应的列表中


文件
data.txt
包含示例数据。

这将让您开始:

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))
列表
x
y
将分别包含:

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

使用
打开文件将在处理完文件或遇到异常时负责关闭文件。模块将逐行读取输入数据,并根据逗号分隔符将每行拆分为一个列表。第一项转换为
int
,第二项转换为
float
,然后再添加到相应的列表中


文件
data.txt
包含示例数据。

假设您的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]])
有很多方法可以从中获得
x
y

>>> 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=d.T
d[:,0],d[:,1]


格式越复杂,最好直接使用
csv
模块。虽然
loadtxt
有很多选项,但通常您需要比它提供的更好的控制。

假设您的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]])
有很多方法可以从中获得
x
y

>>> 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=d.T
d[:,0],d[:,1]


格式越复杂,最好直接使用
csv
模块。虽然
loadtxt
有很多选择,但通常你需要比它提供的更好的控制;但是,对于需要快速绘制csv数据的用户,以下脚本将提供一个很好的解决方案

它显示了如何从csv文件导入数据,以及如何使用matplotlib进行绘图,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

我知道这篇文章相当过时;但是,对于需要快速绘制csv数据的用户,以下脚本将提供一个很好的解决方案

它显示了如何从csv文件导入数据,以及如何使用matplotlib进行绘图,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

我有,我是不是遗漏了什么?我有,我是不是遗漏了什么?我同意,我通常从loadtxt开始,如果我需要多一点灵活性,就升级到csv,如果前两个不成功,就升级到csv。我同意,我通常从loadtxt开始,如果我需要多一点灵活性,就升级到csv,如果前两个不成功。