user7722318
user7722318

Reputation:

Swap some labels in legend - matplotlib

Consider the following example:

import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure(figsize=(4,6))
axis = fig.add_subplot(111)
x = np.linspace(1,2,100)
axis.plot(x, x, label = "a")
axis.plot(x, x**2, label = "b")
axis.plot(x, x**3, label = "c")
axis.plot(x, x**4, label = "d")
axis.legend()

plt.show()

Is there a simple way to swap the first (a with blue line) and last object (d with red line) with each other without changing the order in the code. The legend should therefore show the order (from top to bottom):

Upvotes: 0

Views: 329

Answers (1)

yatu
yatu

Reputation: 88226

You could get the legend's handles and labels with get_legend_handles_labels and reset them in the mentioned order:

import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure(figsize=(16,10))
axis = fig.add_subplot(111)
x = np.linspace(1,2,100)
axis.plot(x, x, label = "a")
axis.plot(x, x**2, label = "b")
axis.plot(x, x**3, label = "c")
axis.plot(x, x**4, label = "d")

axis.legend()
handles, labels = axis.get_legend_handles_labels()
axis.legend([handles[-1]] + handles[1:-1] + [handles[0]], 
            [labels[-1]] + labels[1:-1] + [labels[0]])

plt.show()

enter image description here

Upvotes: 1

Related Questions