Python Pyplot:仅显示图例中的前3行
我正在运行模拟200次,并以高透明度将3个输出列表绘制为3行。这使我能够显示模拟之间的差异 问题是我的图例显示的是3x200项,而不是3项。如何使每行的图例显示一次Python Pyplot:仅显示图例中的前3行,python,matplotlib,Python,Matplotlib,我正在运行模拟200次,并以高透明度将3个输出列表绘制为3行。这使我能够显示模拟之间的差异 问题是我的图例显示的是3x200项,而不是3项。如何使每行的图例显示一次 for simulation in range(200): plt.plot(num_s_nodes, label="susceptible", color="blue", alpha=0.02) plt.plot(num_r_nodes, label="recovered", color="green",
for simulation in range(200):
plt.plot(num_s_nodes, label="susceptible", color="blue", alpha=0.02)
plt.plot(num_r_nodes, label="recovered", color="green", alpha=0.02)
plt.plot(num_i_nodes, label="infected", color="red", alpha=0.02)
plt.legend()
plt.show()
加
对于不希望显示在图例中的任何打印。因此,您可以在代码中执行以下操作:
..., label='_nolegend_' if simulation else 'susceptible', ...
同样,对于其他人,或者如果您不喜欢不确定的代码:
..., label=simulation and '_nolegend_' or 'susceptible',...
为避免打印中出现额外的逻辑,请对图例条目使用“代理”艺术家:
# no show lines for you ledgend
plt.plot([], label="susceptible", color="blue", alpha=0.02)
plt.plot([], label="recovered", color="green", alpha=0.02)
plt.plot([], label="infected", color="red", alpha=0.02)
for simulation in range(200):
# your actual lines
plt.plot(num_s_nodes, color="blue", alpha=0.02)
plt.plot(num_r_nodes, color="green", alpha=0.02)
plt.plot(num_i_nodes, color="red", alpha=0.02)
plt.legend()
plt.show()
您也可以将参数修改为
plt.legend()
,如下所示,除前三个图例条目外,所有其他图例条目都将隐藏:
plt.legend(['susceptible', 'recovered', 'infected'])
这样做的好处是,如果使用tex解析线标签,它也可以工作。我无法让“nolegend”处理这个问题。@tacaswell设置
label=None
实际上有细微的不同,不会将艺术家从图例中删除。例如:plt.plot([0,1],[0,1],label=None);plt.图([0,1],[1,0]);plt.legend(['justthislabel'])
将在图例中显示两项。将无
替换为“\u nolegend”
只会产生一个。
plt.legend(['susceptible', 'recovered', 'infected'])