如何在其他2列数据的条件下生成一列数据的折线图



在我的df中有4列。前两个描述了测试条件。第3列&4是试验数据。第三列数据是固定的x轴数据。我想要一个线叠加图与图例为我的列4 INL数据,y轴数据,基于列1 &2.下面的代码显示了一个示例df。我可以组test_no和温度列从INL数据中获取我想要的组数据的值的最小/最大数据。我不能使用相同的组设置来绘制test_no=0,1 &温度= 25、50。我怎样才能做到这一点呢?由于

import pandas as pd
import matplotlib.pyplot as plt
data = {'Test_no': [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1], 'Temperature': [25, 25, 25, 25, 50, 50, 50, 50, 25, 25, 25, 25, 50, 50, 50, 50], 'Codes': [0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,], 'INL':[0,1.1,-0.9,0, 0,1.0,-0.8,0, 0,0.9,-0.7,0, 0,1.2,-0.6,0]}
df = pd.DataFrame(data)
groups = df.groupby(['Test_no','Temperature'])
#group data and get min,max,mean per Col1/2 group
result = groups.agg({'INL': ['min', 'max', 'mean']})
print(result)
#Plot data per Col1/2 group (start with C1:0,C2:25)
d = df.loc[df["Temperature"] == 25]
d = df.loc[df["Test_no"] == 0]
d['INL'].plot()

我对python比较陌生,但我能够使用groupby()函数将数据分成我需要的组,然后使用matplotlib来解决我的问题。Pyplot用于索引和绘制每组数据。我相信有更有效的解决方案,但这是有效的!使用与问题中相同的DF,我添加了以下代码:

Tests = [g for _, g in df.groupby(['Test_no','Temperature'])]
plt.plot(Tests[0].Codes, Tests[0].INL, label='T0 25C') 
plt.plot(Tests[1].Codes, Tests[1].INL, label='T0 50C') 
plt.plot(Tests[2].Codes, Tests[2].INL, label='T1 25C') 
plt.plot(Tests[3].Codes, Tests[3].INL, label='T1 50C')
plt.xlabel("Codes") 
plt.ylabel("INL") 
plt.title("INL Data")
plt.legend() 
plt.show()

或者您可以使用更紧凑的代码来绘制:

for (n, temp), Test in df.groupby(['Test_no','Temperature']):
plt.plot(Test.Codes, Test.INL, label=f"T{n} {temp}C")

最新更新