首页 > 解决方案 > 通过在另一个表中排名来排序 Matplotlib 上的图例?

问题描述

我在这里环顾四周并进行了一般的谷歌搜索,但我找不到应该是一个干净的答案。

所以,我有表 [A],这是一个按国家/地区细分的时间序列,还有表 [B],它是这些国家排名的列表。

图例的默认顺序似乎是按字母顺序排列的,但是,我想使用表 [ B ] 值对表 [ A ] 图中的图例进行排序。

这可能吗?

图片链接,因为我还没有“排名”。 图表+图例与理想有序列表的屏幕截图

代码 :

fig, ax = plt.subplots()
for label, grp in cht_table.groupby('Country'):
    grp.plot(x = 'Date', y = 'moving',ax = ax,figsize=(15,10),label=label ) 

样本数据 :

TABLE A ------ Time Series ----
      Date    Country  moving
2020-01-24  Argentina     0.0
2020-01-25  Argentina     0.0
2020-01-26  Argentina     0.0
2020-01-27  Argentina     0.0
2020-01-28  Argentina     0.0

TABLE B ------ Ranking  ----
           Country
0               US
1           Brazil
2            India
3           Mexico
4             Peru
5           Russia
6   United Kingdom
7            Italy
8           France
9         Colombia
10       Argentina
11         Germany
12            Iran
13           Spain
14          Poland

标签: pythonpandasmatplotliblegend

解决方案


尝试:

for country in df_rank['Country']:
    grp = cht_table.loc[df['Country'] == country]
    grp.plot(x='Date', y='moving', ax=ax, label=country)

这是你所期望的吗?


推荐阅读