Edit the width of bars using dataframe.plot() function in matplotlib
For anyone coming across this question:
Since pandas 0.14, plotting with bars has a 'width' command:https://github.com/pydata/pandas/pull/6644
The example above can now be solved simply by using
df.plot(kind='bar', stacked=True, width=1)
If think you have to "postprocess" the barplot with matplotlib as pandas internally sets the width of the bars.
The rectangles which form the bars are in container objects.So you have to iterate through these containers and set the width of the rectangles individually:
In [208]: df = pd.DataFrame(np.random.random((6, 5)) * 10, index=list('abcdef'), columns=list('ABCDE'))In [209]: dfOut[209]: A B C D Ea 4.2 6.7 1.0 7.1 1.4b 1.3 9.5 5.1 7.3 5.6c 8.9 5.0 5.0 6.7 3.8d 5.5 0.5 2.4 8.4 6.4e 0.3 1.4 4.8 1.7 9.3f 3.3 0.2 6.9 8.0 6.1In [210]: ax = df.plot(kind='bar', stacked=True, align='center')In [211]: for container in ax.containers: plt.setp(container, width=1) .....: In [212]: x0, x1 = ax.get_xlim()In [213]: ax.set_xlim(x0 -0.5, x1 + 0.25)Out[213]: (-0.5, 6.5)In [214]: plt.tight_layout()
"I want to control the width of bars so that the bars are connected to each other like a histogram."
A better option for the same is to use sns.displot()
Sample code:
emp = pd.read_csv("https://raw.githubusercontent.com/arora123/Data/master/emp-data.csv")sns.displot(emp, x='Department', hue='Gender', multiple='stack', height=8, aspect=1.7);