Python數(shù)據(jù)分析之Matplotlib的常用操作總結(jié)
使用準備
使用matplotlib需引入:
import matplotlib.pyplot as plt
通常2會配合著numpy使用,numpy引入:
import numpy as np
1、簡單的繪制圖像
def matplotlib_draw(): # 從-1到1生成100個點,包括最后一個點,默認為不包括最后一個點 x = np.linspace(-1, 1, 100, endpoint=True) y = 2 * x + 1 plt.plot(x, y) # plot將信息傳入圖中 plt.show() # 展示圖片

2、視圖面板的常用操作
def matplotlib_figure(): x = np.linspace(-1, 1, 100) y1 = 2 * x + 1 y2 = x ** 2 # 平方 plt.figure() # figure是視圖面板 plt.plot(x, y1) # 這里再創(chuàng)建一個視圖面板,最后會生成兩張圖,figure只繪制范圍以下的部分 plt.figure(figsize=(4, 4)) # 設(shè)置視圖長寬 plt.plot(x, y2) plt.show()


3、樣式及各類常用修飾屬性
def matplotlib_style():
x = np.linspace(-3, 3, 100)
y1 = 2 * x + 1
y2 = x ** 2 # 平方
# 限制xy輸出圖像的范圍
plt.xlim((-1, 2)) # 限制x的范圍
plt.ylim((-2, 3)) # 限制y的范圍
# xy描述
plt.xlabel('I am X')
plt.ylabel('I am Y')
# 設(shè)置xy刻度值
# 從-2到2上取11個點,最后生成一個一維數(shù)組
new_sticks = np.linspace(-2, 2, 11)
plt.xticks(new_sticks)
# 使用文字代替數(shù)字刻度
plt.yticks([-1, 0, 1, 2, 3], ['level1', 'level2', 'level3', 'level4', 'level5'])
# 獲取坐標(biāo)軸 gca get current axis
ax = plt.gca()
ax.spines['right'].set_color('red') # 設(shè)置右邊框為紅色
ax.spines['top'].set_color('none') # 設(shè)置頂部邊框為沒有顏色,即無邊框
# 把x軸的刻度設(shè)置為'bottom'
ax.xaxis.set_ticks_position('bottom')
# 把y軸的刻度設(shè)置為'left'
ax.yaxis.set_ticks_position('left')
# 設(shè)置xy軸的位置,以下測試xy軸相交于(1,0)
# bottom對應(yīng)到0點
ax.spines['bottom'].set_position(('data', 0))
# left對應(yīng)到1點
ax.spines['left'].set_position(('data', 1)) # y軸會與1刻度對齊
# 顏色、線寬、實線:'-',虛線:'--',alpha表示透明度
plt.plot(x, y1, color="red", linewidth=1.0, linestyle='--', alpha=0.5)
plt.plot(x, y2, color="blue", linewidth=5.0, linestyle='-')
plt.show() # 這里沒有設(shè)置figure那么兩個線圖就會放到一個視圖里
4、legend圖例的使用
def matplotlib_legend(): x = np.linspace(-3, 3, 100) y1 = 2 * x + 1 y2 = x ** 2 # 平方 l1, = plt.plot(x, y1, color="red", linewidth=1.0, linestyle='--', alpha=0.5) l2, = plt.plot(x, y2, color="blue", linewidth=5.0, linestyle='-') # handles里面?zhèn)魅胍a(chǎn)生圖例的關(guān)系線,labels中傳入對應(yīng)的名稱, # loc='best'表示自動選擇最好的位置放置圖例 plt.legend(handles=[l1, l2], labels=['test1', 'test2'], loc='best') plt.show()

5、添加文字等描述
def matplotlib_describe():
x = np.linspace(-3, 3, 100)
y = 2 * x + 1
plt.plot(x, y, color="red", linewidth=1.0, linestyle='-')
# 畫點,s表示點的大小
x0 = 0.5
y0 = 2 * x0 + 1
plt.scatter(x0, y0, s=50, color='b')
# 畫虛線,
# k代表黑色,--代表虛線,lw線寬
# 表示重(x0,y0)到(x0,-4)畫線
plt.plot([x0, x0], [y0, -4], 'k--', lw=2)
# 標(biāo)注,xytext:位置,textcoords設(shè)置起始位置,arrowprops設(shè)置箭頭,connectionstyle設(shè)置弧度
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xytext=(+30, -30),
textcoords="offset points", fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
# 文字描述
plt.text(-3, 3, r'$this\ is\ the\ text$', fontdict={'size': '16', 'color': 'r'})
plt.show()
6、不同類型圖像的繪制
(1)scatter繪制散點圖:
def matplotlib_scatter(): plt.figure() plt.scatter(np.arange(5), np.arange(5)) # 安排兩個0到4的數(shù)組繪制 x = np.random.normal(0, 1, 500) # 正態(tài)分布的500個數(shù) y = np.random.normal(0, 1, 500) plt.figure() plt.scatter(x, y, s=50, c='b', alpha=0.5) plt.show()


(2)bar繪制直方圖:
def matplotlib_bar(): x = np.arange(10) y = 2 ** x + 10 # facecolor塊的顏色,edgecolor塊邊框的顏色 plt.bar(x, y, facecolor='#9999ff', edgecolor='white') # 設(shè)置數(shù)值位置 for x, y in zip(x, y): # zip將x和y結(jié)合在一起 plt.text(x + 0.4, y, "%.2f" % y, ha='center', va='bottom') plt.show()

(3)contour輪廓圖:
def matplotlib_contours(): def f(a, b): return (1 - a / 2 + a ** 5 + b ** 3) * np.exp(-a ** 2 - b ** 2) x = np.linspace(-3, 3, 100) y = np.linspace(-3, 3, 100) X, Y = np.meshgrid(x, y) # 將x和y傳入一個網(wǎng)格中 # 8表示條形線的數(shù)量,數(shù)量越多越密集 plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot) # cmap代表圖的顏色 C = plt.contour(X, Y, f(X, Y), 8, color='black', linewidth=.5) plt.clabel(C, inline=True, fontsize=10) plt.xticks(()) plt.yticks(()) plt.show()

(4)3D圖:
3D圖繪制需額外再引入依賴:
from mpl_toolkits.mplot3d import Axes3D
def matplotlib_Axes3D():
fig = plt.figure() # 創(chuàng)建繪圖面版環(huán)境
ax = Axes3D(fig) # 將環(huán)境配置進去
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
# stride控制色塊大小
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow')
ax.set_zlim(-2, 2)
plt.show()
(5)subplot子圖繪制:
def matplotlib_subplot(): plt.figure() # 生成繪圖面板 plt.subplot(2, 1, 1) # 兩行1列繪圖位置的第1個位置 plt.plot([0, 1], [0, 1]) # 繪制從(0,0)繪制到(1,1)的圖像 plt.subplot(2, 3, 4) # 兩行3列繪圖位置的第4個位置 plt.plot([0, 1], [0, 1]) # 繪制從(0,0)繪制到(1,1)的圖像 plt.subplot(2, 3, 5) # 兩行3列繪圖位置的第5個位置 plt.plot([0, 1], [0, 1]) # 繪制從(0,0)繪制到(1,1)的圖像 plt.subplot(2, 3, 6) # 兩行3列繪圖位置的第6個位置 plt.plot([0, 1], [0, 1]) # 繪制從(0,0)繪制到(1,1)的圖像 plt.show()

(6)animation動圖繪制
需額外導(dǎo)入依賴:
from matplotlib import animation
# ipython里運行可以看到動態(tài)效果 def matplotlib_animation(): fig, ax = plt.subplots() x = np.arange(0, 2 * np.pi, 0.01) line, = ax.plot(x, np.sin(x)) def animate(i): line.set_ydata(np.sin(x + i / 10)) return line, def init(): line.set_ydata(np.sin(x)) return line, ani = animation.FuncAnimation(fig=fig, func=animate, init_func=init, interval=20) plt.show()

附:直方圖代碼實現(xiàn)
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
# 產(chǎn)生30個學(xué)生身高數(shù)據(jù)
hight = np.random.randint(low=140, high=190, size=30)
print("身高數(shù)據(jù)", hight)
# 繪制直方圖 plt.hist
# 參數(shù)1:要統(tǒng)計的數(shù)據(jù); 參數(shù)2:區(qū)間信息
# 區(qū)間信息有默認值 bins =10 ?分10組
# bins = [140, 145, 160, 170, 190]
# 除了最后一個 都是前閉后開;最后一組是前閉后閉
# [140,145) [145,160) [160,170) [170,190]
bins = [140, 180, 190]
cnt, bins_info, _ = plt.hist(hight,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?bins=10,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# bins=bins,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?edgecolor='w' ?# 柱子的邊緣顏色 白色
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?)
# 直方圖的返回值有3部分內(nèi)容
# 1. 每個區(qū)間的數(shù)據(jù)量
# 2. 區(qū)間信息
# 3. 區(qū)間內(nèi)數(shù)據(jù)數(shù)據(jù)信息 是個對象 不能直接查看
# print("直方圖的返回值", out)
# cnt, bins_info, _ = out
# 修改x軸刻度
plt.xticks(bins_info)
# 增加網(wǎng)格線
# 參數(shù)1:b bool類型 是否增加網(wǎng)格線
# 參數(shù) axis 網(wǎng)格線 垂直于 哪個軸
plt.grid(b=True,
? ? ? ? ?axis='y',
? ? ? ? ?# axis='both'
? ? ? ? ?alpha=0.3
? ? ? ? ?)
# 增加標(biāo)注信息 plt.text
print("區(qū)間信息", bins_info)
print("區(qū)間數(shù)據(jù)量", cnt)
bins_info_v2 = (bins_info[:-1] + bins_info[1:]) / 2
for i, j in zip(bins_info_v2, cnt):
? ? # print(i, j)
? ? plt.text(i, j + 0.4, j,
? ? ? ? ? ? ?horizontalalignment='center', ?# 水平居中
? ? ? ? ? ? ?verticalalignment='center', ?# 垂直居中
? ? ? ? ? ? ?)
# 調(diào)整y軸刻度
plt.yticks(np.arange(0, 20, 2))
plt.show()
更多見官方文檔:教程 | Matplotlib 中文
總結(jié)
到此這篇關(guān)于Python數(shù)據(jù)分析之Matplotlib常用操作的文章就介紹到這了,更多相關(guān)Python Matplotlib常用操作內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信