matplotlib画三维散点图和曲面图

您所在的位置:网站首页 python画三维曲面 matplotlib画三维散点图和曲面图

matplotlib画三维散点图和曲面图

2023-08-29 04:13| 来源: 网络整理| 查看: 265

本篇博文主要来介绍如何利用matplotlib库画三维散点图和曲面图。

三维散点图

numpy的random.rand(d0,d1,d2…)函数根据维度生成服从0~1均匀分布的随机样本点; x、y、z均为一维数组

# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np def randrange(n, vmin, vmax): return (vmax - vmin)*np.random.rand(n) fig = plt.figure() ax = fig.add_subplot(projection="3d") n = 100 x = randrange(n,0,20) y = randrange(n,0,20) z = randrange(n,-30,-5) ax.scatter(x,y,z,marker="^") ax.set_xlabel("X Label") ax.set_ylabel("Y Label") ax.set_zlabel("Z Label") ax.set_title("3D scatter plot") plt.show()

在这里插入图片描述

3D曲面图

在这里需要先利用numpy的meshgrid()函数生成x和y网格点坐标(x,y),也就是说把两个数组的笛卡尔积内的元素的第一二个坐标分别放入两个矩阵中。画曲面图时,z必须是二维的。

import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(projection="3d") x = np.arange(-5,5,0.5) y = np.arange(-5,5,0.5) x,y = np.meshgrid(x, y) z = np.sqrt(x**2 + y**2) ax.plot_surface(x,y,z) ax.set_xlabel("X Label") ax.set_ylabel("Y Label") ax.set_zlabel("Z Label") ax.set_title("3D surface plot") plt.show()

在这里插入图片描述 在画曲面图的时候,我们还可以给图像加上颜色和colorbar

import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(projection="3d") x = np.arange(-5,5,0.5) y = np.arange(-5,5,0.5) x,y = np.meshgrid(x, y) z = np.sqrt(x**2 + y**2) #rstride表示行步长,cmap给曲面加上色彩 surf = ax.plot_surface(x,y,z,rstride=1,cstride=1,cmap=plt.cm.viridis) #colorbar可以给图像添加一个颜色条 fig.colorbar(surf) ax.set_xlabel("X Label") ax.set_ylabel("Y Label") ax.set_zlabel("Z Label") ax.set_title("3D surface plot") plt.show()

在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3