Plot two levels of x_ticklabels on a pandas multi-index dataframe [duplicate]

Try the following code. It’s achieved by creating a subplot for each level[0] index in your case year and using that as the x_label. And for each subplot we plot the data.

def plot_function(x, ax):
    ax = graph[x]
    ax.set_xlabel(x, weight="bold")
    return serotype_df.xs(x).plot(kind='bar', stacked='True', ax=ax, legend=False)

n_subplots = len(serotype_df.index.levels[0])
fig, axes = plt.subplots(nrows=1, ncols=n_subplots, sharey=True, figsize=(14, 8))  # width, height

graph = dict(zip(serotype_df.index.levels[0], axes))
plots = list(map(lambda x: plot_function(x, graph[x]), graph))
ax.tick_params(axis="both", which="both", length=0)
fig.subplots_adjust(wspace=0)

plt.legend()
plt.show()

If you’re not making much changes to each subplot you can always do the following:

plots = list(map(lambda x: serotype_df.xs(x).plot(kind='bar', stacked='True', ax=graph[x], legend=False).set_xlabel(x, weight="bold"), graph))

That way you don’t have to create or use the plot_function

enter image description here

Leave a Comment