首页 > 解决方案 > Matplotlib 传奇不会出现

问题描述

我尝试的每个选项都没有为我的情节显示图例。请帮忙。这是代码,并且在我的所有输入都是简单的 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()

标签: pythonmatplotliblegendlegend-properties

解决方案


plt.legend()在不指定handlesor的情况下调用会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()

推荐阅读