matplotlib bar3d plot 3d histogram

created at 08-05-2021 views: 29

expect

  • 3D histogram
  • Color by row/column
  • Post shadow, stroke black border
  • Custom axis name, scale label, range

matplotlib 3D histogram

Note the order problem caused by meshgrid, (reference).

code

import numpy as np
import matplotlib
matplotlib.rcParams['font.family'] = 'Times New Roman'
matplotlib.rcParams['mathtext.default'] = 'regular'
import matplotlib.pyplot as plt
# from mpl_toolkits.mplot3d import Axes3D


COLOR = ["blue", "cornflowerblue", "mediumturquoise", "goldenrod", "yellow"]
lambda1 = lambda2 = [10 ** x for x in range(-2, 3)]


# x, y: position
x = list(range(len(lambda1)))
y = list(range(len(lambda2)))
x_tickets = [str(_x) for _x in lambda1]
y_tickets = [str(_x) for _x in lambda2]

# acc = np.random.rand(len(x), len(y))
acc = np.arange(len(x) * len(y)).reshape(len(x), len(y)) + 1
acc = acc / acc.max()

# xx, yy = np.meshgrid(x, y)  # So the two axes will be reversed
yy, xx = np.meshgrid(x, y)  # To be reversed

# print(xx)
# print(yy)
color_list = []
for i in range(len(x)):
    c = COLOR[i]
    color_list.append([c] * len(y))
color_list = np.asarray(color_list)
# print(color_list)
xx_flat, yy_flat, acc_flat, color_flat = \
    xx.ravel(), yy.ravel(), acc.ravel(), color_list.ravel()
# print(xx_flat)
# print(yy_flat)


# fig, ax = plt.subplots(projection="3d")
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.bar3d(xx_flat - 0.35, yy_flat - 0.35, 0, 0.7, 0.7, acc_flat,
    color=color_flat,  # colour
    edgecolor="black",  
    shade=True) # Add shadow

# Coordinate axis name
ax.set_xlabel(r"$\lambda_1$")
ax.set_ylabel(r"$\lambda_2$")
ax.set_zlabel("ACC")

# Coordinate axis range
ax.set_zlim((0, 1.01))

# Axis scale label

# has to call `set_*ticks` to mount `ticklabels` to corresponding `ticks` ?
ax.set_xticks(x)
ax.set_xticklabels(x_tickets)
ax.set_yticks(y)
ax.set_yticklabels(y_tickets)

# save
plt.tight_layout()
fig.savefig("bar3d.png", bbox_inches='tight', pad_inches=0)
plt.close(fig)
created at:08-05-2021
edited at: 08-05-2021: