Rendering
文章來源:http://www.zghlxwxcb.cn/news/detail-441679.html
效果:文章來源地址http://www.zghlxwxcb.cn/news/detail-441679.html
- 3D 柱狀圖
- 按行/列涂顏色
- 柱加陰影、描黑邊
- 自定義座標(biāo)軸名、刻度標(biāo)簽、范圍
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()` 之前要轉(zhuǎn)置(`.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) # 加陰影
# 座標(biāo)軸名
ax.set_xlabel(r"$\lambda_1$")
ax.set_ylabel(r"$\lambda_2$")
ax.set_zlabel("ACC")
# 座標(biāo)軸范圍
ax.set_zlim((0, 1.01))
# 座標(biāo)軸刻度標(biāo)簽
# 似乎要 `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實現(xiàn)三維柱狀圖
- 第三十一章 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順序問題
到了這里,關(guān)于matplotlib bar3d畫3d柱狀圖的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!