import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
plt.rcParams['font.sans-serif'] = ['SimSun']
'''
示例数据
'''
读取数据文件
df = pd.read_csv('year.txt', sep="\t", index_col=0)
准备数据
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x_labels = df.columns
y_labels = df.index
x_pos, y_pos = np.meshgrid(np.arange(len(x_labels)), np.arange(len(y_labels)))
x_pos = x_pos.flatten()
y_pos = y_pos.flatten()
z_pos = np.zeros_like(x_pos)
dx = dy = 0.4 # 调整柱子的宽度和深度
dz = df.values.flatten()
颜色映射
norm = plt.Normalize(dz.min(), dz.max())
colors = cm.coolwarm(norm(dz))
ax.bar3d(x_pos, y_pos, z_pos, dx, dy, dz, color=colors, shade=True)
设置X轴和Y轴刻度,使其在柱子中间
ax.set_xticks(np.arange(len(x_labels)) + dx / 2)
ax.set_yticks(np.arange(len(y_labels)) + dy / 2)
ax.set_xticklabels(x_labels)
ax.set_yticklabels(y_labels)
ax.set_xlabel('年龄区间', labelpad=15)
ax.set_ylabel('年龄区间', labelpad=15)
ax.set_zlabel('数量')
启用Y轴网格线
ax.yaxis._axinfo['grid'].update(color='gray', linestyle='-', linewidth=0.5)
调整颜色条的宽度和位置
cbar = plt.colorbar(cm.ScalarMappable(norm=norm, cmap=cm.coolwarm), ax=ax, pad=0.1, shrink=0.5, aspect=20)
cbar.ax.set_ylabel('数量', rotation=270, labelpad=20)
保存图表为PNG文件
plt.savefig('3d_bar_chart.png')
显示图表
plt.show()