0

My following code:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.pyplot import legend as legend

x = np.matrix(
    [
        [1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3],
        [4, 4, 4, 4]
    ]
)

y = x.transpose()

xx = x
yy = y+0.2

# Vertical Lines of grid:

plt.plot(x, y, 'b-o', label='data1')
plt.plot(xx, yy, 'r-*', label='data2')
legend()
plt.show()

generates figures looking like

enter image description here

I'd like to do two things:

  1. stop the legend from duplicating it self; it should only show each label once; something like

enter image description here

  1. position the legend nicely; say put it upper right corner with no overlap with the content of the graph

Easy/elegant solution is really appreciated. Thanks a lot.

Holger Just
  • 52,918
  • 14
  • 115
  • 123
Nick X Tsui
  • 2,737
  • 6
  • 39
  • 73
  • The legend placement is quite well documented: https://matplotlib.org/users/legend_guide.html#legend-location – taras Jun 15 '18 at 21:36

2 Answers2

2

Since x (and therefore, all your other arrays) is a 2-d array, when you call plot() on it, it is equivalent to calling plot() on several 1-d sets, so you're creating a label for each one of these plots.

One way to circumvent this is to assign the plots to a variable, and then insert a legend only for the first one of each.

lines = plt.plot(x, y, 'b-o')
other_lines = plt.plot(xx, yy, 'r-*')
plt.legend([lines[0], other_lines[0]], ['data1', 'data2'])

For legend positioning, take a look at this or at the documentation.

Gabriel Jablonski
  • 854
  • 1
  • 6
  • 17
0

Since your x and y are matrices, each matrix row gets the same label which is duplicated in the legend.

The solution might look like this:

for i in range(x.size[0]):
    plt.plot(x[i], y[i], label='data1' if i == 0 else None)
    plt.plot(xx[i], yy[i], label='data2' if i == 0 else None)
taras
  • 6,566
  • 10
  • 39
  • 50