Categories
Python Answers

How to plot multiple bars with Python matplotlib?

Spread the love

Sometimes, we want to plot multiple bars with Python matplotlib.

In this article, we’ll look at how to plot multiple bars with Python matplotlib.

How to plot multiple bars with Python matplotlib?

To plot multiple bars with Python matplotlib, we can call bar to multiple times.

For instance, we write

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.

And we call xaxis_date to render the x-axis labels as dates.,

Conclusion

To plot multiple bars with Python matplotlib, we can call bar to multiple times.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *