Home > database >  Plot both multi-index labels on x-axis in pandas plot
Plot both multi-index labels on x-axis in pandas plot

Time:10-15

I have a multi-index dataframe and would like to both index as x-axis labels. Where each of the "forecasts" indexenter image description here

my dataframe looks like this:

year    forecast  most important observation  percent increase when left out
2020    PV6SM     Harkins                     17.371021
2050    PV6SM     Harkins                     10.569719
2099    PV6SM     Harkins                     12.343476
2020    PV3S      PV3S                        34.095863
2050    PV3S      PV3S                        32.565513
2099    PV3S      PV3S                        26.110555

CodePudding user response:

You need to rename the index with the year:

groups = df.groupby("year")
fig, axes = plt.subplots(1, len(groups), sharey=True, figsize=(14,8))

for ax, (year, group) in zip(axes, groups):
    # The rename_axis function makes the difference
    group.set_index("forecast").rename_axis(year)["percent increase when left out"].plot(kind="bar", ax=ax)
    ax.tick_params(axis='both', which='both', length=0)

ax.legend()
fig.subplots_adjust(wspace=0)

Output:

output

  • Related