1

I would like to label a whole numpy array with only one label. The following code for example creates 6 (=2+4) labels instead of only 2 labels:

import numpy as np
import matplotlib.pyplot as plt

a = np.random.rand(10,2)
b = np.random.rand(10,4)


plt.figure()
plt.plot(a, 'blue', label = 'a')
plt.plot(b, 'red', label = 'b')
plt.legend()  

How should the code above be modified to create only 2 legend labels, 'a' and 'b'?

enter image description here

3
  • Could you clarify how many lines you expect to be drawn from the array a or b? Commented Nov 21, 2022 at 6:42
  • You are plotting 6 lines. You get 6 labels. Commented Nov 21, 2022 at 8:58
  • 1
    @medium-dimensional I would like to get one label per numpy.array, or one label per color, while plotting 2 blue lines (labeled a ) and 4 red lines (labeled b), i.e. the graph should stay the same, the legend should be only one legend blue line - a, one legend red line - b Commented Nov 21, 2022 at 11:13

1 Answer 1

2
a_lines = plt.plot(a, c='blue')
b_lines = plt.plot(b, c='red')
plt.legend(handles=[a_lines[0], b_lines[0]], labels=['a', 'b'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.