0

Hellow everyone, I have the next question about legends in matplotlib:

My code is the following:

x=[1,2,3,-4,-5]
y=[5,-3,6,7,-2]

plt.plot([x],[y], marker='o', markersize=6, color="green")
plt.grid()
plt.axhline(y=0.0,color='black',alpha=0.3)
plt.axvline(x=0.0,color='black',alpha=0.3)
plt.xlim(-7,7)
plt.ylim(-9,9)
plt.show()

The plot is:

Plot

Now I want put some labels on each point in this imagen, for example:

plot2

Is it that possible?. Thanks in advance for your help.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Héctor Alonso
  • 181
  • 1
  • 2
  • 12

1 Answers1

1

Use plt.annotate :

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)

ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )

ax.set_ylim(-2,2)
plt.show()

enter image description here

You can omit the arrow and change it's properties by playing around with the arrowprops parameter.

For multiple points just make a loop:

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
    label,
    xy=(x, y), xytext=(-20, 20),
    textcoords='offset points', ha='right', va='bottom',
    bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
    arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

enter image description here

Turtalicious
  • 430
  • 2
  • 5