Python图例标签作为表达式

2024-04-27 00:53:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着画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”关键字不能是表达式时出错。有人知道怎么做吗?提前谢谢!你知道吗

-吉姆


Tags: inforlabelsplotnpplthistorynum
1条回答
网友
1楼 · 发布于 2024-04-27 00:53:36

实现这一点的一个技巧是只为内部循环中的一个图设置一个标签。在下面的代码中,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()

相关问题 更多 >