【问题标题】:How to get a legend for a graph using Python/matplotlib [duplicate]如何使用 Python/matplotlib 获取图表的图例 [重复]
【发布时间】:2021-04-05 12:41:54
【问题描述】:

我正在测试一个图表,除了图例之外的所有内容都有效。我已经运行了下面的代码,但没有在 plt.plot 中找到标签,但我仍然没有得到返回的图例。有谁知道为什么?

plt.figure(figsize=(8,5))

 
plt.title('Test Graph', fontdict={'fontweight':'bold', 'fontsize': 24})


plt.plot(excl.Date, excl.Pop2020, 'g.-', label = 'test')

plt.xticks(excl.Date[::4])

plt.xlabel('Date')
plt.ylabel('Pop')

plt.legend

plt.savefig('testpic.png', dpi = 300)

plt.show()

【问题讨论】:

  • plt.legend() 也许?

标签: python-3.x matplotlib


【解决方案1】:

在您的示例中,您忘记了函数调用末尾的() legend。另外,我建议使用 matplotlib 的面向对象的 API:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)

fig, ax = plt.subplots(1)
ax.plot(x, 'g.-', label='test')
ax.legend()

有关图例如何运作的更多信息,请访问documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-24
    • 2015-08-05
    • 1970-01-01
    • 2015-09-19
    • 2014-01-23
    • 1970-01-01
    • 2013-04-27
    • 2021-12-13
    相关资源
    最近更新 更多