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。

在编辑器输入以下代码:

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直方图基本画法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值