Matplotlib 3D Bar Chart

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create a 3D bar chart using Python Matplotlib. We will use fake data to plot the chart with and without shading.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import Libraries and Set Up Figure

In the first step, we will import the necessary libraries and set up the figure and axes for the chart.

import matplotlib.pyplot as plt
import numpy as np

## set up the figure and axes
fig = plt.figure(figsize=(8, 3))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122, projection='3d')

Create Fake Data

In the second step, we will create fake data to use for the chart.

## fake data
_x = np.arange(4)
_y = np.arange(5)
_xx, _yy = np.meshgrid(_x, _y)
x, y = _xx.ravel(), _yy.ravel()

top = x + y
bottom = np.zeros_like(top)
width = depth = 1

Plot the Chart with Shading

In the third step, we will plot the 3D bar chart with shading.

ax1.bar3d(x, y, bottom, width, depth, top, shade=True)
ax1.set_title('Shaded')

Plot the Chart without Shading

In the fourth step, we will plot the 3D bar chart without shading.

ax2.bar3d(x, y, bottom, width, depth, top, shade=False)
ax2.set_title('Not Shaded')

Display the Chart

In the final step, we will display the chart.

plt.show()

Summary

In this lab, we learned how to create a 3D bar chart using Python Matplotlib. We used fake data to plot the chart with and without shading. We imported the necessary libraries, set up the figure and axes, created fake data, plotted the chart with and without shading, and then displayed the chart.

Other Python Tutorials you may like