在单个图形上绘制分组的多列

时间:2019-12-16 10:23:47

标签: pandas matplotlib plot group-by seaborn

enter image description here

对于上述Pandas DataFrame pd,我想根据以下条件进行绘制:

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

我尝试了groupby的{​​{1}},但是随后得到了多个组,并且每组只能绘制一张图。并非所有线都在一个图上。我也尝试过matplotlib,但也无法使其基于seaborn起作用。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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()

enter image description here