ddas
ddas

Reputation: 199

How to Modify Matplotlib Legend

Here is my code.

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

plt.plot(np.arange(0.0,12.0,2.0), 'r-', label='P = increasing')
plt.plot(np.arange(10.0,0.5,-1.8), 'g-', label='P = decreasing')


plt.legend()
plt.show()

The output is shown in the following figure., enter image description here

But I want to modify the legend so that it can be shown as, enter image description here

How to do that?

Upvotes: 2

Views: 1966

Answers (2)

nahusznaj
nahusznaj

Reputation: 493

This obtains the output you show in the image.

fig, ax = plt.subplots()

ax.plot(np.arange(0.0,12.0,2.0), 'r-')
ax.plot(np.arange(10.0,0.5,-1.8), 'g-')

handles, labels = ax.get_legend_handles_labels()
labels = ['P = increasing', ' = decreasing']

ax.legend(handles, labels, loc = 'center right', markerfirst = False)
plt.show()

enter image description here

Upvotes: 1

niraj
niraj

Reputation: 18218

You can try:

plt.legend(markerfirst = False)

From documentation:

markerfirst : bool

If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label. Default is True.

Upvotes: 4

Related Questions