我想绘制一个数组的多个列,并在绘图图例中将它们全部标记为相同。但是在使用时:
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()
我得到的图例标签与我拥有的线条一样多。所以上面的代码在图例框中产生了四个标签。
必须有一种简单的方法来为一组线分配标签?!但是我找不到它...
我想避免不得不诉诸
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()
提前致谢
最佳答案
因此,如果我没听错的话,您希望一次应用所有标签,而不是逐行输入。
您可以做的是将元素保存为数组、列表或类似的,然后遍历它们。
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()
结果是: result:
此外,请在此处查看@Miguels 的回答:"Add a list of labels in Pythons matplotlib"
希望对您有所帮助! :)
关于python - Matplotlib:如何从数组的列中绘制多条线,但给它们一个标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25855014/