Skip to main content
 首页 » 编程设计

python之在 Python 中读取未定义数量的列并使用 matplotlib 绘制数据

2025年05月04日10itcoder

在 python 代码中,我执行以下操作:

x1=[] 
y1=[] 
y2=[] 
y3=[] 
y4=[] 
 
 
 
for line in res_file_1.readlines(): 
    ll=string.split(line) 
    x1.append(float(ll[0])) 
    y1.append(float(ll[1])) 
    y2.append(float(ll[2])) 
    y3.append(float(ll[3])) 
    y4.append(float(ll[4])) 

因此它读取文件的 4 列并将值存储在不同的“y”数组中。我想知道如何更通用地做到这一点,即当我不知道输入文件是否包含 4、16 或 2000 列时

更新:

后来我需要用matplotlib绘制数据,所以我通常这样做:

ax.plot(x1,y1,'ks',color='red') 
ax.plot(x1,y2,'ks',color='green') 
ax.plot(x1,y3,'ks',color='blue') 

如何绘制未定义列数(和颜色)的图?

请您参考如下方法:

如果您有这样的数据文件 input.csv:

x1, y1, y2, y3, y4 
A, 3, 6, 7, 1 
B, 4, 5, 9, 0 
X, 7, 2, 8, 5 
C, 4, 3, 2, 1 

与 pandas你会做这样的事情:

import pandas as pd 
import matplotlib.pyplot as plt 
 
df = pd.read_csv('input.csv', delimiter=',', index_col='x1') 
df.plot(marker='s') 
plt.show() 

你会得到这个图: