6

I would like to plot multiple columns of an array and label them all the same in the plot legend. However when using:

x = np.loadtxt('example_array.npy')
plt.plot(x[:,1:3],label = 'first 2 lines')
plt.plot(x[:,3:5],label = '3rd and 4th lines')
plt.legend()

I get as many legend labels as lines I have. So the above code yields four labels in the legend box.

There must be a simple way to assign a label for a group of lines?! But I cannot find it...

I would like to avoid having to resort to

x = np.loadtxt('example_array.npy')
plt.plot(x[:,1],label = 'first 2 lines')
plt.plot(x[:,1:3])
plt.plot(x[:,3],label = '3rd and 4th lines')
plt.plot(x[:,3:5])
plt.legend()
2
  • use label='_nolegend_', or do x[:, 1:3].ravel() Commented Sep 15, 2014 at 19:06
  • or see this question Commented Sep 15, 2014 at 19:13

2 Answers 2

5

So if I get you correctly you would like to apply your labels all at once instead of typing them out in each line.

What you can do is save the elements as a array, list or similar and then iterate through them.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1,10)
y1 = x
y2 = x*2
y3 = x*3

lines = [y1,y2,y3]
colors  = ['r','g','b']
labels  = ['RED','GREEN','BLUE']

# fig1 = plt.figure()
for i,c,l in zip(lines,colors,labels):  
    plt.plot(x,i,c,label='l')
    plt.legend(labels)    
plt.show()

Which results in: result:

Also, check out @Miguels answer here: "Add a list of labels in Pythons matplotlib"

Hope it helps! :)

Sign up to request clarification or add additional context in comments.

Comments

2

If you want a same label and ticks for both the columns you can just merge the columns before plotting.

x = np.loadtxt('example_array.npy')
plt.plot(x[:,1:3].flatten(1),label = 'first 2 lines')
plt.plot(x[:,3:5].flatten(1),label = '3rd and 4th lines')
plt.legend()

Hope this helps.

1 Comment

Today flatten has no numeric parameter, order is a letter.

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.