Cor*_*rre 5 python plot label matplotlib 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()
Run Code Online (Sandbox Code Playgroud)
我得到的图例标签和我的线条一样多。所以上面的代码在图例框中产生了四个标签。
一定有一种简单的方法可以为一组行分配标签吗?!但是我找不到它...
我想避免不得不求助于
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()
Run Code Online (Sandbox Code Playgroud)
提前致谢
因此,如果我理解正确,您会希望一次应用所有标签,而不是在每一行中输入它们。
您可以做的是将元素保存为数组、列表或类似内容,然后遍历它们。
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()
Run Code Online (Sandbox Code Playgroud)
结果是: 结果:
另外,请在此处查看@Miguels 的回答:“在 Pythons matplotlib 中添加标签列表”
希望能帮助到你!:)
小智 2
如果您想要两列具有相同的标签和刻度,您可以在绘图之前合并列。
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()
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。