目錄
使用mplot3D繪制3D圖表
mplot3d概述
繪制3D線框圖(plot_wireframe())
繪制3D曲面圖(plot_surface())
繪制3D條形圖
?繪制3D柱形圖
np.meshgrid()函數(shù)的補充
使用animation制作動圖
例子1
?例子2
使用basemap繪制統(tǒng)計地圖
實例:美國部分城鎮(zhèn)人口分布(basemap)
實例1:三維空間的星星(3D散點圖)
實例2:三維空間閃爍的星星(3D動圖)
編程題(動點)
總結(jié)
使用mplot3D繪制3D圖表
mplot3d概述
'''Axes3D()方法
Axes3D(fig, rect=None, *args, azim=-60, zscale=None,
sharez=None, prooj_type='persp', **kwargs)
該方法的參數(shù)fig表示所屬畫布,rect表示確定三維坐標(biāo)系位置的元組
'''
# 創(chuàng)建Axes3D類對象的示例代碼如下:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
'''
官方推薦
add_suplot()方法
在調(diào)用add_suplot()方法添加繪圖區(qū)域時為該方法傳入projection='3d',
即指定坐標(biāo)系的類型為三維坐標(biāo)系,返回一個Axes3D類的對象
'''
# 創(chuàng)建Axes3D類對象的示例代碼如下:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
繪制3D線框圖(plot_wireframe())
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 獲取測試數(shù)據(jù)
X, Y, Z = axes3d.get_test_data(0.05)
# 繪制 3D線框圖
ax.plot_wireframe(X, Y, Z, # 表示x、y、z軸的數(shù)據(jù)
rstride=10, cstride=10 # 表示采樣的密度。
# 若使用參數(shù)rstride或cstride中任意一個,則另一個參數(shù)默認(rèn)為0
# rcount,ccount:表示每個坐標(biāo)軸方向所使用的最大樣本量,默認(rèn)為50
# 注意:參數(shù)rstride、cstride與參數(shù)rcount、ccount是互斥關(guān)系,它們不能同時使用
)
plt.show()
繪制3D曲面圖(plot_surface())
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
# 數(shù)據(jù)
x1 = np.arange(-5, 5, 0.25)
y1 = np.arange(-5, 5, 0.25)
# 對數(shù)據(jù)進行小處理
x1, y1 = np.meshgrid(x1, y1) # X, Y = np.meshgrid(x, y) 代表的是將x中每一個數(shù)據(jù)和y中每一個數(shù)據(jù)組合生成很多點,然后將這些點的x坐標(biāo)放入到X中,y坐標(biāo)放入Y中,并且相應(yīng)位置是對應(yīng)的
r1 = np.sqrt(x1** 2 + y1 ** 2)
z1 = np.sin(r1)
# 畫布
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 繪制曲面圖
ax.plot_surface(x1, y1, z1, # 數(shù)據(jù)
cmap=cm.coolwarm, # 曲面顏色映射表
linewidth=0,
)
# 設(shè)置 z 軸刻度的范圍
ax.set_zlim(-1.01, 1.01)
plt.show()
?
繪制3D條形圖
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
import numpy as np
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.sans-serif'] = ['SimHei']
# 創(chuàng)建畫布
fig = plt.figure()
# 創(chuàng)建3D坐標(biāo)系
axes3d = Axes3D(fig)
# 數(shù)據(jù)
zs = range(5)
left = np.arange(0, 10)
height = np.array([])
for i in range(len(zs)):
z = zs[i] # 0,1,2,3,4
height = np.random.randint(0, 30, size=10)
axes3d.bar(left, # y軸數(shù)據(jù)
height, # z軸數(shù)據(jù)
zs=z, # x軸數(shù)據(jù)
zdir='x',
color=['red', 'green', 'purple', 'yellow', 'blue', 'black', 'gray', 'orange', 'pink', 'cyan'])
plt.xticks(zs, ['1月份', '2月份', '3月份', '4月份', '5月份']) # x軸標(biāo)簽
plt.yticks(left, ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'G']) # y軸標(biāo)簽
plt.xlabel('月份')
plt.ylabel('型號')
plt.show()
?繪制3D柱形圖
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams['font.sans-serif'] = ['SimHei']
# 數(shù)據(jù)
color = ["blue", "cornflowerblue", "mediumturquoise", "goldenrod", "yellow"]
lambda1 = lambda2 = [10 ** x for x in range(-2, 3)]
# [0.01, 0.1, 1, 10, 100]
# x, y: position
x = list(range(len(lambda1)))
y = list(range(len(lambda2)))
# [0, 1, 2, 3, 4]
x_tickets = [str(_x) for _x in lambda1] # 將其轉(zhuǎn)換為string類型
y_tickets = [str(_x) for _x in lambda2]
# ['0.01', '0.1', '1', '10', '100']
# acc = np.random.rand(len(x), len(y))
acc = np.arange(len(x) * len(y)).reshape(len(x), len(y)) + 1 # 轉(zhuǎn)換為5行5列的二維數(shù)組,第一位為1
acc = acc / acc.max()
xx, yy = np.meshgrid(x, y)# 將x中每一個數(shù)據(jù)和y中每一個數(shù)據(jù)組合生成很多點,然后將這些點的x坐標(biāo)放入到xx中,y坐標(biāo)放入yy中,并且相應(yīng)位置是對應(yīng)的
color_list = [] # 定義一個列表
for i in range(len(y)):
c = color[i] # 選擇顏色
color_list.append([c] * len(x)) # 把顏色放入列表,并乘以x軸長度,以便每個柱形圖都有顏色
color_list = np.asarray(color_list) # 將輸入轉(zhuǎn)為矩陣格式
xx_flat, yy_flat, acc_flat, color_flat = xx.ravel(), yy.ravel(), acc.T.ravel(), color_list.ravel() # #ravel()方法將數(shù)組維度拉成一維數(shù)組
# 畫布
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
# 繪制3D柱形圖
ax.bar3d(xx_flat - 0.5, # 中心在刻度線
yy_flat - 0.5,
0,
1, 1,
acc_flat,
color=color_flat, # 顏色
edgecolor="black", # 黑色描邊
shade=True) # 加陰影
plt.show()
np.meshgrid()函數(shù)的補充
# X, Y = np.meshgrid(x, y) 代表的是將x中每一個數(shù)據(jù)和y中每一個數(shù)據(jù)組合生成很多點,然后將這些點的x坐標(biāo)放入到X中,y坐標(biāo)放入Y中,并且相應(yīng)位置是對應(yīng)的
# 如:
x = [1, 2, 3, 4]
y = [7, 8, 9]
# x和y中的每一個元素組合生成
[[[1, 7], [2, 7], [3, 7], [4, 7]],
[[1, 8], [2, 8], [3, 8], [4, 8]],
[[1, 9], [2, 9], [3, 9], [4, 9]]]
# 然后
# 再分別放入X和Y中
X = [[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]]
Y = [[7, 7, 7, 7],
[8, 8, 8, 8],
[9, 9, 9, 9],]
# 例子
In [1]: import numpy as np
In [2]: import matplotlib.pyplot as plt
In [3]: x = np.linspace(1, 4, 4)
In [4]: x
Out[4]: array([1., 2., 3., 4.])
In [5]: y = np.linspace(7, 9, 3)
In [6]: y
Out[6]: array([7., 8., 9.])
In [7]: X, Y = np.meshgrid(x, y)
In [8]: X
Out[8]:
array([[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.]])
In [9]: Y
Out[9]:
array([[7., 7., 7., 7.],
[8., 8., 8., 8.],
[9., 9., 9., 9.]])
使用animation制作動圖
# FuncAnimation類
FuncAnimation(fig, # 表示動畫所在的畫布
func, # 表示每幀動畫調(diào)用的函數(shù)
frames, # 表示動畫的長度(一次動畫包含的幀數(shù))
init_func, # 表示用于開始繪制幀的函數(shù),它會在第一幀動畫之前調(diào)用一次。若未設(shè)置該參數(shù),則程序?qū)⑹褂胒rames序列中第一項的繪圖結(jié)果
fargs, # 表示傳遞給func函數(shù)的其他參數(shù)
interval, # 表示更新動畫的頻率,以毫秒為單位,默認(rèn)為200
blit, # 表示是否更新所有的點,默認(rèn)為False。官方推薦將blit參數(shù)設(shè)為True,但建議macOS用戶將blit參數(shù)設(shè)為False,否則將無法顯示動畫
)
-
例子1
-
# 以qt5為圖形界面后端 %matplotlib qt5 import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # 導(dǎo)入動畫FuncAnimation類 # 數(shù)據(jù) x = np.arange(0, 2 * np.pi, 0.01) # 畫布 fig, ax = plt.subplots() # 繪圖 line, = ax.plot(x, np.sin(x)) # 定義每幀動畫調(diào)用的函數(shù) def animate(i): line.set_ydata(np.sin(x + i / 10.0)) return line # 定義初始化幀的函數(shù) def init(): line.set_ydata(np.sin(x)) return line ani = FuncAnimation(fig=fig, # 畫布 func=animate, # 每幀動畫調(diào)用的函數(shù) frames=100, # 一次動畫包含的幀數(shù) init_func=init, # 用于開始繪制幀的函數(shù),它會在第一幀動畫之前調(diào)用一次。 interval=20, # 更新動畫的頻率,以毫秒為單位 blit=False # 是否更新所有的點,默認(rèn)為False。 ) plt.show()
-
?例子2
-
# 案例2:點擊鼠標(biāo)左鍵暫停/繼續(xù)動畫 import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() # 構(gòu)造空線條 line, = ax.plot([], []) # 構(gòu)造線條數(shù)據(jù) n = 50 x = np.arange(n) y = np.sin(x) # 設(shè)置坐標(biāo)軸刻度范圍 ax.set_ylim(-1.1, 1.1) ax.set_xlim(0, n) # 控制每幀畫面如何繪制 def update(i): line.set_data(x[:i], y[:i]) return line, ani = animation.FuncAnimation(fig, update, n, interval=10,) # 事件處理 paused = False def toggle_pause(event): global paused if paused: ani.resume() else: ani.pause() paused = not paused fig.canvas.mpl_connect('button_press_event', toggle_pause) plt.show()
使用basemap繪制統(tǒng)計地圖
'''
安裝basemap
cmd窗口命令行安裝
pip install basemap
安裝完成后,在python里輸入以下代碼:
from mpl_toolkits.basemap import Basemap
無報錯,則成功
'''
# 使用basemap
# 以下是常用參數(shù)
Basemap(llcrnrlon=None,llcrnrlat=None, # 表示地圖投影區(qū)域左下角的經(jīng)度或緯度
urcrnrlon=None,urcrnrlat=None, # 表示地圖投影區(qū)域右上角的經(jīng)度或緯度
lon_0=None,lat_0=None, # 表示所需地圖投影區(qū)域中心的經(jīng)度或緯度
width=None,height=None, # 表示所需地圖投影區(qū)域的寬度和高度
rsphere=None, # 表示投影中使用的球體的半徑
resolution=None, # 表示包括海岸線、湖泊等的分辨率,可以取值為'c'(粗略。默認(rèn)值)、'l'(低)、'i'(中級)、'h'(高)、'f'(完整)或None。
# 若要使用shapefile(一種用于存儲地理要素的幾何位置和屬性信息的格式)文件,則可以將resolution參數(shù)設(shè)為None,這種方式無須加載任何數(shù)據(jù),且會極大提高程序的性能
area_thresh=None, # 表示不會繪制海岸線或湖泊的閾值
anchor='C', # 表示地圖置于繪圖區(qū)域的方式,默認(rèn)為C,表示地圖居中
projection='cyl' # 表示地圖投影的類型,默認(rèn)值為cyl
)
實例:美國部分城鎮(zhèn)人口分布(basemap)
# 03_twinkling_stars_in_3d
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 創(chuàng)建 Basemap 對象
map = Basemap(projection='stere', # 立體影像投影
lat_0=90, lon_0=-105, # 地圖投影區(qū)域中心的經(jīng)度或緯度
llcrnrlat=23.41, llcrnrlon=-118.67, # 地圖投影區(qū)域左下角的經(jīng)度或緯度
urcrnrlat=45.44, urcrnrlon=-64.52, # 地圖投影區(qū)域右上角的經(jīng)度或緯度
rsphere=6371200, # 投影中使用的球體的半徑
resolution='l', # 表示包括海岸線、湖泊低的分辨率
area_thresh=10000 # 表示不會繪制海岸線或湖泊的閾值
)
map.drawmapboundary() # 繪制地圖投影周圍邊界
map.drawstates() # 繪制州界
map.drawcoastlines() # 繪制海岸線
map.drawcountries() # 繪制國家邊界
# 繪制緯線
parallels = np.arange(0., 90, 10.)
map.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)
# 繪制經(jīng)線
meridians = np.arange(-110., -60., 10.)
map.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)
# 讀取文件數(shù)據(jù)
posi = pd.read_csv("第七章/2014_us_cities.csv")
# 從3228組城市數(shù)據(jù)中選擇500 組數(shù)據(jù)
lat = np.array(posi["lat"][0:500]) # 獲取緯度值
lon = np.array(posi["lon"][0:500]) # 獲取經(jīng)度值
pop = np.array(posi["pop"][0:500], dtype=float) # 獲取人口數(shù)
# 氣泡圖的氣泡大小
size = (pop / np.max(pop)) * 1000
x, y = map(lon, lat)
map.scatter(x, y, s=size)
plt.title('2014年美國部分城鎮(zhèn)的人口分布情況')
plt.show()
實例1:三維空間的星星(3D散點圖)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 生成測試數(shù)據(jù)
x = np.random.randint(0, 40, 30)
y = np.random.randint(0, 40, 30)
z = np.random.randint(0, 40, 30)
# 創(chuàng)建三維坐標(biāo)系的繪圖區(qū)域, 并在該區(qū)域中繪制3D散點圖
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for xx, yy, zz in zip(x, y, z):
# 簡單判斷邏輯,給每個范圍的星星賦顏色
color = 'y'
if 10 < zz < 20:
color = '#C71585'
elif zz >= 20:
color = '#008B8B'
ax.scatter(xx, yy, zz, c=color, marker='*',
s=160,
linewidth=1, # 線型寬度
edgecolor='black' # 邊緣顏色
)
# 設(shè)置軸名稱和標(biāo)題
ax.set_xlabel('x軸')
ax.set_ylabel('y軸')
ax.set_zlabel('z軸')
ax.set_title('3D散點圖', fontproperties='simhei', # 字體樣式
fontsize=14 # 字體大小
)
plt.tight_layout() # 使圖形更加緊湊
plt.show()
實例2:三維空間閃爍的星星(3D動圖)
# 02_twinkling_stars_in_3d
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 生成測試數(shù)據(jù)
xx = np.array([13, 5, 25, 13, 9, 19, 3, 39, 13, 27])
yy = np.array([4, 38, 16, 26, 7, 19, 28, 10, 17, 18])
zz = np.array([7, 19, 6, 12, 25, 19, 23, 25, 10, 15])
# 畫布和創(chuàng)建Axes3D對象類
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 繪制初始的3D散點圖
star = ax.scatter(xx, yy, zz, # 數(shù)據(jù)
c='#C71585', # 顏色
marker='*', # 標(biāo)記類型
s=160, # 標(biāo)記大小
linewidth=1, # 線型寬度
edgecolor='black' # 邊緣顏色
)
# 定義每幀動畫調(diào)用的函數(shù)
def animate(i):
if i % 2:
color = '#C71585'
else:
color = 'white'
next_star = ax.scatter(xx, yy, zz, c=color, marker='*', s = 160, linewidth=1, edgecolor='black')
return next_star
# 定義初始化幀的函數(shù)
def init():
return star # 返回初始的3D散點圖
ani = FuncAnimation(fig=fig, # 畫布
func=animate, # 每幀動畫調(diào)用
frames=None, # 一次動畫包含的幀數(shù)
init_func =init, # 用于開始繪制幀的函數(shù),它會在第一幀動畫之前調(diào)用一次。
interval=1000, # 更新動畫的頻率,以毫秒為單位
blit=False # 是否更新所有的點,默認(rèn)為False。
)
# 設(shè)置軸名稱和標(biāo)題
ax.set_xlabel('x軸')
ax.set_ylabel('y軸')
ax.set_zlabel('z軸')
ax.set_title('3D散點圖', fontproperties='simhei', fontsize=14)
plt.tight_layout() # 使圖形更加緊湊
plt.show()
?
編程題(動點)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation # 指定渲染環(huán)境
%matplotlib auto
# 自動
# 設(shè)置畫布
fig = plt.figure(figsize=(10,6))
# 設(shè)置x,y參數(shù)
x = np.linspace(0, 2*np.pi, 256)
y = np.sin(x)
# 定義方法
def point(self):
points.set_data(x[self], y[self]) # x[self], y[self] 表示x,y的數(shù)據(jù)
text.set_text("x=%.3f,y=%.3f"%(x[self], y[self])) # 傳入x,y的數(shù)據(jù),保留三位小數(shù)
return points, text # Line2D(_line1) #Text(4, 1, 'x=4.066,y=-0.798')
# 繪制曲線圖
plt.plot(x, y)
# 繪制動點
points,= plt.plot(x[0], y[0], # 初始點
"or"
)
text = plt.text(4, 1, # 文本注釋位置
'',
fontsize=14
) # 添加文本注釋
ani = animation.FuncAnimation(fig, # 畫布
point,
np.arange(0, 256),
interval=100, # 更新動畫的頻率,以毫秒為單位
blit=True # 是否更新所有的點,默認(rèn)為False。
)
plt.show()
文章來源:http://www.zghlxwxcb.cn/news/detail-758135.html
總結(jié)
本文主要使用matplotlib相關(guān)庫繪制3D圖表和統(tǒng)計地圖,以望多加練習(xí)!文章來源地址http://www.zghlxwxcb.cn/news/detail-758135.html
到了這里,關(guān)于使用matplotlib繪制3D圖表和統(tǒng)計地圖的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!