python - 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()
解决方案
plt.legend()
在不指定handles
or的情况下调用会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()
推荐阅读
- javascript - 是否有更多方法可以阻止cors?
- javascript - 最大的 Contentful Paint 正在等待未知的东西
- swift - 如何在 WatchOS 上获得具有完全透明背景的 SwiftUI Slider?
- python - 如何根据数字的重复从numpy数组中提取特定数字
- javascript - 如果数组中的 id 匹配,则设置行中第一列的值
- twitter-bootstrap - CSS Navbar 被网页顶部截断
- node.js - 构建期间出错:是什么导致错误 [ERR_IPC_CHANNEL_CLOSED]:通道关闭?
- javascript - 如何在 Slack 的线程中使用自定义斜杠命令
- r - 我需要使用可以选择的不同列来绘制图表,
- python - 无法使用 xpath 从 href 标记中提取文本