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
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! :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With