Skip to content Skip to sidebar Skip to footer

How Do You Remove Spaces Between Bars In Bar Charts For Where Plotted Values Are Zero?

Sometimes datasets have a number of variables with a selection of other 'things' that contribute to them. It can be useful to show the contribution (e.g. %) to a variable of these

Solution 1:

As commented, there's no inbuilt function for this. Here's an approach that you can explore:

# we will use this to shift the bars
shifted = df.notnull().cumsum()

# the width for each bar
width = 1 / len(df.columns)

fig = plt.figure(figsize=(10,3))
ax = plt.gca()
colors = [f'C{i}' for i in range(df.shape[1])]
for i,idx in enumerate(df.index):
    offsets = shifted.loc[idx]
    values = df.loc[idx]
    ax.bar(np.arange(df.shape[1]) + offsets*width, values, 
           color=colors[i], width=width, label=idx)
    
ax.set_xticks(np.arange(df.shape[1]))
ax.set_xticklabels(df.columns);
ax.legend()

Output:

enter image description here

Post a Comment for "How Do You Remove Spaces Between Bars In Bar Charts For Where Plotted Values Are Zero?"