Home > Net >  Plot multiindex dataframe groupping internal level on one subplot
Plot multiindex dataframe groupping internal level on one subplot

Time:02-03

I want to plot multiindex dataframe on one plot with sublots.

Dataframe example

import datetime
import random
base = datetime.datetime.today()
numdays = 7
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]
df_plot = pd.DataFrame({"y": random.choices(range(0, 100), k=16 * numdays)},
   index=pd.MultiIndex.from_product(
    [["A", "B", "C", "D"],
     ["m1", "m2", 'm3', 'm4'], 
     date_list],
    names=["Group", "metric", "date"]))
df_plot.head()
Group   metric  date     y
A   m1  2022-02-02      18
        2022-02-01      47
        2022-01-31      2

I want four subplots in one figure where each subplot corresponds to one group (A, B, C, D) and on each sublot there are four lines that correspond to each metric (m1, m2, m3, m4). X-axis is date, y-axis is cell value in one-column dataframe with multiindex (see above example).

I know that plotting may be done in several ways by groupping dataframe by index.

Is there elegant solution in one command like below? There must be four supplots with four lines on each subplot.

df_plot.plot(..., subplots=True, layout=(2, 2))

CodePudding user response:

You can try reset the index before groupby, then manually plot into a pre-populated axis grid:

df_plot = df_plot['y'].unstack('metric').reset_index('Group')
fig, axes = plt.subplots(2,2)

for ax, (group, data) in zip(axes.ravel(), df_plot.groupby('Group')):
    data.plot(ax=ax)

Output:

enter image description here

  •  Tags:  
  • Related