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()

Thanks in advance

Cornspierre
  • 322
  • 1
  • 5
  • 14

2 Answers2

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! :)

Dominique Paul
  • 1,623
  • 2
  • 18
  • 31
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.

  • Today [flatten](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.html) has no numeric parameter, `order` is a letter. – mins Jul 03 '23 at 09:02