【问题标题】: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 文件中提取数据列并将它们定义为 x 和 y 变量,然后使用 pylab 在 python 中绘制它们?
【发布时间】:2012-07-27 18:50:14
【问题描述】:

我有一个包含以下数据的 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 新手,请耐心等待!

【问题讨论】:

  • 我有,我错过了什么吗?

标签: python csv matplotlib plot


【解决方案1】:

假设您的 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 有很多选择,但您通常需要比它提供的更精细的控制。

【讨论】:

  • 我同意,我通常从 loadtxt 开始,如果我需要更多的灵活性,则向上移动到 genfromtxt,如果前两个没有成功,则移动到 csv。
【解决方案2】:

这会让你开始:

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]

注意事项:

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

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

【讨论】:

    【解决方案3】:

    我知道这篇文章已经过时了;但是,对于需要快速绘制 csv 数据的人来说,以下脚本将提供一个很好的解决方案。

    它展示了如何从 csv 文件中导入数据,以及如何使用 matplotlib 制作一个图,这将制作一个 png 并绘制它。

    使用没有标题的Lake Huron 的数据,你会得到一个漂亮的图。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-25
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多