Python繪制3D圖形
3D圖形在數(shù)據(jù)分析、數(shù)據(jù)建模、圖形和圖像處理等領(lǐng)域中都有著廣泛的應(yīng)用,下面將給大家介紹一下如何使用python進(jìn)行3D圖形的繪制,包括3D散點(diǎn)、3D表面、3D輪廓、3D直線(曲線)以及3D文字等的繪制。
準(zhǔn)備工作:
python中繪制3D圖形,依舊使用常用的繪圖模塊matplotlib,但需要安裝mpl_toolkits工具包,安裝方法如下:windows命令行進(jìn)入到python安裝目錄下的Scripts文件夾下,執(zhí)行: pip install --upgrade matplotlib即可;linux環(huán)境下直接執(zhí)行該命令。
安裝好這個(gè)模塊后,即可調(diào)用mpl_tookits下的mplot3d類進(jìn)行3D圖形的繪制。
下面以實(shí)例進(jìn)行說(shuō)明。
1、3D表面形狀的繪制
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') # Make data u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) # Plot the surface ax.plot_surface(x, y, z, color='b') plt.show()
球表面,結(jié)果如下:
2、3D直線(曲線)的繪制
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()
這段代碼用于繪制一個(gè)螺旋狀3D曲線,結(jié)果如下:
3、繪制3D輪廓
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) 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()
繪制結(jié)果如下:
4、繪制3D直方圖
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') x, y = np.random.rand(2, 100) * 4 hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]]) # Construct arrays for the anchor positions of the 16 bars. # Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos, # ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid # with indexing='ij'. xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25) xpos = xpos.flatten('F') ypos = ypos.flatten('F') zpos = np.zeros_like(xpos) # Construct arrays with the dimensions for the 16 bars. dx = 0.5 * np.ones_like(zpos) dy = dx.copy() dz = hist.flatten() ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average') plt.show()
繪制結(jié)果如下:
5、繪制3D網(wǎng)狀線
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()
繪制結(jié)果如下:
6、繪制3D三角面片圖
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(
繪制結(jié)果如下:
7、繪制3D散點(diǎn)圖
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()
繪制結(jié)果如下:
8、繪制3D文字
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(
繪制結(jié)果如下:
9、3D條狀圖
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()
繪制結(jié)果如下:
以上所述是小編給大家介紹的python繪制3D圖形,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持
相關(guān)文章
分享4個(gè)方便且好用的Python自動(dòng)化腳本
自動(dòng)化測(cè)試是把以人為驅(qū)動(dòng)的測(cè)試行為轉(zhuǎn)化為機(jī)器執(zhí)行的一種過(guò)程,直白的就是為了節(jié)省人力、時(shí)間或硬件資源,提高測(cè)試效率,這篇文章主要給大家分享介紹了3個(gè)方便且好用的Python自動(dòng)化腳本,需要的朋友可以參考下2022-02-02Python 調(diào)用 Outlook 發(fā)送郵件過(guò)程解析
這篇文章主要介紹了Python 調(diào)用 Outlook 發(fā)送郵件過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08Python使用Matplotlib實(shí)現(xiàn)雨點(diǎn)圖動(dòng)畫效果的方法
這篇文章主要介紹了Python使用Matplotlib實(shí)現(xiàn)雨點(diǎn)圖動(dòng)畫效果的方法,結(jié)合實(shí)例形式分析了win10安裝ffmpeg及animation函數(shù)的使用相關(guān)操作技巧,需要的朋友可以參考下2017-12-12python神經(jīng)網(wǎng)絡(luò)Keras實(shí)現(xiàn)GRU及其參數(shù)量
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)Keras實(shí)現(xiàn)GRU及其參數(shù)量,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05詳解Python Socket網(wǎng)絡(luò)編程
這篇文章主要為大家介紹了Python Socket網(wǎng)絡(luò)編程,主要介紹使用 Python 進(jìn)行 TCP Socket網(wǎng)絡(luò)編程2016-01-01Django 多語(yǔ)言教程的實(shí)現(xiàn)(i18n)
這篇文章主要介紹了Django 多語(yǔ)言教程的實(shí)現(xiàn)(i18n),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-07-07