[Python] Multi-level x-axis bar graph in pandas

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    This questions relates to a similar question which can be found here: How to create a variability plot with a multi-level grouped label x-axis

    I have stolen code from this post to get myself started: Plot both multi-index labels on x-axis in pandas plot

    ...but I am currently stuck

    my data is in this format:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt

    # for same set of random variates
    np.random.seed(seed = 123)
    dates = pd.date_range(start = "28/05/2024", end = "28/05/2025", freq = "D")
    vehicles = np.random.choice(["A", "B", "C", "D", "E", "F"], size = len(dates))
    kilometres = np.random.normal(loc = 170, scale = 76, size = len(dates)).round(2)
    df = pd.DataFrame({"date":dates, "fleet no":vehicles, "kilometres":kilometres})
    # groupby to get data into appropriate format
    df = df.groupby(by = [df["date"].dt.to_period("M"), "fleet no"]).agg({"date":"count", "kilometres":"sum"})\
    .rename(columns = {"date":"days"}).reset_index(level = None)


    I want to be able to produce a graph whereby the x-axis is grouped by both date and fleet no, the same way they are formatted in the subplots produced by this code:

    groups = df.groupby(by = "date")
    figure, axes = plt.subplots(nrows = 1, ncols = len(groups), sharey = True, figsize = (16, 5))

    for ax, (year, group) in zip(axes, groups):
    group.set_index("fleet no").rename_axis(year)["days"].plot(kind = "bar", ax = ax)


    except it should be all in one plot

    Additionally, the year-month axis labels should be formatted in the "%Y-%b" format.

    any help would be greatly appreciated

    Continue reading...

Compartilhe esta Página