Matplotlib 图例不会出现

Eva*_*and 2 python matplotlib legend legend-properties

我尝试的每个选项都没有为我的情节显示图例。请帮忙。这是代码,并且绘图工作正常,我的所有输入都是简单的 NumPy 数组。添加图例功能时,角落里会出现一个小框,因此我知道指令正在运行,但其中没有任何内容。我正在使用 Jupyter Notebook,我的其他尝试显示在 后#。谁能找到缺陷:

import pandas as pd
import matplotlib.pyplot as plt

ratios = ['Share Price', 'PEG', 'Price to Sales']
final_z_scores = np.transpose(final_z_scores)
print(final_z_scores)

fig = plt.figure(figsize=(6,4))

#plt.plot(ratios, final_z_scores[0], ratios, final_z_scores[1], ratios, final_z_scores[2])
first = plt.plot(ratios, final_z_scores[0])
second = plt.plot(ratios, final_z_scores[1])

#ax.legend((first, second), ('oscillatory', 'damped'), loc='upper right', shadow=True)
ax.legend((first, second), ('label1', 'label2'))
plt.xlabel('Ratio Types')
plt.ylabel('Values')
plt.title('Final Comparisons of Stock Ratios')
plt.legend(loc='upper left')

plt.plot()
plt.show()
Run Code Online (Sandbox Code Playgroud)

Wil*_*ler 6

调用时plt.legend()不指定handles或显式遵循此处labels概述的此调用签名的描述:

当您不传入任何额外参数时,将自动确定要添加到图例的元素。

在这种情况下,标签取自艺术家。您可以在创建艺术家时指定它们,也可以通过调用set_label()艺术家的方法来指定它们:

因此,为了在示例中自动填充图例,您只需为不同的图分配标签:

import pandas as pd
import matplotlib.pyplot as plt

ratios = ['Share Price', 'PEG', 'Price to Sales']
final_z_scores = np.transpose(final_z_scores)

fig = plt.figure(figsize=(6,4))
first = plt.plot(ratios, final_z_scores[0], label='label1')
second = plt.plot(ratios, final_z_scores[1], label='label2')

plt.xlabel('Ratio Types')
plt.ylabel('Values')
plt.title('Final Comparisons of Stock Ratios')
plt.legend(loc='upper left')

# Calling plt.plot() here is unnecessary 
plt.show()
Run Code Online (Sandbox Code Playgroud)