如何从多TXT文件构建指定列表并使用Matplotlib绘制分组折线图
问题描述
我有A.txt和B.txt两个文本文件,都是3行3列格式(首行为表头A、B、C):
A.txt内容:
A B C 1994 4 6 1996 8 10 1998 10 14
B.txt内容:
A B C 1995 14 2 1997 18 5 1999 12 9
我需要从两个文件的对应列提取数据,构建如下列表:
list1 = [[1994, 1996, 1998], [1995,1997,1999]] list2 =[[4,8,10] , [14, 18, 12]]
之后用Matplotlib在同一画布绘制折线图对比,但我写的Python代码没得到预期结果,代码如下:
#To create a list of files inside directory I did this import os cwd = os.getcwd() # list to store files res = [] # Iterate directory for file in os.listdir(cwd): # check only text files if file.endswith('.txt'): res.append(file) #then to create a two list from each file i did this nxyear = [] nxdata = [] myyear = [] mydata = [] for fin in res: print(fin) GNSS = fin[0:4] # station name, e.g., UH01 ts_enu = [] ts_enu = pd.read_csv (fin, header=0, delim_whitespace=True) year = ts_enu.iloc[:,0] # year dis = ts_enu.iloc[:,1] # NS myyear = [] mydata = [] myyear.append(year) mydata.append(dis) nxyear.append(myyear) plt.plot(myyear,mydata) plt.show()
问题分析与修正代码
你的代码存在几个关键问题:
- 未导入
pandas和matplotlib.pyplot库,运行会直接报错 - 循环内每次重置
myyear和mydata,且直接将DataFrame的列对象加入列表,不符合目标的普通列表格式 nxyear.append(myyear)缩进错误,只会添加最后一个文件的数据- 绘图逻辑简单,没有实现多折线对比的效果
修正后的代码如下:
import os import pandas as pd import matplotlib.pyplot as plt cwd = os.getcwd() res = [] # 遍历目录获取所有txt文件 for file in os.listdir(cwd): if file.endswith('.txt'): res.append(file) list1 = [] # 存储所有文件的年份数据 list2 = [] # 存储所有文件的B列数据 for fin in res: # 读取文件,按任意空白字符分隔 ts_enu = pd.read_csv(fin, header=0, delim_whitespace=True) # 将年份列转为普通列表后加入list1 year_list = ts_enu.iloc[:, 0].tolist() list1.append(year_list) # 将B列数据转为普通列表后加入list2 data_list = ts_enu.iloc[:, 1].tolist() list2.append(data_list) # 在同一画布绘制对比折线图 plt.figure(figsize=(8, 5)) # 遍历数据绘制每条折线,添加对应文件名的标签 for idx in range(len(list1)): plt.plot(list1[idx], list2[idx], label=f'{res[idx]}') plt.xlabel('年份') plt.ylabel('B列数据') plt.title('两个文件数据对比折线图') plt.legend() plt.grid(True) plt.show() # 输出目标格式的列表 print(f'list1 = {list1}') print(f'list2 = {list2}')
修正说明
- 补充导入必要的库,确保代码可正常运行
- 使用
tolist()将DataFrame的列对象转为普通列表,完全匹配你需要的格式 - 将数据收集操作放在循环内,确保每个文件的年份和B列数据都被正确存入目标列表
- 绘图时遍历数据列表,为每条折线添加文件名标签,实现清晰的对比效果
- 添加坐标轴标签、标题、图例和网格,提升图表的可读性
内容的提问来源于stack exchange,提问作者mark22
相关产品推荐
相关产品推荐

