Reputation:
I am creating a bar chart like this:
gender = ['M', 'F']
numbers = [males,females]
bars = plt.bar(gender, numbers, width=0.1, bottom=None, align='center', data=None)
plt.show()
The two bars in my graph are quite distant from each other. Is there any way to bring them closer WITHOUT changing the width? If I increase the width, the space between the bars reduces but I don't want an increased width. Maybe something with changing the size of the plot could work?
Upvotes: 2
Views: 1304
Reputation: 80279
You can change the xlim
s. With a categorical index, the x-positions are numbered internally as 0, 1, ...
. Matplotlib adds a default padding of 5% on each side, which is too short when there are only two bars. Optionally, you can also change the ylim
to make a bit more room for the text on top of the bar:
from matplotlib import pyplot as plt
gender = ['M', 'F']
numbers = [1644, 1771]
bars = plt.bar(gender, numbers, width=0.1, bottom=None, align='center', data=None)
for x, y in zip(gender, numbers):
plt.text(x, y, f'{y}\n', ha='center', va='center')
plt.xlim(-0.9, len(gender) - 1 + 0.9)
plt.ylim(0, max(numbers) * 1.1)
plt.show()
Upvotes: 3