在matplotlib中的一个图上绘制来自多个数据帧的两列



我在一个文件夹里有一堆。txt文件。每个列都有不同的数据,每个列都有相同的列标题。我已经遍历了所有的文件,将它们转换成单独的数据帧,并将它们存储在一个字典中。我想把所有的时间列合并在一起,把不同的压力画在y轴上的同一张图上。那么x=合并时间,y是所有不同的压强。有人能帮我解决这个问题吗?提前谢谢你的任何帮助。

以下是其中一个txt文件的标题:

[15191 rows x 4 columns], 'Stg2_ASCII.txt':            TIME  Pressure  Rate  Prop_con
0      00:00:00       146  16.8       0.0
1      00:00:00       152  16.8       0.0
2      00:00:00       153  16.9       0.0
3      00:00:00       152  16.8       0.0
4      00:00:00       153   9.9       0.0

#所有数据帧存储在这里

combine = {}

for filename in os.listdir(dir):
if filename.endswith(".txt"):
data = pd.read_csv(filename, delim_whitespace=True, skiprows=range(0,2))
df = pd.DataFrame({
"TIME": data._get_column_array(1)
,"Pressure": data._get_column_array(2)
,"Rate": data._get_column_array(6)
,"Prop_con": data._get_column_array(8)
})

combine[filename] = df

您可以使用join方法,在这种情况下,它比merge方法使用起来稍微方便一些。由于您希望根据时间绘制数据,因此从一开始就将TIME设置为索引是有意义的。这使得join使用起来很方便,因为它在默认情况下合并索引上的数据框。为了保持编号的一致性,可以重命名第一个数据框的列。

import os
import pandas as pd  # v 1.2.3
combine = {}
for filename in os.listdir(dir):
if filename.endswith(".txt"):
data = pd.read_csv(filename, delim_whitespace=True, skiprows=range(0,2))
df = pd.DataFrame({
"Pressure": data._get_column_array(2),
"Rate": data._get_column_array(6),
"Prop_con": data._get_column_array(8)
},
index=data._get_column_array(1))
combine[filename] = df
# Select first dataframe and then merge others to it on the index, using
# outer merge in case the time ranges are not identical in all files
dfm = list(combine.values())[0]
for idx, df_other in enumerate(list(combine.values())[1:]):
dfm = dfm.join(df_other, how='outer', rsuffix=idx+2)
# Rename first columns for naming consistency
dfm.columns = [col+'1' if idx < df_other.columns.size else col
for idx, col in enumerate(dfm.columns)]
# Plot all pressures
dfm[dfm.columns[['Pressure' in col for col in dfm.columns]]].plot()

最新更新