3D Bar Plots in Matplotlib with Python

Three Dimensional Bar Plots 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

Default image
Aman Kharwal

I am a programmer from India, and I am here to guide you with Data Science, Machine Learning, Python, and C++ for free. I hope you will learn a lot in your journey towards Coding, Machine Learning and Artificial Intelligence with me.

Leave a Reply