How do I adjust the width of bars in matplotlib?

To adjust the width of bars in matplotlib, you need to specify the width of each bar in the code when creating the plot. The width of the bars can be adjusted by setting the width parameter in the function call for the plot, such as plt.bar(x,y,width=0.5) which sets the width of the bars to 0.5. Alternatively, you can use the figsize argument to adjust the size of the entire plot, which will proportionally affect the width of the bars.


You can use the width argument to adjust the width of bars in a bar plot created by Matplotlib:

import matplotlib.pyplot as plt

plt.bar(x=df.category, height=df.amount, width=0.8)

The default value for width is 0.8 but you can increase this value to make the bars wider or decrease this value to make the bars more narrow.

The following example shows how to use this syntax in practice.

Example: Adjust Width of Bars in Matplotlib

Suppose we have the following pandas DataFrame that contains information about the total sales of various products at some grocery store:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'item': ['Apples', 'Oranges', 'Kiwis', 'Bananas', 'Limes'],
                   'sales': [18, 22, 19, 14, 24]})

#view DataFrame
print(df)

      item  sales
0   Apples     18
1  Oranges     22
2    Kiwis     19
3  Bananas     14
4    Limes     24

We can use the following code to create a bar chart to visualize the number of sales of each item:

import matplotlib.pyplot as plt

#create bar chart
plt.bar(x=df.item, height=df.sales)

By default, Matplotlib uses a width of 0.8.

However, we can use the width argument to specify a different value:

import matplotlib.pyplot as plt

#create bar chart with narrow bars
plt.bar(x=df.item, height=df.sales, width=0.4)

matplotlib adjust bar width

Notice that the bars are much more narrow.

Also note that if you use a value of 1 for width, the bars will touch each other:

import matplotlib.pyplot as plt

#create bar chart with width of 1
plt.bar(x=df.item, height=df.sales, width=1, edgecolor='black')

Feel free to adjust the value for the width argument to make the bars in the plot as wide or narrow as you’d like.

The following tutorials explain how to perform other common tasks in Matplotlib:

x