0

I've looked around on here and googling in general, but I can't find what should be a clean answer.

So, I have table [ A ], which is a timeseries, broken down by country, and table [ B ] , which is a list of those countries ranked.

The default order of the legend appears to be alphabetical, however, I'd like to use Table [ B ] values to order the legend in the table [ A ] plot.

Is this possible?

Image link as I am not yet 'ranked' . Screencap of chart+legend vs ideal ordered list

Code :

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 ) 

Sample data :

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
  • 2
    `table_a.Country = pd.Categorical(values=table_a.Country, categories=table_b.Country, ordered=True)` convert the column to categorical – Trenton McKinney Jun 24 '21 at 16:45
  • 1
    Also, you should choose a palette with more colors, because 4 of the colors are being reused. See https://stackoverflow.com/a/47146928/7758804 – Trenton McKinney Jun 24 '21 at 16:53
  • 1
    `table_a.pivot(index='Date', columns='Country', values='moving').plot(figsize=(15, 10))` to plot the data with `pandas.DataFrame.plot` – Trenton McKinney Jun 24 '21 at 16:54

1 Answers1

0

Try:

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

Is it what you expect?

Corralien
  • 109,409
  • 8
  • 28
  • 52