[Python] For multi-index columns in pandas dataframe, how can I group index of a particular...

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    I have a pandas dataframe which is basically a pivot table.

    df.plot(kind = "bar",stacked = True) results in following plot. The labels in x-axis are congested as shown. [​IMG]

    In Excel I can group the first index value for Scenarios pes, tes and des are clear and distinct as shown: [​IMG]

    How can I create similar labels in x-axis using matplotlib in Python?

    Here is a sample dataset with minimal code:

    dict = {'BatteryStorage': {('des-PDef3', 'Central Africa'): 0.0,
    ('des-PDef3', 'Eastern Africa'): 2475.9,
    ('des-PDef3', 'North Africa'): 98.0,
    ('des-PDef3', 'Southern Africa'): 124.0,
    ('des-PDef3', 'West Africa'): 1500.24,
    ('pes-PDef3', 'Central Africa'): 0.0,
    ('pes-PDef3', 'Eastern Africa'): 58.03,
    ('pes-PDef3', 'North Africa'): 98.0,
    ('pes-PDef3', 'Southern Africa'): 124.0,
    ('pes-PDef3', 'West Africa'): 0.0,
    ('tes-PDef3', 'Central Africa'): 0.0,
    ('tes-PDef3', 'Eastern Africa'): 1175.86,
    ('tes-PDef3', 'North Africa'): 98.0,
    ('tes-PDef3', 'Southern Africa'): 124.0,
    ('tes-PDef3', 'West Africa'): 0.0},
    'Biomass PP': {('des-PDef3', 'Central Africa'): 44.24,
    ('des-PDef3', 'Eastern Africa'): 1362.4,
    ('des-PDef3', 'North Africa'): 178.29,
    ('des-PDef3', 'Southern Africa'): 210.01999999999998,
    ('des-PDef3', 'West Africa'): 277.4,
    ('pes-PDef3', 'Central Africa'): 44.24,
    ('pes-PDef3', 'Eastern Africa'): 985.36,
    ('pes-PDef3', 'North Africa'): 90.93,
    ('pes-PDef3', 'Southern Africa'): 144.99,
    ('pes-PDef3', 'West Africa'): 130.33,
    ('tes-PDef3', 'Central Africa'): 44.24,
    ('tes-PDef3', 'Eastern Africa'): 1362.4,
    ('tes-PDef3', 'North Africa'): 178.29,
    ('tes-PDef3', 'Southern Africa'): 210.01999999999998,
    ('tes-PDef3', 'West Africa'): 277.4}}

    df = pd.DataFrame.from_dict(dict)
    df.plot(kind = "bar",stacked = True)
    plt.show()

    Continue reading...

Compartilhe esta Página