Matplotlib.pyplot 三维绘图的实现示例

折线图

Axes3D.plot(xs,ys,*args,**kwargs)

Argument Description
xs, ys x, y coordinates of vertices
zs z value(s), either one for all points or one for each point.
zdir Which direction to use as z (‘x', ‘y' or ‘z') when plotting a 2D set.
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z ** 2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()

plt.show()

散点图

Axes3D.scatter(xs,ys,zs=0,zdir='z',s=20,c=None,depthshade=True,*args,**kwargs)

Argument Description
xs, ys Positions of data points.
zs Either an array of the same length as xs and ys or a single value to place all points in the same plane. Default is 0.
zdir Which direction to use as z (‘x', ‘y' or ‘z') when plotting a 2D set.
s Size in points^2. It is a scalar or an array of the same length as x and y.
c A color. c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. c can be a 2-D array in which the rows are RGB or RGBA, however, including the case of a single row to specify the same color for all points.
depthshade Whether or not to shade the scatter markers to give the appearance of depth. Default is True.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

def randrange(n, vmin, vmax):
  '''
  Helper function to make an array of random numbers having shape (n, )
  with each number distributed Uniform(vmin, vmax).
  '''
  return (vmax - vmin) * np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
  xs = randrange(n, 23, 32)
  ys = randrange(n, 0, 100)
  zs = randrange(n, zlow, zhigh)
  ax.scatter(xs, ys, zs, c=c, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

线框图

Axes3D.plot_wireframe(X,Y,Z,*args,**kwargs)

Argument Description
X, Y, Data values as 2D arrays
Z  
rstride Array row stride (step size), defaults to 1
cstride Array column stride (step size), defaults to 1
rcount Use at most this many rows, defaults to 50
ccount Use at most this many columns, defaults to 50
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Grab some test data.
X, Y, Z = axes3d.get_test_data(0.05)

# Plot a basic wireframe.
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()

表面图

Axes3D.plot_surface(X,Y,Z,*args,**kwargs)

Argument Description
X, Y, Z Data values as 2D arrays
rstride Array row stride (step size)
cstride Array column stride (step size)
rcount Use at most this many rows, defaults to 50
ccount Use at most this many columns, defaults to 50
color Color of the surface patches
cmap A colormap for the surface patches.
facecolors Face colors for the individual patches
norm An instance of Normalize to map values to colors
vmin Minimum value to map
vmax Maximum value to map
shade Whether to shade the facecolors
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
            linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

柱状图

Axes3D.bar(left,height,zs=0,zdir='z',*args,**kwargs)

Argument Description
left The x coordinates of the left sides of the bars.
height The height of the bars.
zs Z coordinate of bars, if one value is specified they will all be placed at the same z.
zdir Which direction to use as z (‘x', ‘y' or ‘z') when plotting a 2D set.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
  xs = np.arange(20)
  ys = np.random.rand(20)

  # You can provide either a single color or an array. To demonstrate this,
  # the first bar of each set will be colored cyan.
  cs = [c] * len(xs)
  cs[0] = 'c'
  ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

箭头图

Axes3D.quiver(*args,**kwargs)

Arguments:

X, Y, Z:
The x, y and z coordinates of the arrow locations (default is tail of arrow; see pivot kwarg)
U, V, W:
The x, y and z components of the arrow vectors

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make the grid
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
           np.arange(-0.8, 1, 0.2),
           np.arange(-0.8, 1, 0.8))

# Make the direction data for the arrows
u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *
   np.sin(np.pi * z))

ax.quiver(x, y, z, u, v, w, length=0.1, normalize=True)

plt.show()

2D转3D图

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')

# Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x,y)')

# Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = ('r', 'g', 'b', 'k')
x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
labels = np.random.randint(3, size=80)

# By using zdir='y', the y value of these points is fixed to the zs value 0
# and the (x,y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=labels, label='points in (x,z)')

# Make legend, set axes limits and labels
ax.legend()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# Customize the view angle so it's easier to see that the scatter points lie
# on the plane y=0
ax.view_init(elev=20., azim=-35)

plt.show()

文本图

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')

# Demo 1: zdir
zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1))
xs = (1, 4, 4, 9, 4, 1)
ys = (2, 5, 8, 10, 1, 2)
zs = (10, 3, 8, 9, 1, 8)

for zdir, x, y, z in zip(zdirs, xs, ys, zs):
  label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir)
  ax.text(x, y, z, label, zdir)

# Demo 2: color
ax.text(9, 0, 0, "red", color='red')

# Demo 3: text2D
# Placement 0, 0 would be the bottom left, 1, 1 would be the top right.
ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes)

# Tweaking display region and labels
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()

3D拼图

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data
from matplotlib import cm
import numpy as np

# set up a figure twice as wide as it is tall
fig = plt.figure(figsize=plt.figaspect(0.5))

# ===============
# First subplot
# ===============
# set up the axes for the first plot
ax = fig.add_subplot(1, 2, 1, projection='3d')

# plot a 3D surface like in the example mplot3d/surface3d_demo
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
            linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
fig.colorbar(surf, shrink=0.5, aspect=10)

# ===============
# Second subplot
# ===============
# set up the axes for the second plot
ax = fig.add_subplot(1, 2, 2, projection='3d')

# plot a 3D wireframe like in the example mplot3d/wire3d_demo
X, Y, Z = get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()

到此这篇关于Matplotlib.pyplot 三维绘图的实现示例的文章就介绍到这了,更多相关Matplotlib.pyplot 三维绘图内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python的地形三维可视化Matplotlib和gdal使用实例

    我是以Python开门的,我还是觉得Python也可以进行地形三维可视化,当然这里需要借助第三方库,so,我就来介绍:Python一个很重要可视化插件,Matplotlib. Matplotlib是Python最著名的绘图库,它提供了一整套友好的命令,十分适合交互式地进行制图.而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中.你会发现Matplotlib和matlab相似,但是你知道matlab强大是很强大,但是安装包就有7G,一下就让我失去玩弄他的兴趣. Matplotlib的二维图形非

  • Python使用matplotlib绘制三维图形示例

    本文实例讲述了Python使用matplotlib绘制三维图形.分享给大家供大家参考,具体如下: 用二维泡泡图表示三维数据 泡泡的坐标2维,泡泡的大小三维,使用到的函数 plt.scatter(P[:,0], P[:,1], s=S, lw = 1.5, edgecolors = C, facecolors='None') 其中P[:,0], P[:,1]为泡泡的坐标数据,s为泡泡的大小,lw为泡泡的边线宽度,edgecolors为边线颜色,facecolors为填充颜色 代码及注释 # -*-

  • Matplotlib绘制雷达图和三维图的示例代码

    1.雷达图 程序示例 '''1.空白极坐标图''' import matplotlib.pyplot as plt plt.polar() plt.show() '''2.绘制一个极坐标点''' import numpy as np import matplotlib.pyplot as plt # 极坐标(0.25*pi,20) plt.polar(0.25*np.pi, 20, 'ro', lw=2) # 'ro'红色圆点 plt.ylim(0,50) plt.show() '''3.绘制多

  • Python使用matplotlib绘制三维参数曲线操作示例

    本文实例讲述了Python使用matplotlib绘制三维参数曲线操作.分享给大家供大家参考,具体如下: 一 代码 import matplotlib as mpl from mpl_toolkits.mplot3d importAxes3D import numpy as np import matplotlib.pyplot as plt mpl.rcParams['legend.fontsize']=10#图例字号 fig = plt.figure() ax = fig.gca(proje

  • Python基于matplotlib实现绘制三维图形功能示例

    本文实例讲述了Python基于matplotlib实现绘制三维图形功能.分享给大家供大家参考,具体如下: 代码一: # coding=utf-8 import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d x,y = np.mgrid[-2:2:20j,-2:2:20j] #测试数据 z=x*np.exp(-x**2-y**2) #三维图形 ax = plt.subplot(111, project

  • Python Matplotlib实现三维数据的散点图绘制

    一.背景 近期项目即将开展,计划第一步就是实现数据的可视化,所以先学习一下数据展示相关Demo.选用Python2.7与Matplotlib来实现,平台采用Pycharm,值得一提的是,Matplotlib的安装前首先要安装Numpy包,但是在完成Numpy的安装之后,楼主不能在PyCharm平台下进行自动安装,或者CMD中使用类似pip install Matplotlib,参考网上解决方案后采用直接去官网下载相应的安装包直接运行安装到相关目录下.在此就不赘述了. 二. 参考 Python语言

  • Matplotlib.pyplot 三维绘图的实现示例

    折线图 Axes3D.plot(xs,ys,*args,**kwargs) Argument Description xs, ys x, y coordinates of vertices zs z value(s), either one for all points or one for each point. zdir Which direction to use as z ('x', 'y' or 'z') when plotting a 2D set. import matplotli

  • 使用matplotlib的pyplot模块绘图的实现示例

    1. 绘制简单图形 使用 matplotlib 的pyplot模块绘制图形.看一个 绘制sin函数曲线的例子. import matplotlib.pyplot as plt import numpy as np # 生成数据 x = np.arange(0, 6, 0.1) # 以0.1为单位,生成0到 6 的数据* y = np.sin(x) # 绘制图形 plt.plot(x,y) plt.show() 这里使用NumPy的arange()方法生成了[0, 0.1, 0.2, - , 5.

  • 如何用Matplotlib 画三维图的示例代码

    用Matplotlib画三维图 最基本的三维图是由(x, y, z)三维坐标点构成的线图与散点图,可以用ax.plot3D和ax.scatter3D函数来创建,默认情况下,散点会自动改变透明度,以在平面上呈现出立体感 三维的线图和散点图 #绘制三角螺旋线 from mpl_toolkits import mplot3d %matplotlib inline import matplotlib.pyplot as plt import numpy as np ax = plt.axes(proje

  • PyQt5结合matplotlib绘图的实现示例

    参考网上的例子,实现了简单的matplotlib pyqt5绘图 相关知识点:  (1)pyqt5中添加控件要在布局中添加  (2)布局可以使用replaceWidget替换控件  (3)信号与槽机制 timer = QtCore.QTimer(self) timer.timeout.connect(self.update_figure) self.btnPlot.clicked.connect(self.plotButton_callback) 实现的效果 import sys from Py

  • Python三维绘图之Matplotlib库的使用方法

    前言 在遇到三维数据时,三维图像能给我们对数据带来更加深入地理解.python的matplotlib库就包含了丰富的三维绘图工具. 1.创建三维坐标轴对象Axes3D 创建Axes3D主要有两种方式,一种是利用关键字projection='3d'l来实现,另一种则是通过从mpl_toolkits.mplot3d导入对象Axes3D来实现,目的都是生成具有三维格式的对象Axes3D. #方法一,利用关键字 from matplotlib import pyplot as plt from mpl_

  • python matplotlib绘制三维图的示例

    作者:catmelo 本文版权归作者所有 链接:https://www.cnblogs.com/catmelo/p/4162101.html 本文参考官方文档:http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html 起步 新建一个matplotlib.figure.Figure对象,然后向其添加一个Axes3D类型的axes对象. 其中Axes3D对象的创建,类似其他axes对象,只不过使用projection='3d'关键词. impo

  • Python数据可视化之matplotlib.pyplot绘图的基本参数详解

    目录 1.matplotlib简介 2.图形组成元素的函数用法 2.1. figure():背景颜色 2.2 xlim()和 ylim():设置 x,y 轴的数值显示范围 2.3 xlabel()和 ylabel():设置 x,y 轴的标签文本 2.4 grid():绘制刻度线的网格线 2.5 axhline():绘制平行于 x 轴额度水平参考线 2.6 axvspan():绘制垂直于 x 轴的参考区域 2.7 xticks(),yticks() 2.8 annotate():添加图形内容细节的

  • Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度

    前言 matplotlib.pyplot是一些命令行风格函数的集合,使matplotlib以类似于MATLAB的方式工作.每个pyplot函数对一幅图片(figure)做一些改动:比如创建新图片,在图片创建一个新的作图区域(plotting area),在一个作图区域内画直线,给图添加标签(label)等.matplotlib.pyplot是有状态的,亦即它会保存当前图片和作图区域的状态,新的作图函数会作用在当前图片的状态基础之上. 在开始本文之前,不熟悉的朋友可以先看看这篇文章:Python

随机推荐