Matplotlib PyPlot – Set Different Widths for Bars in Bar Plot

To set different widths for bars in a Bar Plot using Matplotlib PyPlot API, call matplotlib.pyplot.bar() function, and pass required width values as an array for width parameter of bar() function.

The definition of matplotlib.pyplot.bar() function with width parameter’s default value of 0.8 is

bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs):

Set width with a list containing required width values. Usually the width is in the range [0.0, 1.0]

Note: Make sure that the width is either a list with length same as that of x and height, or just a single float value.

Example

In the following program, we will draw a bar plot with bars having different widths.

example.py

import matplotlib.pyplot as plt

#data
x = [1, 2, 3, 4, 5]
h = [10, 8, 12, 4, 7]
w = [0.8, 0.5, 0.2, 0.4, 0.9, 1.0]

#bar plot
plt.bar(x, height = h, width = w)

plt.show()

Output

ADVERTISEMENT
Matplotlib PyPlot -Different Widths for Bars in Bar Plot
Different width values set for bars in Bar Plot

Conclusion

In this Matplotlib Tutorial, we learned how to set different widths for bars in bar plot using Matplotlib PyPlot API.