How to remove margins from Matplotlib bar chart?
1 Answer
You can set the limits of the axes to -.5
and len(df)-.5
to avoid the margins of the bar chart.
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams["patch.force_edgecolor"] = True
df = pd.DataFrame([1,2])
df.plot.bar(width=1)
plt.xlim(-0.5,len(df)-.5)
plt.show()
-
2Also, if you use
plt.xlim(ax.patches[0].get_x(), ax.patches[-1].get_x())
you don't need to hardcode the values.– RaquelJun 11, 2020 at 14:33 -
1
-
1@Vincent Yes, it misses the last bar but it can be handled by adding the last bar's width:
plt.xlim(ax.patches[0].get_x(), ax.patches[-1].get_x() + ax.patches[-1].get_width())
Jan 2 at 6:35