1- from collections import defaultdict
1+ from collections import defaultdict , OrderedDict
22import os
33import subprocess
44import sys
@@ -70,15 +70,21 @@ def _create_legend(self, trend_mapping):
7070 box = self ._ax .get_position ()
7171 self ._ax .set_position ([box .x0 , box .y0 , box .width * 0.95 , box .height ])
7272
73- legend_dummy_lines , lines_list = [], []
74- for lines in trend_mapping .values ():
73+ # sort based on lines count in trends
74+ # to have the trends in nice order in the legend
75+ sorted_trend_items = sorted (
76+ trend_mapping .items (), key = lambda item : len (item [1 ]), reverse = True
77+ )
78+ sorted_mapping = OrderedDict (sorted_trend_items )
79+
80+ legend_dummy_lines = []
81+ for lines in sorted_mapping .values ():
7582 color = next (self ._ax ._get_lines .prop_cycler )["color" ]
7683 for line in lines :
7784 line .set_color (color )
7885
7986 legend_line = Line2D ([0 ], [0 ], color = color , lw = 4 )
8087 legend_dummy_lines .append (legend_line )
81- lines_list .append (lines )
8288
8389 self ._legend = self ._ax .legend (
8490 legend_dummy_lines ,
@@ -87,9 +93,12 @@ def _create_legend(self, trend_mapping):
8793 loc = "center left" ,
8894 bbox_to_anchor = (1 , 0.5 ),
8995 )
90- for idx , legend_line in enumerate (self ._legend .get_lines ()):
96+
97+ for legend_line , lines in zip (
98+ self ._legend .get_lines (), sorted_mapping .values ()
99+ ):
91100 legend_line .set_picker (5 )
92- self ._legend_mapping [legend_line ] = lines_list [ idx ]
101+ self ._legend_mapping [legend_line ] = lines
93102
94103 def _add_naming (self ):
95104 self ._fig .suptitle (self ._conf .general .plot_title )
0 commit comments