pythonmatplotliblegend

How to put all legend entries on one line?


I can't seem to find a solution. I have a legend that's custom (using solution found here) and I'm trying to put multiple entries on one line rather than have each new entry under the previous one. How does one do?

red_patch = mpatches.Patch(color='red', label='The red data')
blue_patch = mpatches.Patch(color='blue', label='The blue data')
plt.legend(handles=[red_patch, blue_patch])

I'd like to have "(red marker) The red data, (blue marker) The blue data, etc..." all in one line on top. It'd be nice to have it start a new line too when there are more entries than can fit on the plot. So just like normal text I guess.


Solution

  • If you want to have n columns in the legend, you can use

    plt.legend(ncols=n)  # could be ncol or ncols depending on version