在完成了3d柱形图的绘制以后,需要增加一个功能:根据柱形图的不同高度,使用不同的颜色,因此想到了使用色带的方法。但是网上看了很多文档,没有现成的“高度--颜色”映射方案,于是打算自己做一个简单的“高度” 转 “颜色“的方案。
参考网址:https://blog.youkuaiyun.com/liuchengzimozigreat/article/details/90477501
1 编程基础
导入必要的库和创建图。
import matplotlib.pyplot as plt
import matplotlib as mpl
fig = plt.figure()
2 创建色带
# 色带,用于为柱形图根据高度取色
cmap = mpl.cm.jet
ax3 = fig.add_axes([0.01, 0.3, 0.02, 0.5]) # 四个参数分别是左、下、宽、长
norm = mpl.colors.Normalize(vmin=0, vmax=100)
cb3 = mpl.colorbar.ColorbarBase(ax3, cmap=cmap,
norm=norm,
spacing='proportional',
orientation='vertical')
3 创建3d坐标
# ax = Axes3D(fig)
ax = fig.add_subplot(111, projection='3d')
4 根据高度获取颜色:ColorbarBase.to_rgba()
for zb in zbs:
high = [1] * len(xs)
cs = [cb3.to_rgba(0)] * len(xs)
for data in zb:
high[data[0]] = (4095 - data[1]) / 4095 * 100
cs[data[0]] = cb3.to_rgba(high[data[0]])
ax.bar(xs, high, zs=t, zdir='y', color=cs, alpha=0.5)
注意:在matplotlib的3.2版本以后,ColorbarBase.to_rgba()被移除了,所以要注意版本。我使用的版本是matplotlib 3.0.2版本。
完整的代码:
def draw_putu(dat_file):
pds = read_pd(dat_file)
zhoubo = 0
zbs = []
zb = list()
for pd in pds:
if pd[0] == 0:
zbs.append(zb)
zb = list()
zhoubo += 1
else:
# 解析一个周波
zb.append(pd)
fig = plt.figure()
# 色带,用于为柱形图根据高度取色
cmap = mpl.cm.jet
ax3 = fig.add_axes([0.01, 0.3, 0.02, 0.5]) # 四个参数分别是左、下、宽、长
norm = mpl.colors.Normalize(vmin=0, vmax=100)
cb3 = mpl.colorbar.ColorbarBase(ax3, cmap=cmap,
norm=norm,
spacing='proportional',
orientation='vertical')
# ax = Axes3D(fig)
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel(u'放电角度')
ax.set_ylabel('T')
ax.set_zlabel('Q%')
xs = [i for i in range(360)]
t = 0
for zb in zbs:
high = [1] * len(xs)
cs = [cb3.to_rgba(0)] * len(xs)
for data in zb:
high[data[0]] = (4095 - data[1]) / 4095 * 100
cs[data[0]] = cb3.to_rgba(high[data[0]])
ax.bar(xs, high, zs=t, zdir='y', color=cs, alpha=0.5)
t += 1
# plt.show()
name = dat_file.split('.')[0]
plt.savefig(name+'.png')
效果图: