3D Bar Plots in Matplotlib with Python

In this Python tutorial I will show you how to create 3D Bar Plots with Python using Matplotlib.

3D Bar Plot allows us to compare the relationship of three variables rather than just two. 3D bar charts with matplotlib are slightly more complex than your scatter plots, because the bars have 1 more characteristic, depth.

Basically, the “thickness” of the bars is also define-able. For most, this will be simply a pre-determined set of data, but you can actually use this for one more “dimension” to your plot.

Let’s create 3D Bar plots

# Import the libraries
import numpy as np
from matplotlib import cm
import matplotlib.colors as col
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
alpha = 1. / np.linspace(1, 8, 5)
t = np.linspace(0, 5, 16)
T, A = np.meshgrid(t, alpha)
data = np.exp(-T * A)

fig = plt.figure()
ax = fig.gca(projection='3d')
cmap = cm.ScalarMappable(col.Normalize(0, len(alpha)),cm.gray)
for i, row in enumerate(data):
    ax.bar(4 * t, row, zs=i, zdir='y', alpha=0.8, color=cmap.to_rgba(i))
plt.show()
alpha = np.linspace(1, 8, 5)
t = np.linspace(0, 5, 16)
T, A = np.meshgrid(t, alpha)
data = np.exp(-T * (1. / A))

fig = plt.figure()
ax = fig.gca(projection='3d')
x1 = T.flatten()
y1 = A.flatten()
z1 = np.zeros(data.size)
dx = .40 * np.ones(data.size)
dy = .40 * np.ones(data.size)
dz = data.flatten()

ax.set_xlabel('T')
ax.set_ylabel('Alpha')
ax.bar3d(x1, y1,z1, dx, dy, dz, color='red')
plt.show()

Follow us on Instagram for all your Queries

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1498

Leave a Reply