You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何删除matplotlib 3D柱状图底部平面及解决同高度色块深浅不一问题

matplotlib 3D柱状图问题解答

现有可复现问题的代码如下:

import numpy as np
import matplotlib.pyplot as plt


# setup the figure and axes
fig = plt.figure(figsize=(8, 8))
ax = plt.axes(projection='3d')

# fake data
_x = np.arange(10)
_y = np.arange(10)
_xx, _yy = np.meshgrid(_x, _y)
x, y = _xx.ravel(), _yy.ravel()

top = np.zeros(shape=100)
top[0] = 10
    
bottom = np.zeros(shape=100)
width = depth = 1


ax.bar3d(x, y, bottom, width, depth, top, shade=True)
plt.show()

代码运行后效果:
3D柱状图效果


问题1:删除3D柱状图的底部平面

原因说明

出现的底部平面是top值为0的柱体:这些柱体高度为0,渲染后会变成贴在z=0平面的色块,拼接后就形成了完整的底部平面。

解决方法

过滤掉高度为0的柱体,只绘制有高度的部分即可,修改bar3d的传参部分代码:

# 过滤所有高度大于0的柱体数据
mask = top > 0
x_filter = x[mask]
y_filter = y[mask]
top_filter = top[mask]
bottom_filter = bottom[mask]

# 仅绘制过滤后的柱体
ax.bar3d(x_filter, y_filter, bottom_filter, width, depth, top_filter, shade=True)

问题2:同高度柱体色块深浅不一的原因及解决方法

产生原因

该现象由bar3d的shade=True参数导致:开启阴影渲染后,matplotlib会模拟3D空间的光照效果,不同位置的柱体、同一柱体的不同面因为和虚拟光源的夹角不同,着色时会自动叠加明暗效果,最终出现同高度色块深浅不一的情况。

解决方法

  • 不需要阴影效果的场景:直接关闭shade参数即可实现颜色完全统一
    ax.bar3d(x, y, bottom, width, depth, top, shade=False)
    
  • 需要保留阴影的场景:手动为所有同高度柱体设置相同的facecolor,即可保证同高度颜色统一
    # 为所有柱体设置统一的蓝色,可按需替换为其他色值
    colors = ['#1f77b4'] * len(top)
    ax.bar3d(x, y, bottom, width, depth, top, shade=True, color=colors)
    

内容的提问来源于stack exchange,提问作者Federico Vega

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:15:06