Rendering
文章来源:https://www.toymoban.com/news/detail-441679.html
效果:文章来源地址https://www.toymoban.com/news/detail-441679.html
- 3D 柱状图
- 按行/列涂颜色
- 柱加阴影、描黑边
- 自定义座标轴名、刻度标签、范围
Code
- 注意
meshgrid
带来的xx
、yy
与acc_flat
之间顺序不匹配的问题,见 [9]。
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()
# 注意顺序问题,见 [9]
# 2022.3.27:这里正常用,要反的**不**是这里,而是后文的 `acc.ravel()` 那里
xx, yy = np.meshgrid(x, y) # 2022.3.27:这里正常用,要反的**不**是这里
# yy, xx = np.meshgrid(x, y) # 2022.3.27:这里**别**反
# print(xx)
# print(yy)
color_list = []
for i in range(len(y)):
c = COLOR[i]
color_list.append([c] * len(x))
color_list = np.asarray(color_list)
# print(color_list)
# 2022.3.27:注意这里 `acc` 在 `ravel()` 之前要转置(`.T`)一下,见 [9]
xx_flat, yy_flat, acc_flat, color_flat = \
xx.ravel(), yy.ravel(), acc.T.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, # 颜色
edgecolor="black", # 黑色描边
shade=True) # 加阴影
# 座标轴名
ax.set_xlabel(r"$\lambda_1$")
ax.set_ylabel(r"$\lambda_2$")
ax.set_zlabel("ACC")
# 座标轴范围
ax.set_zlim((0, 1.01))
# 座标轴刻度标签
# 似乎要 `set_*ticks` 先,再 `set_*ticklabels`
# 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)
# 保存
plt.tight_layout()
fig.savefig("bar3d.png", bbox_inches='tight', pad_inches=0)
plt.close(fig)
References
- Demo of 3D bar charts
- 3D plots as subplots
- matplotlib实现三维柱状图
- 第三十一章 3D 条形图
- Grouped bar chart with labels
- apply color map to mpl_toolkits.mplot3d.Axes3D.bar3d
- List of named colors
- How to make bar3d plot with transparent faces and non-transparent edges?
- numpy meshgrid顺序问题
到了这里,关于matplotlib bar3d画3d柱状图的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!