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

17,240

Solution 1

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

Solution 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.

Share:
17,240

Related videos on Youtube

Cornspierre
Author by

Cornspierre

Updated on May 25, 2022

Comments

  • Cornspierre
    Cornspierre about 2 years

    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

    • behzad.nouri
      behzad.nouri almost 10 years
      use label='_nolegend_', or do x[:, 1:3].ravel()
    • behzad.nouri
      behzad.nouri almost 10 years
      or see this question