python繪制三維圖

需要資料的加我:hn27242508

一、初始化

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

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

1

2

3

4

import?matplotlib.pyplot as plt

from?mpl_toolkits.mplot3d?import?Axes3D

fig?=?plt.figure()

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

二曙咽、直線繪制(Line plots)

基本用法:

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

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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

三尤蛮、散點(diǎn)繪制(Scatter plots)

基本用法:

1ax.scatter(xs, ys, zs, s=20, c=None, depthshade=True,?*args,?*kwargs)

xs,ys,zs:輸入數(shù)據(jù)屡律;

s:scatter點(diǎn)的尺寸

c:顏色掩驱,如c = 'r'就是紅色潘靖;

depthshase:透明化蕉陋,True為透明,默認(rèn)為True洼畅,F(xiàn)alse為不透明

*args等為擴(kuò)展變量泵殴,如maker = 'o',則scatter結(jié)果為’o‘的形狀

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

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)

基本用法:

1ax.plot_wireframe(X, Y, Z,?*args,?**kwargs)

X,Y,Z:輸入數(shù)據(jù)

rstride:行步長(zhǎng)

cstride:列步長(zhǎng)

rcount:行數(shù)上限

ccount:列數(shù)上限

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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)

基本用法:

1ax.plot_surface(X, Y, Z,?*args,?**kwargs)

X,Y,Z:數(shù)據(jù)

rstride、cstride宣决、rcount蘸劈、ccount:同Wireframe plots定義

color:表面顏色

cmap:圖層

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

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)

基本用法:

1ax.plot_trisurf(*args,?**kwargs)

X,Y,Z:數(shù)據(jù)

其他參數(shù)類似surface-plot

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

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)

基本用法:

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

code:

1

2

3

4

5

6

7

8

9

10

11

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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(條形圖)

基本用法:

1ax.bar(left, height, zs=0, zdir='z',?*args,?**kwargs

x洼专,y壹甥,zs = z,數(shù)據(jù)

zdir:條形圖平面化的方向壶熏,具體可以對(duì)應(yīng)代碼理解句柠。

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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空間溯职,其實(shí)就是投影空間不空,對(duì)應(yīng)code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

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不同的是帽哑,如果一個(gè)四子圖效果谜酒,如:

MATLAB:

1

2

3

subplot(2,2,1)

subplot(2,2,2)

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

Python:

1

2

3

subplot(2,2,1)

subplot(2,2,2)

subplot(2,1,2)

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

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

?補(bǔ)充:

文本注釋的基本用法:

code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市妻枕,隨后出現(xiàn)的幾起案子僻族,更是在濱河造成了極大的恐慌,老刑警劉巖屡谐,帶你破解...
    沈念sama閱讀 222,104評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件述么,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡愕掏,警方通過查閱死者的電腦和手機(jī)度秘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來饵撑,“玉大人剑梳,你說我怎么就攤上這事唆貌。” “怎么了垢乙?”我有些...
    開封第一講書人閱讀 168,697評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵锨咙,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我追逮,道長(zhǎng)酪刀,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,836評(píng)論 1 298
  • 正文 為了忘掉前任羊壹,我火速辦了婚禮蓖宦,結(jié)果婚禮上齐婴,老公的妹妹穿的比我還像新娘油猫。我一直安慰自己,他們只是感情好柠偶,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,851評(píng)論 6 397
  • 文/花漫 我一把揭開白布情妖。 她就那樣靜靜地躺著,像睡著了一般诱担。 火紅的嫁衣襯著肌膚如雪毡证。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,441評(píng)論 1 310
  • 那天蔫仙,我揣著相機(jī)與錄音料睛,去河邊找鬼。 笑死摇邦,一個(gè)胖子當(dāng)著我的面吹牛恤煞,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播施籍,決...
    沈念sama閱讀 40,992評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼居扒,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了丑慎?” 一聲冷哼從身側(cè)響起喜喂,我...
    開封第一講書人閱讀 39,899評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎竿裂,沒想到半個(gè)月后玉吁,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,457評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡腻异,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,529評(píng)論 3 341
  • 正文 我和宋清朗相戀三年诈茧,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片捂掰。...
    茶點(diǎn)故事閱讀 40,664評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡敢会,死狀恐怖曾沈,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情鸥昏,我是刑警寧澤塞俱,帶...
    沈念sama閱讀 36,346評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站吏垮,受9級(jí)特大地震影響障涯,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜膳汪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,025評(píng)論 3 334
  • 文/蒙蒙 一唯蝶、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧遗嗽,春花似錦粘我、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至娇豫,卻和暖如春匙姜,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背冯痢。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評(píng)論 1 272
  • 我被黑心中介騙來泰國打工氮昧, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人浦楣。 一個(gè)月前我還...
    沈念sama閱讀 49,081評(píng)論 3 377
  • 正文 我出身青樓袖肥,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親椒振。 傳聞我的和親對(duì)象是個(gè)殘疾皇子昭伸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,675評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容