Data:
import pandas as pd
import seaborn as sns
data = sns.load_dataset('tips').iloc[0:5, [2,6]]
I use the below function to automatically generate bar plots for each variable in the data:
import numpy as np
ncols = 2
nrows = int(np.ceil(data.shape[1] / ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols,
figsize=(4*ncols, 3*nrows), sharex=True)
for ax, (name, g) in zip(axes.ravel(), data.items()):
z = g.value_counts(normalize=True, ascending=True) * 100
if isinstance(z.index, (pd.Int64Index)):
z = z.sort_index(ascending=False)
z.plot.barh(ax=ax)
ax.title.set_text(name)
It works, and bars are automatically plotted in most to least frequent order (e.g. sex), except for numerical categories, which are plotted in numerical order (e.g. size):
That said, the function also triggers this future warning:
FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.
I have tried:
if isinstance(z.index, (int)):
The above does not generate a warning, but bars are not sorted as I wish.
I have also tried:
if isinstance(z.index, (pd.Index(datatype='int64'))):
But this triggers an error, Index(...) must be called with a collection of some kind, None was passed. In this last case, I also don't know how to specify both float and int.
