scott huang
scott huang

Reputation: 2688

How to place legend next to each line in matplitlib

Here is my plot, you can see that there is over 15 lines in a plot, although I put a legend in the top right corner, I still can not easily differentiate each line.

Is there a better way of doing this? for example, put legend next each line? I can not find a API. any help is appreciated.

enter image description here

You can

Upvotes: 4

Views: 4367

Answers (1)

Tom de Geus
Tom de Geus

Reputation: 5975

The comment is indeed what you need. This post is just to make a solution a bit more explicit.

Using annotate a label can be placed at a specific position. I.e. it can be placed based on the coordinates of the last point of the curve, e.g. (xlast, ylast). To make the plot more pretty, the horizontal position can increased by e.g. 2% to place the label at a small distance from the last point (i.e. the label is placed at (1.02*xlast, ylast)).

In a small example:

import numpy             as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()


x     = np.linspace(0,1,2)
y     = 1*x
label = '1x'
color = 'b'

ax.plot(x, y, color=color)

ax.annotate(label,
  xy     = (     x[-1], y[-1]),
  xytext = (1.02*x[-1], y[-1]),
  color  = color,
)


x     = np.linspace(0,1,2)
y     = 2*x
label = '2x'
color = 'r'

ax.plot(x, y, color=color)

ax.annotate(label,
  xy     = (     x[-1], y[-1]),
  xytext = (1.02*x[-1], y[-1]),
  color  = color,
)


ax.set_xlim([0,1.2])

ax.set_xlabel('x')
ax.set_ylabel('y')

plt.savefig('so.png')
plt.show()

Which results in:

enter image description here

Upvotes: 3

Related Questions