Python 图例标签作为表达式

Python legend labels as expression

我正在尝试绘制 9 条线,每条线属于 3 个类别中的 1 个,我想显示一个只有 3 个标签而不是 9 个标签的图例。现在我的代码看起来像

tau = np.array([.1, .2, .3])
num_repeats = 3
plot_colors = ['r-','b-','k-']
labels = ['tau = 0.1','tau = 0.2','tau = 0.3']
plot_handles=[None]*3

for k in np.arange(tau.size):
  for ell in np.arange(num_repeats):
    ( _, _, n_iter, history,_ ) = opti.minimise (theta0, f_tol=f_tol, theta_tol = theta_tol, tau=tau[k], N=3,report=50000, m=1)
    true_energy = -59.062
    error = np.absolute(true_energy - history[:,num_p])
    plot_handles[k] = plt.plot(np.arange(0,n_iter),error,plot_colors[k],'label'=labels[k])

plt.xlabel('Iteration')
plt.ylabel('Absolute Error')
plt.yscale('log')
plt.legend(handles=plot_handles)
plt.show()

我收到一条错误消息,指出 'label' 关键字不能是表达式。有谁知道这样做的方法吗?提前致谢!

-吉姆

实现这一点的一个技巧是在内循环中只为一个图设置标签。在下面的代码中,label 只有在 ell==0:

时才为非空
tau = np.array([.1, .2, .3])
num_repeats = 3
plot_colors = ['r-','b-','k-']
labels = ['tau = 0.1','tau = 0.2','tau = 0.3']
plot_handles=[None]*3

for k in np.arange(tau.size):
  for ell in np.arange(num_repeats):
    ( _, _, n_iter, history,_ ) = opti.minimise (theta0, f_tol=f_tol, theta_tol = theta_tol, tau=tau[k], N=3,report=50000, m=1)
    true_energy = -59.062
    error = np.absolute(true_energy - history[:,num_p])
    if ell == 0:
        label = labels[k] 
    else:
        label = '' 
    plot_handles[k] = plt.plot(np.arange(0, n_iter), error, plot_colors[k], label=label)

plt.xlabel('Iteration')
plt.ylabel('Absolute Error')
plt.yscale('log')
plt.legend(handles=plot_handles)
plt.show()