'How to fix this legend to place the label beside the markers

How would I fix this legend such that the labels (numeric values ) are placed beside the legend entry/marker

import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.lines import Line2D     

np.random.seed(0)
df0 = pd.DataFrame(np.random.randint(0,1000,size=(18, 4)), 
columns=list('ABCD'))
ax = df0.plot()

mrkr = ['o', '.', 'v', 'x']
mrkr_df = pd.DataFrame(mrkr)

idx_mx_vals = df0.abs().idxmax().to_list()

mx_vals = df0.to_numpy()[idx_mx_vals, 
np.arange(len(idx_mx_vals))].tolist()

legend_elements = []
for x, y, m, line, j in zip(idx_mx_vals, mx_vals, mrkr, ax.lines, mx_vals):
    line2 = ax.plot(x, y, marker=m, c=line.get_color(), markersize=7, label=j)
    legend_elements.append(Line2D([0], [0], c=line.get_color(), marker=m))
leg1 = ax.legend(loc='upper right')

Desired Output as shown in attached foto

enter image description here



Solution 1:[1]

You created a list of legend elements but never passed it to ax.legend.

leg1 = ax.legend(handles=legend_elements,
                 labels=list(map(str, mx_vals)),
                 loc='upper right')

Alternatively, you can pass the right label directly when you build the Line2D so that you don't have to pass it to ax.legend.

legend_elements = []
for x, y, m, line in zip(idx_mx_vals, mx_vals, mrkr, ax.lines):
    kwargs = dict(marker=m, c=line.get_color(), markersize=7, label=str(y)) # <--- Label is here.
    line2 = ax.plot(x, y, **kwargs)
    legend_elements.append(Line2D([], [], **kwargs)
leg1 = ax.legend(legend_elements, loc='upper right')

enter image description here

Edit: to answer your comment about keeping the column names in the legend, simply iterate over columns in your zip and adjust the label accordingly:

for x, y, m, line, column in zip(idx_mx_vals, mx_vals, mrkr, ax.lines, columns):
    kwargs = dict(marker=m, c=line.get_color(), markersize=7, label=f"{column} ({y})"
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1