2

I would like to "merge" the first level of multi index, i.e. have a centered "USA" and "EU" instead of the tupples.

Minimal Exmaple

df = pd.DataFrame(data={"region":["USA","USA","EU","EU"], "sctr":["HH","NFC","HH","NFC"], "values":[1,2,3,4]})
df = df.set_index(["region","sctr"])

fig, ax = plt.subplots(1,figsize=(8,6))
df.plot(kind="bar")
plt.xticks(rotation = 0)
plt.show()

Output enter image description here

Desired output Using excel, one gets the desired output (almost) by default:

enter image description here

The ideal solution is simple, short and does not require any manual adjustments if more regions / sectrs are added.

1 Answer 1

3

There are other ways to make the x-axis ticks into two lines: the first line is taken from the multi-index and made into a list; the second line is placed from the multi-index list by the text function. Hiding the existing labels is handled by the plot parameter.

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame(data={"region":["USA","USA","EU","EU"], "sctr":["HH","NFC","HH","NFC"], "values":[1,2,3,4]})
df = df.set_index(["region","sctr"])

fig, ax = plt.subplots(1,figsize=(8,6))
df.plot(kind='bar', xlabel='', ax=ax)
ax.set_xticklabels(df.index.get_level_values(level=1).tolist(), rotation=0)

 for container in ax.containers:
    for i,child in enumerate(container.get_children()):
        if i == 0:
            ax.text(child.xy[0]+child.get_width(), -0.08, df.index.get_level_values(level=0)[0], ha='center', transform=ax.transAxes)
        elif i == 2:
            ax.text(child.xy[0]-(child.get_width()*2), -0.08, df.index.get_level_values(level=0)[2], ha='center', transform=ax.transAxes)

plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

this works as indicated, but I had hoped for a simpler and less manual-adjustment requiring solution.
Is the manual adjustment at the X-axis? It is possible to make this a variable since the whole figure is one. The value of -0.08 is difficult.
Fixed the problem so that the value of the x-axis can be obtained automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.