I'm trying to make a bar chart where there is equal space around all bars using pandas
. When I don't specify a width
this works fine out of the box. The problem is that when I specify the width
, the margin on the left and right of the chart doesn't change, which makes the space around the left-most and right-most bar bigger than for the others. I've tried adjusting the margin with ax.margins(x=0)
but this has no effect. How can I keep an even space for all bars?
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
print(matplotlib.__version__) # 3.5.3
print(pd.__version__) # 1.3.5
def grid_in_between(ax):
"""Create gridlines in between (major) data axis values using minor gridlines
Args:
ax: Matplotlib axes
"""
ticks = ax.get_xticks()
ax.set_xticks(np.array(ticks[:-1]) + np.diff(ticks) / 2, minor=True)
ax.grid(visible=True, axis='x', which='minor')
ax.grid(visible=False, axis='x', which='major')
ax.tick_params(which='minor', length=0, axis='x')
df = pd.DataFrame({'value': range(8)})
fig, ax = plt.subplots(1, 2)
df.plot.bar(ax=ax[0])
df.plot.bar(ax=ax[1], width=.95)
grid_in_between(ax[0])
grid_in_between(ax[1])
ax[0].set_title('Evenly spaced')
ax[1].set_title('Parameter width\nmakes first and last space bigger')
ax[1].margins(x=0) # no effect
plt.show()