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

相关推荐
不想写bug呀2 小时前
多线程案例——单例模式
java·开发语言·单例模式
我不会写代码njdjnssj2 小时前
网络编程 TCP UDP
java·开发语言·jvm
费弗里3 小时前
Python全栈应用开发利器Dash 3.x新版本介绍(1)
python·dash
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
就叫飞六吧9 天前
基于keepalived、vip实现高可用nginx (centos)
python·nginx·centos
Vertira9 天前
PyTorch中的permute, transpose, view, reshape和flatten函数详解(已解决)
人工智能·pytorch·python
学Linux的语莫9 天前
python基础语法
开发语言·python
匿名的魔术师9 天前
实验问题记录:PyTorch Tensor 也会出现 a = b 赋值后,修改 a 会影响 b 的情况
人工智能·pytorch·python
Ven%9 天前
PyTorch 张量(Tensors)全面指南:从基础到实战
人工智能·pytorch·python