Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib set width of bars to be the same size for all subplots

I have 3 subplots in my figure below. I set the width to be 0.3 for each of the subplots but the bars are now not even in size. How do i make the bars same size and yet maintain a spacing between the pairs of bars?

my code:

    g=['col1','col2','col3']
    fig, axs = plt.subplots(1,len(g)/1,figsize = (50,20))
    axs = axs.ravel()

    for j,x in enumerate(g):
        df_plot[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j],position = 0, title = 'mytitle', fontsize = 30, width=0.3)
        df_plot2[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j],position = 1, color='red', width=0.3)
        axs[j].title.set_size(40)
        fig.tight_layout()  

enter image description here

like image 891
jxn Avatar asked Aug 31 '25 05:08

jxn


1 Answers

If all subplots should have the same size, the idea would be to set the limits of the xaxis such that all bars have the same width.

ax.set_xlim(-0.5,maxn-0.5)

where maxn would be the maximum number of bars to plot.

enter image description here

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

col1 = np.random.choice(["Mon", "Tue", "Wed", "Thu", "Fri"], 100, p=[0.1, 0.4, 0.2, 0.2,0.1])
col2 = np.random.choice([0,1], 100, p=[0.4, 0.6])
col3 = np.random.choice(list("abcde"), 100, p=[0.15, 0.35, 0.1, 0.3,0.1])
df = pd.DataFrame({'col1':col1,'col2':col2,'col3':col3})


g=['col1','col2','col3']
fig, axs = plt.subplots(1,len(g)/1,figsize = (10,4))
axs = axs.ravel()

maxn = 5
for j,x in enumerate(g):
    df[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j],position = 0, title = 'mytitle', width=0.3)
    df[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j],position = 1, color='red', width=0.3)
    axs[j].set_xlim(-0.5,maxn-0.5)

fig.tight_layout()
plt.show()
like image 194
ImportanceOfBeingErnest Avatar answered Sep 02 '25 17:09

ImportanceOfBeingErnest