如何在Jupyter Notebook的3D坐标轴中绘制DataFrame多列直方图?
在Jupyter Notebook中绘制DataFrame的3D分布直方图
下面提供两种可行的实现方案,分别适配静态可视化和交互式可视化需求:
方法一:使用Matplotlib的bar3d(静态3D直方图)
这种方式适合生成静态的3D直方图,核心是统一所有列的直方图区间,避免3D视图错位:
import matplotlib.pyplot as plt import pandas as pd import numpy as np # 替换为你的实际DataFrame df = pd.DataFrame({ 'A': np.random.normal(0, 1, 1000), 'B': np.random.normal(2, 1.5, 1000), 'C': np.random.normal(-1, 0.8, 1000) }) # 统一所有列的直方图区间,保证y轴刻度对齐 all_data = df.values.flatten() bins = np.histogram_bin_edges(all_data, bins='auto') bin_width = bins[1] - bins[0] # 创建3D坐标轴 fig = plt.figure(figsize=(10, 7)) ax = fig.add_subplot(111, projection='3d') # 遍历每一列绘制柱状图 for col_idx, col_name in enumerate(df.columns): counts, _ = np.histogram(df[col_name], bins=bins) # 设置柱子的位置参数 x_pos = np.full(len(counts), col_idx) y_pos = bins[:-1] col_width = 0.8 # 列间间距,避免柱子重叠 bin_depth = bin_width freq_height = counts ax.bar3d(x_pos, y_pos, 0, col_width, bin_depth, freq_height, shade=True) # 设置坐标轴标签和刻度 ax.set_xlabel('Data Columns') ax.set_xticks(range(len(df.columns))) ax.set_xticklabels(df.columns) ax.set_ylabel('Value Range') ax.set_zlabel('Frequency') plt.tight_layout() plt.show()
关键说明:
- 统一
bins是核心:如果各列使用不同的区间,3D视图中y轴会错位,导致柱状图混乱 col_width设为0.8是为了保留列间间隙,提升可读性shade=True添加3D阴影效果,增强视觉层次感
方法二:使用Plotly(交互式3D直方图,适合Jupyter)
Plotly生成的交互式图表支持旋转、缩放,在Jupyter中体验更直观,代码也更简洁:
import plotly.express as px import pandas as pd import numpy as np # 替换为你的实际DataFrame df = pd.DataFrame({ 'A': np.random.normal(0, 1, 1000), 'B': np.random.normal(2, 1.5, 1000), 'C': np.random.normal(-1, 0.8, 1000) }) # 将宽格式DataFrame转为长格式,适配Plotly输入要求 df_long = df.melt(var_name='Column', value_name='Value') # 绘制3D直方图 fig = px.histogram_3d(df_long, x='Column', y='Value', z='Value', histfunc='count', nbins_y=20) # 可手动调整y轴区间数量 # 调整布局和标签 fig.update_layout( scene=dict( xaxis_title='Data Columns', yaxis_title='Value Range', zaxis_title='Frequency' ), height=600, width=800 ) fig.show()
关键说明:
melt方法将每列数据转为行格式,方便Plotly按列分组统计- 生成的图表支持鼠标拖拽旋转、滚轮缩放,可直观查看各列分布的细节差异
内容的提问来源于stack exchange,提问作者Bettabus
相关产品推荐
相关产品推荐

