def _sort_legend(self, ax: matplotlib.axes.Axes): """Sort legend of a given axis base on lines' zorder.""" handles, labels = ax.get_legend_handles_labels() zipped_list = list(zip(handles, labels)) # print("Before:", zipped_list) zipped_list.sort(key=lambda x: x[0].get_zorder()) # print("After: ", zipped_list) unzipped = [[i for i, j in zipped_list], [j for i, j in zipped_list]] return unzipped[0], unzipped[1]
def plot_delivered_vaccines_quantity(df_delivered: pd.DataFrame, ax: mp.axes.Axes) -> ResultValue: log = logging.getLogger('plot_delivered_vaccines_quantity') log.info(" >>") rv: ResultValue = ResultKo(Exception("Error")) try: line_label = "Dosi consegnate - somma" line_color = "#ff5733" df_delivered.sort_values(by="data_consegna", inplace=True) by_date = df_delivered.groupby(["data_consegna"]).sum() by_date.reset_index(level=0, inplace=True) by_date["cumulata"] = by_date["numero_dosi"].cumsum() x_del = by_date["data_consegna"] y_del = by_date["cumulata"] remove_tick_lines('x', ax) remove_tick_lines('y', ax) set_axes_common_properties(ax, no_grid=True) ax.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m/%y")) ax.xaxis.set_minor_formatter(mdates.DateFormatter("%d/%m")) ax.xaxis.set_major_locator(mdates.DayLocator(interval=2)) ax.scatter(x_del, y_del, s=30, marker='.') line = ax.plot(x_del, y_del, 'b-', linewidth=2, color=line_color, label=line_label) ax.set_xticklabels(x_del, rotation=80) handles, labels = ax.get_legend_handles_labels() patch = mpatches.Patch(color=line_color, label=line_label) handles.append(patch) plt.legend(handles=handles, loc='upper left') rv = ResultOk(line) except Exception as ex: log.error("Exception caught - {ex}".format(ex=ex)) rv = ResultKo(ex) log.info(" <<") return rv
def fix_pandas_multiplot_legend(ax: matplotlib.axes.Axes, legend_loc: Tuple[Union[int, float], Union[int, float]]): """ When plotting multiple pieces of data, the Pandas-generated plot legend will often look like "(metric, place)" (e.g., "(Deaths, Connecticut)". This function corrects the legend, by extracting just the place. Parameters: ax - the plot axis legend_loc - the desired location for the legend, as a tuple """ patches, labels = ax.get_legend_handles_labels() pat = re.compile(r'^\([^,\s]+,\s+(.*)\)$') labels2 = [] for label in labels: m = pat.match(label) assert m is not None labels2.append(m.group(1)) ax.legend(patches, labels2, loc=legend_loc)