python数据分析 | Matplotlib3D绘图

1 导入模块

from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
%matplotlib notebook # 在notebook展示和旋转图片

2 3D曲线图

# 将 0-15 分为 1000份
zline = np.linspace(0,15,1000)
xline = np.sin(zline)
yline = np.cos(zline)
# 创建3D画布
fig = plt.figure()
ax = Axes3D(fig)

# 绘制图形
ax.plot(xline,yline,zline)
plt.show()

在这里插入图片描述

3 散点图

x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x,y,z,color="b")
plt.show()

在这里插入图片描述

4 平面图

# 构建数据
x = [1,2,3,4]
y = [1,2,3,4]

X,Y = np.meshgrid(x,y)  # x --> 行的延申(复制), y --> 列的延申(复制)
print(X)
print(Y)
"""
结果:
[[1 2 3 4]
 [1 2 3 4]
 [1 2 3 4]
 [1 2 3 4]]
[[1 1 1 1]
 [2 2 2 2]
 [3 3 3 3]
 [4 4 4 4]]
"""
fig = plt.figure()
ax = Axes3D(fig)

# 绘制平面  z=3
ax.plot_surface(X,Y,Z=X*0+4) # 平面放置在z=4的位置上 平面的函数时z = X*0 + 4

# 设置x,y,z标签
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")

plt.show()

在这里插入图片描述

5 曲面图

# 构建数据
x = np.arange(-2,2,0.1)
y = np.arange(-2,2,0.1)
print(x)
print(y)

# 延申,构造平面
X,Y = np.meshgrid(x,y)
print(X)
print(Y)
# 定义构造曲面的函数,即z
def fun(x,y):
#     return x**2
    return x**2 + y**2
fig = plt.figure()
ax = Axes3D(fig)

# 绘制曲面 
ax.plot_surface(X,Y,fun(X,Y),rstride=1,cstride=1) # 平面放置在z=4的位置上
plt.show()

在这里插入图片描述
这个图,本人觉得很好看。
学习来自使用matplotlib绘制3D函数图像

import matplotlib.pyplot as plt  # 绘图用的模块
from mpl_toolkits.mplot3d import Axes3D  # 绘制3D坐标的函数
import numpy as np


def fun(x, y):
    return np.power(x, 2) + np.power(y, 2)


fig1 = plt.figure()  # 创建一个绘图对象
ax = Axes3D(fig1)  # 用这个绘图对象创建一个Axes对象(有3D坐标)
X, Y = np.mgrid[-2:2:40j, -2:2:40j]  # 从-2到2分别生成40个取样坐标,并作满射联合
Z = fun(X, Y)  # 用取样点横纵坐标去求取样点Z坐标
plt.title("This is main title")  # 总标题
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.coolwarm, alpha=0.5)  # 用取样点(x,y,z)去构建曲面
ax.set_xlabel('x label', color='r')
ax.set_ylabel('y label', color='g')
ax.set_zlabel('z label', color='b')  # 给三个坐标轴注明
plt.show()  # 显示模块中的所有绘图对象

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值