Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: put legend symbols on the right of the labels

It's a simple thing but I've searched for quite a while without success: I want to customise a figure legend by reversing the horizontal order of the symbols and labels.

In Gnuplot, this is simply achieved by set key reverse. Example: change x data1 to data1 x. In matplotlib, there seems to be no user-friendly solution. Thus, I thought about changing a kind of handle anchor or just shifting the handle's position, but couldn't find any point to start with.

like image 427
Erwin411 Avatar asked Jul 21 '14 14:07

Erwin411


People also ask

How do I move my legend to the right in Matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

How do I move the legend outside in Matplotlib?

In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it. We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend.

How do I change the order of items in Matplotlib legend?

Change order of items in the legend The above order of elements in the legend region can be changed by the gca method that uses another sub-method called get_legend_handles_labels method. These handles and labels lists are passed as parameters to legend method with order of indexes.


1 Answers

The requested feature is already there, as the keyword markerfirst of the legend command.

    plt.plot([1,2],[3,4], label='labeltext')
    plt.legend(markerfirst=False)
    plt.show()

If you want to make it your default behaviour, you can change the value of legend.markerfirst in rcParams, see customizing matplotlib.

like image 110
Karl der Kaefer Avatar answered Sep 30 '22 13:09

Karl der Kaefer