0
0
Matplotlibdata~5 mins

3D bar charts in Matplotlib

Choose your learning style9 modes available
Introduction

3D bar charts help you see data with three dimensions. They make it easy to compare values across two categories and their heights.

When you want to show sales numbers by product and month.
To compare temperatures across cities and days.
When you need to display survey results by age group and question.
To visualize counts of items by category and location.
Syntax
Matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.bar3d(x, y, z, dx, dy, dz, color='color')

plt.show()

x, y, z are the starting coordinates of each bar.

dx, dy, dz are the width, depth, and height of each bar.

Examples
Two bars at positions (1,3) and (2,4) with heights 5 and 7.
Matplotlib
ax.bar3d([1, 2], [3, 4], [0, 0], [0.5, 0.5], [0.5, 0.5], [5, 7])
Bars with different colors.
Matplotlib
ax.bar3d(x, y, z, dx, dy, dz, color=['red', 'blue'])
Sample Program

This code draws three 3D bars with different heights and colors. It labels each axis for clarity.

Matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Data
x = [1, 2, 3]
y = [1, 2, 3]
z = [0, 0, 0]  # bars start at z=0

# Bar sizes
dx = np.ones(3) * 0.5

dy = np.ones(3) * 0.5

dz = [5, 3, 7]  # heights

ax.bar3d(x, y, z, dx, dy, dz, color=['red', 'green', 'blue'])

ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Height')

plt.show()
OutputSuccess
Important Notes

Make sure to import Axes3D from mpl_toolkits.mplot3d to enable 3D plotting.

Use arrays or lists of the same length for x, y, z, dx, dy, and dz.

You can customize colors to make bars easier to distinguish.

Summary

3D bar charts show data with three dimensions: position and height.

Use ax.bar3d() with starting points and sizes for bars.

Label axes to help others understand your chart.