6

How to remove margins from Matplotlib bar chart?

enter image description here

1
  • 4
    Why have you added blurry screenshots of your code and the output rather than include them in the question?
    – roganjosh
    Oct 17, 2017 at 19:48

1 Answer 1

14

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

enter image description here

3
  • 2
    Also, if you use plt.xlim(ax.patches[0].get_x(), ax.patches[-1].get_x()) you don't need to hardcode the values.
    – Raquel
    Jun 11, 2020 at 14:33
  • 1
    I think with ax.patches[-1].get_x()) you miss the last bar
    – Vincent
    Feb 2, 2021 at 11:33
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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