如何更改matplotlib图例框中的名称?

时间:2016-04-28 18:56:16

标签: python matplotlib graphics

我有文件in.txt,它有很多行。和1-20列(它未定义)。并包含数字。

我使用此代码绘制图形

y=np.loadtxt('in.txt')
t=np.arange(len(y))*1
plt.subplot(211)
plt.title(r'in')
plt.grid(1)
plt.plot(t,y, label = 'in')
plt.legend(borderpad = 0.1, labelspacing = 0.1)
plt.show()

It is what I have now (in this example I have 10 columns in file in.txt)

但是,而不是传说中的所有名字都是"在"中,我想要的名称如" 1"," 2"," 3&#34 ;等等(从1到n,其中n是我的in.txt文件中的列数)

2 个答案:

答案 0 :(得分:1)

你可以做到这一点的一种方法是在for循环的迭代中绘制每一行。例如:

y = np.random.random((3,5))  # create fake data
t = np.arange(len(y))
plt.subplot(211)
plt.title(r'in')
plt.grid(1)
for col_indx in range(y.shape[1]):
    plt.plot(t, y[:,col_indx], label = col_indx)
plt.legend(borderpad = 0.1, labelspacing = 0.1)
plt.show()

或者,我建议在您的情况下使用此解决方案,是使用调用plt.legend的可选参数。像这样:

plt.plot(t, y)
plt.legend(range((len(y)))

如果您想要更高级一些,请查看plt.legend的文档字符串。

如果您想使用基于1的索引开始标记,而不是从零开始,请不要忘记在标签和范围中添加+1; - )

答案 1 :(得分:0)

你正在利用plot中的广播来获取x / y,但是kwargs也没有广播。任

x = np.arange(25)
y = np.random.rand(25, 6)


fig, ax = plt.subplots()
for j, _y in enumerate(y.T, start=1):
    ax.plot(x, _y, label=str(j))
ax.legend(borderpad=0.1, labelspacing=0.1)

fig, ax = plt.subplots()
lns = ax.plot(x, y)
labels = [str(j) for j in range(1, y.shape[1] + 1)]
ax.legend(handles=lns, labels=labels, borderpad=0.1, labelspacing=0.1)