# Pandas, make the bars of a bar graph have equal widths

What do I need to change so that ax1 uses the same width for bars as ax2?

import pandas as pd
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(2)

pd.Series([1]).plot(kind='bar', width=0.5, ax=ax1)
pd.Series([1, 2, 3]).plot(kind='bar', width=0.5, ax=ax2)

plt.show()


## 2 Answers

Looking at the documentation, it seems there is no obvious way.

Looking at the source code of the plt.bar method (held on Axes objects), and searching for uses of the width parameter, it starts getting quite complicated and I don't think it is meant to be used for this purpose explicitly! Lots of internal methods, starting with a _, like self._convert_dx is a clue.

I would just offer a nasty hack for your toy example, hoping it is applicable to your actual data:

In [1] : import pandas as pd
...: import matplotlib.pyplot as plt
...:
...: fig, (ax1, ax2) = plt.subplots(2)
...:
...: pd.Series([0, 1, 0]).plot(kind='bar', ax=ax1)
...: pd.Series([1, 2, 3]).plot(kind='bar', ax=ax2)


Gives

So the hack is to make the length of your datasets the same, adding zeros where needed.

n1k31t4 provided an interesting view that made me realize that the width depends on the limits of x axis. Learning that I made the following adjustments:

import pandas as pd
import numpy.random as rd
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(2)

width = .5

s1 = pd.Series(rd.randint(10, size=rd.randint(1, 10)))
s2 = pd.Series(rd.randint(10, size=rd.randint(1, 10)))

s1.plot(kind='bar', width=width, ax=ax1)
s2.plot(kind='bar', width=width, ax=ax2)

ax1.set_xlim([-width, (2 + len(s2)) * width])
ax2.set_xlim([-width, (2 + len(s2)) * width])
ax1.set_xlim([-.5, max(len(s1), len(s2)) - 1 + width])
ax2.set_xlim([-.5, max(len(s1), len(s2)) - 1 + width])

plt.show()


This seems to be universal enough while not requiring to touch the members of series.