python画图|3D直方图基础教程

前述已经完成了直方图和3D图的基本学习,链接如下:

直方图:python画图|水平直方图绘制-CSDN博客

3D图:python画图|水平直方图绘制-CSDN博客

现在我们尝试把二者结合,画3D直方图。

【1】官网教程

首先,依然是来到官网,链接如下;

Demo of 3D bar charts --- Matplotlib 3.9.2 documentation

官网输出了好看的3D直方图,为此,尝试解读代码。

【2】代码解读

首先是引入numpy和matplotlib模块:

复制代码
import matplotlib.pyplot as plt  #引入matplotlib模块画图
import numpy as np #引入numpy模块做数学计算

然后声明了要画3D图:

复制代码
# set up the figure and Axes
fig = plt.figure(figsize=(8, 3)) #定义要画图
ax1 = fig.add_subplot(121, projection='3d') #声明要画3D图,位于左侧
ax2 = fig.add_subplot(122, projection='3d') #声明要画3D图,位于右侧

再之后定义了一组数据备用:

复制代码
# fake data
_x = np.arange(4) #_x取值[0 1 2 3]
_y = np.arange(5) #_x取值[0 1 2 3 4]
_xx, _yy = np.meshgrid(_x, _y) #生成一个_x和_y组成的矩阵
x, y = _xx.ravel(), _yy.ravel() #使用ravel()把_xx和_yy拉成一维数组

这里稍微复杂一些,因此我们先把数据输出。

前半部分,_x = np.arange(4)=[0 1 2 3],_y = np.arange(5)=[0 1 2 3 4],这家可以直接看出来的数据,然后出现了_xx和_yy,再之后它们又被拉平成一位数据赋值给x和y。

在编辑器输入以下代码:

python 复制代码
import matplotlib.pyplot as plt  #引入matplotlib模块画图
import numpy as np #引入numpy模块做数学计算

# set up the figure and Axes
fig = plt.figure(figsize=(8, 3)) #定义要画图
ax1 = fig.add_subplot(121, projection='3d') #声明要画3D图,位于左侧
ax2 = fig.add_subplot(122, projection='3d') #声明要画3D图,位于右侧

# fake data
_x = np.arange(4) #_x取值[0 1 2 3]
_y = np.arange(5) #_x取值[0 1 2 3 4]
_xx, _yy = np.meshgrid(_x, _y) #生成一个_x和_y组成的矩阵
x, y = _xx.ravel(), _yy.ravel() #使用ravel()把_xx和_yy拉成一维数组
print('_x=',_x)
print('_y=',_y)
print('_xx=',_xx)
print('_yy=',_yy)
print('x=',x)
print('y=',y)

输出结果为:

_x= [0 1 2 3]

_y= [0 1 2 3 4]

_xx= [[0 1 2 3]

[0 1 2 3]

[0 1 2 3]

[0 1 2 3]

[0 1 2 3]]

_yy= [[0 0 0 0]

[1 1 1 1]

[2 2 2 2]

[3 3 3 3]

[4 4 4 4]]

x= [0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3]

y= [0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4]

可见meshgrid把_xx和_yy都定义成5X4矩阵,然后又被ravel都拉成一维矩阵。

换一个说法,_x = np.arange(4)=[0 1 2 3],_y = np.arange(5)=[0 1 2 3 4],在_x和_y中任取一个数,按照上下两列的形式排列,出来的结果就是x和y。

继续解读:定义直方图的基本属性

复制代码
top = x + y #定义top=x+y
bottom = np.zeros_like(top) #返回一个一维top列的0矩阵
width = depth = 1 #定义width = depth = 1

定义画图和输出图形:

复制代码
ax1.bar3d(x, y, bottom, width, depth, top, shade=True) #定义画3D图,有阴影
ax1.set_title('Shaded') #设置3D图名字Shaded

ax2.bar3d(x, y, bottom, width, depth, top, shade=False) #定义画3D图,无阴影
ax2.set_title('Not Shaded') #设置3D图名字Not Shaded

plt.show() #输出图形

需要注意的是, bottom其实是方块的底部,bottom = np.zeros_like(top)就是要求下一个方块叠放在上一个方块上。

输出结果为;

++图1++

由图1可见,3D直方图左侧有阴影,右侧没有。

【3】总结

本文学习了3D直方图基本画法。

相关推荐
疑惑的杰瑞6 分钟前
[C语言]连子棋游戏
c语言·开发语言·游戏
wrx繁星点点7 分钟前
创建型模式-单例模式
java·开发语言·单例模式
杨~friendship22 分钟前
Ubuntu上使用qt和opencv显示图像
linux·开发语言·c++·qt·opencv·ubuntu
街 三 仔26 分钟前
【C语言零基础入门篇 - 3】:格式化输入输出、字符操作和sizeof运算符揭秘
c语言·开发语言
喜欢猪猪41 分钟前
TCP/IP网络编程概念及Java实现TCP/IP通讯Demo
开发语言·php
西农小陈1 小时前
python-字符排列问题
数据结构·python·算法
测试19981 小时前
使用Selenium进行网页自动化
自动化测试·软件测试·python·selenium·测试工具·自动化·测试用例
小黄酥1 小时前
Python学习笔记--模块
笔记·python·学习
UvwxyZ6661 小时前
python日志记录与命令行交互
开发语言·python
解孔明1 小时前
IDEA2023.1添加java虚拟机启动参数,打开断言
java·开发语言