【问题标题】:multi-line plotting in PythonPython中的多线绘图
【发布时间】:2020-11-17 16:33:46
【问题描述】:

所以我想绘制这样的多线图:

现在我正在尝试自己做,但是白人,黑人,亚洲人等种族群体在“种族”标题下的列中

这是我的数据从原始数据框过滤后的样子:

plt1_data = df1.loc[(df1.Region == "All") & (df1.Age == "All") & (df1.Sex == "All"),["Ethnicity","Value","Time"]]
                       Ethnicity Value  Time
12                           All   4.8  2004
192                        Asian   9.4  2004
372                  Asian Other   9.3  2004
552                        Black  12.8  2004
732                       Indian   6.9  2004
...                          ...   ...   ...
34212  Pakistani and Bangladeshi   8.4  2018
34392                    Unknown   4.1  2018
34572                      White   3.7  2018
34752              White British   3.8  2018
34932                White Other   3.4  2018

这是我用来获取类似于上述图表的代码:

plt.figure(figsize=(20,10))
plt.plot( 'Time', 'Ethnicity', data=plt1_data, color='red')
plt.plot( 'Time', 'Ethnicity', data=plt1_data, color='yellow')
plt.plot( 'Time', 'Ethnicity', data=plt1_data, color='magenta')
plt.plot( 'Time', 'Ethnicity', data=plt1_data, color='blue')
plt.legend()

但效果不好,给了我下图:

所以我需要帮助来修复我的图表。 非常感谢!

更新图:

更新图代码:

plt.figure(figsize=(30,30))
for cat, df_cat in plt1_data.groupby('Ethnicity'):
    plt.plot(df_cat['Time'],df_cat['Value'], label=cat)
plt.legend()

【问题讨论】:

    标签: python dataframe matplotlib plot multiline


    【解决方案1】:

    考虑使用seaborn

    import seaborn as sns
    
    sns.lineplot(data=plt1_data, x='Time', y='Value', hue='Ethnicity')
    

    【讨论】:

    • 我复制粘贴了你的代码,它给了我这个:DataError: No numeric types to aggregate
    【解决方案2】:

    您需要做一个“groupby”并遍历生成的种族和数据框

    plt.figure(figsize=(20,10))
    for cat, df_cat in plt1_data.groupby('Ethnicity'):
        plt.plot(df_cat['Time'],df_cat['Value'], label=cat)
    plt.legend()
    

    【讨论】:

    • 感谢这工作!但是图表看起来很乱。请参阅我上面附上的图表
    • 看起来您的数据类型不是数字而是对象。在这种情况下,您必须先转换它。
    猜你喜欢
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2020-10-04
    • 2016-08-14
    • 2019-10-17
    • 1970-01-01
    相关资源
    最近更新 更多