【问题标题】:Plotting multiple columns groupedby on a single graph在单个图表上绘制多列分组
【发布时间】:2020-04-08 19:12:08
【问题描述】:

对于上面的 Pandas DataFrame pd,我想按照以下条件进行绘图:

  • 单线图
  • 对于每个算法,x 轴 = num_ingress 和 y 轴 = ['total_flows', 'successful flows', 'dropped_flows']。因此,对于每个算法,图上必须有 3 行
  • y 轴的标签必须是算法名称 + 列,例如A - Total FlowsB - Total Flows

我已经尝试了matplotlibgroupby,但后来我得到了多个组,我只能为每个组绘制一个图。不是一个图上的所有线。我也尝试了seaborn,但也无法基于groupby 使其工作。

任何帮助将不胜感激。

【问题讨论】:

    标签: pandas matplotlib plot group-by seaborn


    【解决方案1】:

    创建您的数据框,确保使用sort_values 按算法和num_ingress 进行排序。

    import pandas as pd
    
    algorithm = ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B']
    num_ingress = [4, 2, 1, 3, 5, 4, 2, 1, 3, 5]
    total_flow = [8000, 4000, 2000, 6000, 10000, 8000, 4000, 2000, 6000, 10000]
    successful_flows = [5985, 3994, 1997, 5991, 1994, 5975, 3988, 1996, 5974, 5087]
    dropped_flows = [2000, 0, 0, 0, 7991, 2005, 0, 0, 9, 4889]
    
    df = pd.DataFrame({'algorithm': algorithm,
          'num_ingress': num_ingress,
          'total_flow': total_flow,
          'successful_flows': successful_flows,
          'dropped_flows': dropped_flows
         })
    
    df.sort_values(['algorithm', 'num_ingress'], inplace=True)
    df
    

    然后绘制

    import matplotlib.pyplot as plt
    import numpy as np
    
    for i, algorithm in enumerate(df.groupby('algorithm')):
        algorithm_df = pd.DataFrame(algorithm[1])
        plt.subplot(1, 2, i+1)
        plt.plot(algorithm_df['num_ingress'], algorithm_df[['total_flow', 'successful_flows', 'dropped_flows']])
        plt.title("Algorithm {}".format(algorithm_df['algorithm'].values[0]))
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-06
      • 2021-09-08
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      相关资源
      最近更新 更多