python - Matplotlib:如何从数组的列中绘制多条线,但给它们一个标签?

标签 python matplotlib plot label legend

我想绘制一个数组的多个列,并在绘图图例中将它们全部标记为相同。但是在使用时:

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/

相关文章:

python - 如何恢复被删除的库函数?

python - Django 科学记数法输入验证

python - 使用 PyCharm 我想显示 plot extra figure 窗口

python - 带有 TkAgg 错误 : PyEval_RestoreThread: null tstate on save_fig() - do I need threads enabled? 的 Matplotlib

r - 在 R 中绘制多个数据集

python - 使用 matplotlib 绘制直方图或散点图

python - 当一条记录属于多个组时,pandas groupby

python - 使用 Pandas 查找具有 Null 的 2 列之间的差异

ruby - 在 ruby​​ 中使用 matplotlib.image 是否有等效项

R 中的旋转 Axis 标签