簡體   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