最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python繪制三維圖的詳細新手教程

 更新時間:2022年08月30日 10:19:41   作者:桂。  
通常我們用 Python 繪制的都是二維平面圖,但有時也需要繪制三維場景圖,下面這篇文章主要給大家介紹了關(guān)于python繪制三維圖的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下

本文僅僅梳理最基本的繪圖方法。

一、初始化

假設(shè)已經(jīng)安裝了matplotlib工具包。

利用matplotlib.figure.Figure創(chuàng)建一個圖框:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

二、直線繪制(Line plots)

基本用法:

ax.plot(x,y,z,label=' ')

code:

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()

三、散點繪制(Scatter plots)

基本用法:

ax.scatter(xs, ys, zs, s=20, c=None, depthshade=True, *args, *kwargs)
  • xs,ys,zs:輸入數(shù)據(jù);
  • s:scatter點的尺寸
  • c:顏色,如c = 'r'就是紅色;
  • depthshase:透明化,True為透明,默認為True,F(xiàn)alse為不透明
  • *args等為擴展變量,如maker = 'o',則scatter結(jié)果為’o‘的形狀

code:

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()

四、線框圖(Wireframe plots)

基本用法:

ax.plot_wireframe(X, Y, Z, *args, **kwargs)
  • X,Y,Z:輸入數(shù)據(jù)
  • rstride:行步長
  • cstride:列步長
  • rcount:行數(shù)上限
  • ccount:列數(shù)上限

code:

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()

五、表面圖(Surface plots)

基本用法:

ax.plot_surface(X, Y, Z, *args, **kwargs)
  • X,Y,Z:數(shù)據(jù)
  • rstride、cstride、rcount、ccount:同Wireframe plots定義
  • color:表面顏色
  • cmap:圖層

code:

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()

六、三角表面圖(Tri-Surface plots)

基本用法:

ax.plot_trisurf(*args, **kwargs)
  • X,Y,Z:數(shù)據(jù)
  • 其他參數(shù)類似surface-plot

code:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
 
 
n_radii = 8
n_angles = 36
 
# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).
radii = np.linspace(0.125, 1.0, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
 
# Repeat all angles for each radius.
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
 
# Convert polar (radii, angles) coords to cartesian (x, y) coords.
# (0, 0) is manually added at this stage,  so there will be no duplicate
# points in the (x, y) plane.
x = np.append(0, (radii*np.cos(angles)).flatten())
y = np.append(0, (radii*np.sin(angles)).flatten())
 
# Compute z to make the pringle surface.
z = np.sin(-x*y)
 
fig = plt.figure()
ax = fig.gca(projection='3d')
 
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)
 
plt.show()

七、等高線(Contour plots)

基本用法:

ax.contour(X, Y, Z, *args, **kwargs)

code:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
 
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, cmap=cm.coolwarm)
ax.clabel(cset, fontsize=9, inline=1)
 
plt.show()

二維的等高線,同樣可以配合三維表面圖一起繪制:

code:

from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
 
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
 
ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)
 
plt.show()

也可以是三維等高線在二維平面的投影:

code:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
 
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
 
ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)
 
plt.show()

八、Bar plots(條形圖)

基本用法:

ax.bar(left, height, zs=0, zdir='z', *args, **kwargs
  • x,y,zs = z,數(shù)據(jù)
  • zdir:條形圖平面化的方向,具體可以對應(yīng)代碼理解。

code:

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()

九、子圖繪制(subplot)

A-不同的2-D圖形,分布在3-D空間,其實就是投影空間不空,對應(yīng)code:

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))
c_list = []
for c in colors:
    c_list.append([c]*20)
# 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=c_list, 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')

B-子圖Subplot用法

與MATLAB不同的是,如果一個四子圖效果,如:

MATLAB:

subplot(2,2,1)
subplot(2,2,2)
subplot(2,2,[3,4])

Python:

subplot(2,2,1)
subplot(2,2,2)
subplot(2,1,2)

code:

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(2, 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(2,1,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()

補充:

文本注釋的基本用法:

code:

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()

參考:

http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html

總結(jié)

到此這篇關(guān)于python繪制三維圖的文章就介紹到這了,更多相關(guān)python繪制三維圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 利用python計算時間差(返回天數(shù))

    利用python計算時間差(返回天數(shù))

    這篇文章主要給大家介紹了關(guān)于如何利用python計算時間差(返回天數(shù))的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • python 實現(xiàn)語音聊天機器人的示例代碼

    python 實現(xiàn)語音聊天機器人的示例代碼

    這篇文章主要介紹了python 實現(xiàn)語音聊天機器人的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-12-12
  • Python八大常見排序算法定義、實現(xiàn)及時間消耗效率分析

    Python八大常見排序算法定義、實現(xiàn)及時間消耗效率分析

    這篇文章主要介紹了Python八大常見排序算法定義、實現(xiàn)及時間消耗效率分析,結(jié)合具體實例形式對比分析了冒泡排序、直接插入排序、選擇排序、歸并排序、希爾排序、桶排序、堆排序等排序算法的使用與執(zhí)行效率,需要的朋友可以參考下
    2018-04-04
  • 一文講解如何查看python腳本所依賴三方包及其版本

    一文講解如何查看python腳本所依賴三方包及其版本

    Python因為具有超多的第三方庫而被大家喜歡,下面這篇文章主要給大家介紹了關(guān)于如何查看python腳本所依賴三方包及其版本的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下
    2023-03-03
  • Python3.4實現(xiàn)從HTTP代理網(wǎng)站批量獲取代理并篩選的方法示例

    Python3.4實現(xiàn)從HTTP代理網(wǎng)站批量獲取代理并篩選的方法示例

    這篇文章主要介紹了Python3.4實現(xiàn)從HTTP代理網(wǎng)站批量獲取代理并篩選的方法,涉及Python網(wǎng)絡(luò)連接、讀取、判斷等相關(guān)操作技巧,需要的朋友可以參考下
    2017-09-09
  • Django 實現(xiàn) Websocket 廣播、點對點發(fā)送消息的代碼

    Django 實現(xiàn) Websocket 廣播、點對點發(fā)送消息的代碼

    這篇文章主要介紹了Django 實現(xiàn) Websocket 廣播、點對點發(fā)送消息,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • Python中轉(zhuǎn)換角度為弧度的radians()方法

    Python中轉(zhuǎn)換角度為弧度的radians()方法

    這篇文章主要介紹了Python中轉(zhuǎn)換角度為弧度的radians()方法,是Python入門中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-05-05
  • Python __slots__的使用方法

    Python __slots__的使用方法

    這篇文章主要介紹了Python __slots__的使用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • Python3實時操作處理日志文件的實現(xiàn)

    Python3實時操作處理日志文件的實現(xiàn)

    本文主要介紹了Python3實時操作處理日志文件的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • Python將運行結(jié)果導(dǎo)出為CSV格式的兩種常用方法

    Python將運行結(jié)果導(dǎo)出為CSV格式的兩種常用方法

    這篇文章主要給大家介紹了關(guān)于Python將運行結(jié)果導(dǎo)出為CSV格式的兩種常用方法,Python生成(導(dǎo)出)csv文件其實很簡單,我們一般可以用csv模塊或者pandas庫來實現(xiàn),需要的朋友可以參考下
    2023-07-07

最新評論

云林县| 诸暨市| 蓝山县| 隆林| 长岭县| 宜兴市| 工布江达县| 台北县| 石楼县| 涿州市| 佛教| 呼玛县| 关岭| 平谷区| 佛冈县| 左权县| 金昌市| 嵩明县| 贺州市| 天水市| 凤山市| 合阳县| 重庆市| 武邑县| 花垣县| 南宁市| 宁远县| 乌海市| 临西县| 盐山县| 濮阳县| 安图县| 盖州市| 富民县| 肥城市| 资溪县| 大连市| 樟树市| 康保县| 文水县| 虎林市|