Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: How to plot multiple lines from columns of an array, but give them one label?

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

like image 969
Cornspierre Avatar asked Sep 15 '14 19:09

Cornspierre


2 Answers

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

like image 134
Dominique Paul Avatar answered Nov 14 '22 23:11

Dominique Paul


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.

like image 26
Sainath Motlakunta Avatar answered Nov 14 '22 22:11

Sainath Motlakunta