Let's take this DataFrame:
import itertools
import numpy as np
import pandas as pd
tuples = list(itertools.product(list('abcd'), [1,2]))
index = pd.MultiIndex.from_tuples(tuples, names=['letter', 'digit'])
data = np.random.rand(8, 4)
df = pd.DataFrame(data, index=index, columns=list('abcd'))
I have the following function to get stacked bar plots and save them:
def build_stacked_bar_graph(df: pd.DataFrame, xlabel: str, ylabel: str, title: str, saving_name: str, yticks: list=None)->None:
plt.rcParams["figure.figsize"] = [15, 15]
ax = df.sort_index().plot(kind='bar', fontsize=14, stacked=True)
plt.ylabel(ylabel, size=16)
plt.xlabel(xlabel, size=16)
plt.title(title, size=20)
if isinstance(df, pd.DataFrame):
plt.legend(fontsize=14)
if yticks is not None:
plt.yticks(yticks)
plt.savefig(f'img/{saving_name}.jpg', bbox_inches = 'tight', pad_inches = 0.1)
If I apply this function to my Dataframe I get:
build_stacked_bar_graph(df, 'abc', 'value', 'Test', 'test')
I would like the x ticks to be multilevel, not tuples and the bars with the same lvl 0 (a,b,c,d) to be close to each other.
I am stuck for quite some time. Can someone help me?