首页 > 解决方案 > 如何为 matplotlib 添加由数组索引名称而不是索引中的值组成的图例?

问题描述

在这里编程的新手。

我正在尝试根据列表绘制图形,但列表数组中包含一系列值。我正在尝试使用 for 循环将所有类别绘制到一个图中。当我试图绘制图表时,除了图例之外,一切都很好。我需要做的是创建一个图例,说明哪些行是“集装箱”、“货轮”、“散货船”......但是当我尝试使用 plt.legend() 时,它给了我的值“集装箱”、“货轮”、“散货船”而不是标签本身。关于如何仅绘制列表数组而不是图例的值,我可以得到帮助吗?

为了进一步说明,这里是列表值之一,仅适用于容器

Input: print(containers)

Output:
     month   vessel_type     number_of_vessels  gross_tonnage
0   2019-12   Container               1442      74170.533
8   2020-01   Container               1418      74664.129
16  2020-02   Container               1287      65183.106
24  2020-03   Container               1399      72789.161
32  2020-04   Container               1329      71068.988
40  2020-05   Container               1262      68167.275
48  2020-06   Container               1321      71659.294
56  2020-07   Container               1340      71578.085
categories=[containers,freighters,bulk_carriers,tankers,passengers,barges,tugs,miscellaneous]

for i in categories:
    plt.plot(i['month'],i['gross_tonnage'],label=i)
    plt.xlabel('months')
    plt.ylabel('gross_tonnage')
    plt.title('Changes in gross tonnage over time')
    plt.legend()```

[![Here is the screenshot of what im trying to achieve, pardon the poor drawing][1]][1]


[![this is the screenshot of the disaster][2]][2]


  [1]: https://i.stack.imgur.com/ai30L.png
  [2]: https://i.stack.imgur.com/7knj8.png

标签: pythonexcelpandasmatplotlib

解决方案


推荐阅读