How to remove gaps between bars in Matplotlib bar chart?

MatplotlibServer Side ProgrammingProgramming

To remove gaps between bars, we can change the align value to center in the argument of bar() method.


  • Create a dictionary called data with two keys, milk and water.

  • Get the list of keys and values in the dictionay.

  • Using subplots() method, create a figure and add a set of two subplots.

  • On axis 2, use bar method to plot bars without gaps. Set the width attribute as 1.0. Set the title using set_title() method.

  • Use tight_layout() to adjust the padding between and around the subplots.

  • To display the figure, use show() method.


import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = {'milk': 12, 'water': 10}
names = list(data.keys())
values = list(data.values())
fif, (ax1, ax2) = plt.subplots(2), values, align='center', width=.05, color='yellow')
ax1.set_title("with gap"), values, align='edge', width=1.0, color='yellow')
ax2.set_title("without gap")


Published on 08-May-2021 09:47:22