九个例子玩转Matplotlib.pyplot 三维绘图

折线图

Axes3D.plot(xsys*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(xsyszs=0zdir=‘z‘s=20c=Nonedepthshade=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(XYZ*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(XYZ*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(leftheightzs=0zdir=‘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:

XYZ:
The x, y and z coordinates of the arrow locations (default is tail of arrow; see pivot kwarg)
UVW:
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()

原文地址:https://www.cnblogs.com/wuwen19940508/p/8638266.html

时间: 2024-11-06 09:48:35

九个例子玩转Matplotlib.pyplot 三维绘图的相关文章

【python】matplotlib.pyplot入门

matplotlib.pyplot介绍 matplotlib的pyplot子库提供了和matlab类似的绘图API,方便用户快速绘制2D图表. matplotlib.pyplot是命令行式函数的集合,每一个函数都对图像作了修改,比如创建图形,在图像上创建画图区域,在画图区域上画线,在线上标注等. 下面简单介绍一下pyplot的基本使用: (1)使用plot()函数画图 plot()为画线函数,下面的小例子给ploy()一个列表数据[1,2,3,4],matplotlib假设它是y轴的数值序列,然

Python使用matplotlib绘制三维曲线

本文主要演示如何使用matplotlib绘制三维图形 代码如下: # -*- coding: UTF-8 -*- 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() # 设置三维图形模式 a

matplotlib 画图 三维图

#绘制三维图 import numpy as np import mpl_toolkits.mplot3d import matplotlib.pyplot as plt x,y=np.mgrid[-2:2:20j,-2:2:20j] z=x*np.exp(-x**2-y**2) ax=plt.subplot(111,projection='3d') ax.plot_surface(x,y,z,rstride=2,cstride=1,cmap=plt.cm.Blues_r) ax.set_xla

matplotlib.pyplot画图笔记

一.简单示例 1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 x = np.arange(3,8,1) #x轴数据 5 y1 = x*2 6 y2 = x**2 7 plt.figure(figsize=(5,3.5)) 8 plt.plot(x, y1,'r',marker='o',label='y1:double x') #关键句,前两个参数是X.Y轴数据,其他参数指定曲线属性,如标签label,颜色color,线宽lin

matplotlib.pyplot的使用

有时我们在进行可视化的时候需要用箭头来指出某个点表示的特别的含义.这里给出一个例子来记录一下. 1 import numpy as np 2 import matplotlib.pyplot as plt 3 4 x = np.linspace(-3,3,100) 5 y = x**2 6 7 x_l = [-3,-2] 8 y_l = [9,4] 9 position_text = {'qwe':(-3,-9),'rty':(-2,4)} # 定义的是箭头初始的位置和箭头需要指示的内容 10

Matplotlib.pyplot 常用方法

1.介绍 Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形.通过 Matplotlib,开发者可以仅需要几行代码,便可以生成绘图, 直方图,功率谱,条形图,错误图,散点图等. 2.Matplotlib基础知识 2.1.Matplotlib中的基本图表包括的元素 x轴和y轴 水平和垂直的轴线 x轴和y轴刻度 刻度标示坐标轴的分隔,包括最小刻度和最大刻度 x轴和y轴刻度标签 表示特定坐标轴的值 绘图区域 实际绘图的区域 2.2.

Python中用matplotlib.pyplot画图总结

1. import numpy as np import matplotlib.pyplot as plt def f1(t):     #根据横坐标t,定义第一条曲线的纵坐标     return np.exp(-t)*np.cos(2*np.pi*t) def f2(t):     #根据横坐标t,定义第二条曲线的纵坐标     return np.sin(2*np.pi*t)*np.cos(3*np.pi*t) #定义很坐标的值,来自于np.arange(0.0,5.0,0.02), #.

matplotlib.pyplot import报错: ValueError: _getfullpathname: embedded null character in path

Environment: Windows 10, Anaconda 3.6 matplotlib 2.0 import matplotlib.pyplot 报错: ValueError: _getfullpathname: embedded null character in path 原因以及Solution: http://stackoverflow.com/questions/34004063/error-on-import-matplotlib-pyplot-on-anaconda3-f

matplotlib.pyplot 中很好看的一种style

""" This example demonstrates the "ggplot" style, which adjusts the style to emulate ggplot_ (a popular plotting package for R_). These settings were shamelessly stolen from [1]_ (with permission). .. [1] http://www.huyng.com/post