I need help with creating a custom legend

i am trying to create that legend

i am trying this but it is not working

axis[0].legend(['x', '+'], ['median', 'mean'])

It’s not clear what you think that code will do. Please see the docs at matplotlib.axes.Axes.legend — Matplotlib 3.4.3 documentation. In particular you need to make an object and pass a handle from it to legend. There is an example of doing this without having visible child artists at https://matplotlib.org/stable/gallery/text_labels_and_annotations/custom_legends.html#sphx-glr-gallery-text-labels-and-annotations-custom-legends-py

how do u create ‘custom lines’ which are markers like ‘x’,’+’

It’s still not clear what you are trying to do. Onlymake a legend or add a legend to a plot with data in it?

only make a legend

i have a violin plot with which, i have put ‘+’ and ‘x’ on mean and medians

        axis[i].scatter(1, statistics.median(last_l), marker='x', color='black', zorder=1,s=40)
        axis[i].scatter(2, statistics.median(last_l_t), marker='x', color='black', zorder=1,s=40)
        axis[i].scatter(3, statistics.median(last_i), marker='x', color='black', zorder=1,s=40)
        axis[i].scatter(4, statistics.median(last_i_t), marker='x', color='black', zorder=1,s=40)
        axis[i].scatter(5, statistics.median(last_c), marker='x', color='black', zorder=1,s=40)
        axis[i].scatter(6, statistics.median(last_c_t), marker='x', color='black', zorder=1,s=40)

        axis[i].scatter(1, statistics.mean(last_l), marker='+', color='black', zorder=1,s=40)
        axis[i].scatter(2, statistics.mean(last_l_t), marker='+', color='black', zorder=1,s=40)
        axis[i].scatter(3, statistics.mean(last_i), marker='+', color='black', zorder=1,s=40)
        axis[i].scatter(4, statistics.mean(last_i_t), marker='+', color='black', zorder=1,s=40)
        axis[i].scatter(5, statistics.mean(last_c), marker='+', color='black', zorder=1,s=40)
        axis[i].scatter(6, statistics.mean(last_c_t), marker='+', color='black', zorder=1,s=40)

so just take one of those, sc = ax[i].scatter(1, statistics.mean(last_l), marker='+', color='black') and pass it to legend: ax[i].legend(sc, 'mean'), or even easier, just label one of the scatter calls:
ax[i].scatter(1, statistics.mean(last_l), marker='+', color='black', label='mean'), and call legend with no arguments ax[i].legend(). I wouldn’t go through the bother of making a “custom” legend.

1 Like