Python matplotlib与numpy实现多平面二维条形图绘制

青禾
青禾
发布时间:2026-10-13| 2人浏览过
原创

本文介绍如何使用Python的matplotlib和numpy库,在三维坐标系中将二维条形图投射到不同的Y平面(如y=0, y=1等)。通过示例代码展示如何生成随机数据、设置颜色与透明度,并正确配置坐标轴标签,实现多平面条形图的可视化效果。

本文演示如何在不同的平面上绘制二维条形图。

该实例构建了一个三维图形,其中包含投射到平面y=0、y=1等位置的二维条形图。

演示结果如下:

完整代码见下文。

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

colors = ['r', 'g', 'b', 'y']
yticks = [3, 2, 1, 0]
for c, k in zip(colors, yticks):
  # Generate the random data for the y=k 'layer'.
  xs = np.arange(20)
  ys = np.random.rand(20)

  # You can provide either a single color or an array with the same length as
  # xs and ys. To demonstrate this, we color the first bar of each set cyan.
  cs = [c] * len(xs)
  cs[0] = 'c'

  # Plot the bar graph given by xs and ys on the plane y=k with 80% opacity.
  ax.bar(xs, ys, zs=k, zdir='y', color=cs, alpha=0.8)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# On the y axis let's only label the discrete values that we have data for.
ax.set_yticks(yticks)

plt.show()

脚本运行耗时:(0分0.063秒)

总结

以上是关于使用Python、matplotlib和numpy在不同平面绘制二维条形图的完整内容,希望能对大家有所帮助。感兴趣的朋友可继续查阅本站其他相关专题,如有疏漏欢迎留言指正。感谢各位对本站的支持!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。