Plot Multiple Bars in Python with Matplotlib

In this tutorial, we will learn how to plot multiple bars with Python matplotlib. To plot multiple bars with Python matplotlib, we can call bar to multiple times.

Code Example:

import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime

x = [
    datetime.datetime(2021, 1, 4, 0, 0),
    datetime.datetime(2021, 1, 5, 0, 0),
    datetime.datetime(2021, 1, 6, 0, 0)
]
x = date2num(x)

y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()

plt.show()
  • To create the x list with some dates.
  • Then we call date2num with x to convert the dates to values that can be plotted.
  • Next, we create a subplot with subplot.
  • And we call ax.bar to plot the bars with diffent x and y values.
  • We also set the color of the bars to different colors and change the alignment of them by setting align.

#python 

1.30 GEEK