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
JavaScript
x
8
1
df = pd.DataFrame(data={"region":["USA","USA","EU","EU"], "sctr":["HH","NFC","HH","NFC"], "values":[1,2,3,4]})
2
df = df.set_index(["region","sctr"])
3
4
fig, ax = plt.subplots(1,figsize=(8,6))
5
df.plot(kind="bar")
6
plt.xticks(rotation = 0)
7
plt.show()
8
Desired output Using excel, one gets the desired output (almost) by default:
The ideal solution is simple, short and does not require any manual adjustments if more regions / sectrs are added.
Advertisement
Answer
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.
JavaScript
1
19
19
1
import matplotlib.pyplot as plt
2
import pandas as pd
3
4
df = pd.DataFrame(data={"region":["USA","USA","EU","EU"], "sctr":["HH","NFC","HH","NFC"], "values":[1,2,3,4]})
5
df = df.set_index(["region","sctr"])
6
7
fig, ax = plt.subplots(1,figsize=(8,6))
8
df.plot(kind='bar', xlabel='', ax=ax)
9
ax.set_xticklabels(df.index.get_level_values(level=1).tolist(), rotation=0)
10
11
for container in ax.containers:
12
for i,child in enumerate(container.get_children()):
13
if i == 0:
14
ax.text(child.xy[0]+child.get_width(), -0.08, df.index.get_level_values(level=0)[0], ha='center', transform=ax.transAxes)
15
elif i == 2:
16
ax.text(child.xy[0]-(child.get_width()*2), -0.08, df.index.get_level_values(level=0)[2], ha='center', transform=ax.transAxes)
17
18
plt.show()
19