1
$\begingroup$

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()

enter image description here

$\endgroup$
0
$\begingroup$

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

Aligned bars

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

$\endgroup$
0
$\begingroup$

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()

enter image description here

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.