如何从熊猫数据框创建多折线图?

时间:2021-07-16 20:55:22

标签: python pandas matplotlib

我有一个包含 3 列的 csv 文件:

  1. 时间戳
  2. 测量响应时间
  3. 型号名称
Timestamp,ResponseTime,Model
16-07-2021 17:59:22,1.421802,trained_sm_95
16-07-2021 17:59:23,1.414357,trained_sm_95
16-07-2021 17:59:25,1.623063,trained_sm_95
16-07-2021 17:59:27,1.401964,trained_md_96
16-07-2021 17:59:28,1.4,trained_md_96
16-07-2021 17:59:29,1.396638,trained_md_96
16-07-2021 17:59:31,1.601539,trained_lg_95
16-07-2021 17:59:33,1.205376,trained_lg_95
16-07-2021 17:59:34,1.411902,trained_lg_95

我想在包含 3 条线的多折线图中可视化响应时间,每个模型一条线。 我的代码如下所示:

df = pd.read_csv(r'D:\temp\times.csv')
#pd.to_datetime(df['Timestamp'],errors='ignore') 
sm = df.ResponseTime[df["Model"] == 'trained_sm_95']
md = df.ResponseTime[df["Model"] == 'trained_md_96']
lg = df.ResponseTime[df["Model"] == 'trained_lg_95']

x = df.Timestamp
plt.rcParams["font.family"] = "Times New Roman"
plt.scatter(x, y)

plt.plot( 'x', 'sm', data=df)
plt.plot( 'x', 'md', data=df)
plt.plot( 'x', 'lg', data=df)

plt.legend()
plt.show() 

代码目前在这一行被破坏:

plt.plot('x', 'lg', data=df)

出现此错误:

<块引用>

ValueError: 格式字符串中的字符 l 无法识别

我看不出代码有什么问题。

如何加载和可视化上述数据?

2 个答案:

答案 0 :(得分:1)

好的,这里有多个错误……首先,要绘制数据,您必须将变量传递给函数参数,而您传递的字符串与变量名称相同……所以它应该看起来像这样。

plt.plot(x, sm)
plt.plot(x, md)
plt.plot(x, lg)

您的语法仅在 df would 包含“x”、“lg”、“md”或“sm”时才有效,这些可以通过例如访问。

df['x']

如果是这样,那么,并且只有这样,您才能使用您正在使用的语法。在这里查看更多详细信息Plot不要害怕阅读文档 :)

答案 1 :(得分:0)

Petr 的回答绝对是一种方法,但它只是完全摆脱了 data 参数。要使用您原来的 data 技术,请更改过滤 sm/md/lg 的方式。

例如,目前您的 sm 只是一个 ResponseTime 系列:

sm = df.ResponseTime[df['Model'] == 'trained_sm_95']

# 0    1.421802
# 1    1.414357
# 2    1.623063
# Name: ResponseTime, dtype: float64

如果您只过滤 df 而不指定 ResponseTime,您将保留所有列:

sm = df[df['Model'] == 'trained_sm_95']

#             Timestamp  ResponseTime          Model
# 0 2021-07-16 17:59:22      1.421802  trained_sm_95
# 1 2021-07-16 17:59:23      1.414357  trained_sm_95
# 2 2021-07-16 17:59:25      1.623063  trained_sm_95

这将允许您使用 plt.plot(data=...)DataFrame.plot() 绘制 'Timestamp''ResponseTime' 的关系图:

  • plt.plot(data=...)

    df['Timestamp'] = pd.to_datetime(df['Timestamp'], dayfirst=True)
    
    sm = df[df.Model.eq('trained_sm_95')]
    md = df[df.Model.eq('trained_md_96')]
    lg = df[df.Model.eq('trained_lg_95')]
    
    plt.plot('Timestamp', 'ResponseTime', data=sm, label='sm')
    plt.plot('Timestamp', 'ResponseTime', data=md, label='md')
    plt.plot('Timestamp', 'ResponseTime', data=lg, label='lg')
    plt.legend()
    
  • DataFrame.plot()

    或者,最简单的方法是直接在共享的 ax 上使用 DataFrame.plot()

    fig, ax = plt.subplots()
    sm.plot('Timestamp', 'ResponseTime', ax=ax, label='sm')
    md.plot('Timestamp', 'ResponseTime', ax=ax, label='md')
    lg.plot('Timestamp', 'ResponseTime', ax=ax, label='lg')
    

请注意,如果您使用 seaborn,则更容易,因为您甚至不需要创建 sm/md/lg。只需使用原始 df 并设置 hue='Model'

import seaborn as sns
sns.lineplot(x='Timestamp', y='ResponseTime', hue='Model', data=df)

sm/md/lg plots using data param

相关问题