Python數(shù)據(jù)分析之Matplotlib的常用操作總結(jié)
使用準(zhǔn)備
使用matplotlib需引入:
import matplotlib.pyplot as plt
通常2會(huì)配合著numpy使用,numpy引入:
import numpy as np
1、簡(jiǎn)單的繪制圖像
def matplotlib_draw():
# 從-1到1生成100個(gè)點(diǎn),包括最后一個(gè)點(diǎn),默認(rèn)為不包括最后一個(gè)點(diǎn)
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)建一個(gè)視圖面板,最后會(huì)生成兩張圖,figure只繪制范圍以下的部分
plt.figure(figsize=(4, 4)) # 設(shè)置視圖長(zhǎng)寬
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個(gè)點(diǎn),最后生成一個(gè)一維數(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è)置右邊框?yàn)榧t色
ax.spines['top'].set_color('none') # 設(shè)置頂部邊框?yàn)闆]有顏色,即無邊框
# 把x軸的刻度設(shè)置為'bottom'
ax.xaxis.set_ticks_position('bottom')
# 把y軸的刻度設(shè)置為'left'
ax.yaxis.set_ticks_position('left')
# 設(shè)置xy軸的位置,以下測(cè)試xy軸相交于(1,0)
# bottom對(duì)應(yīng)到0點(diǎn)
ax.spines['bottom'].set_position(('data', 0))
# left對(duì)應(yīng)到1點(diǎn)
ax.spines['left'].set_position(('data', 1)) # y軸會(huì)與1刻度對(duì)齊
# 顏色、線寬、實(shí)線:'-',虛線:'--',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那么兩個(gè)線圖就會(huì)放到一個(gè)視圖里
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中傳入對(duì)應(yīng)的名稱,
# loc='best'表示自動(dòng)選擇最好的位置放置圖例
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='-')
# 畫點(diǎn),s表示點(diǎn)的大小
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繪制散點(diǎn)圖:
def matplotlib_scatter():
plt.figure()
plt.scatter(np.arange(5), np.arange(5)) # 安排兩個(gè)0到4的數(shù)組繪制
x = np.random.normal(0, 1, 500) # 正態(tài)分布的500個(gè)數(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傳入一個(gè)網(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)境配置進(jì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個(gè)位置
plt.plot([0, 1], [0, 1]) # 繪制從(0,0)繪制到(1,1)的圖像
plt.subplot(2, 3, 4) # 兩行3列繪圖位置的第4個(gè)位置
plt.plot([0, 1], [0, 1]) # 繪制從(0,0)繪制到(1,1)的圖像
plt.subplot(2, 3, 5) # 兩行3列繪圖位置的第5個(gè)位置
plt.plot([0, 1], [0, 1]) # 繪制從(0,0)繪制到(1,1)的圖像
plt.subplot(2, 3, 6) # 兩行3列繪圖位置的第6個(gè)位置
plt.plot([0, 1], [0, 1]) # 繪制從(0,0)繪制到(1,1)的圖像
plt.show()
(6)animation動(dòng)圖繪制
需額外導(dǎo)入依賴:
from matplotlib import animation
# ipython里運(yùn)行可以看到動(dòng)態(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()
附:直方圖代碼實(shí)現(xiàn)
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
# 產(chǎn)生30個(gè)學(xué)生身高數(shù)據(jù)
hight = np.random.randint(low=140, high=190, size=30)
print("身高數(shù)據(jù)", hight)
# 繪制直方圖 plt.hist
# 參數(shù)1:要統(tǒng)計(jì)的數(shù)據(jù); 參數(shù)2:區(qū)間信息
# 區(qū)間信息有默認(rèn)值 bins =10 ?分10組
# bins = [140, 145, 160, 170, 190]
# 除了最后一個(gè) 都是前閉后開;最后一組是前閉后閉
# [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. 每個(gè)區(qū)間的數(shù)據(jù)量
# 2. 區(qū)間信息
# 3. 區(qū)間內(nèi)數(shù)據(jù)數(shù)據(jù)信息 是個(gè)對(duì)象 不能直接查看
# print("直方圖的返回值", out)
# cnt, bins_info, _ = out
# 修改x軸刻度
plt.xticks(bins_info)
# 增加網(wǎng)格線
# 參數(shù)1:b bool類型 是否增加網(wǎng)格線
# 參數(shù) axis 網(wǎng)格線 垂直于 哪個(gè)軸
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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
openstack中的rpc遠(yuǎn)程調(diào)用的方法
今天通過本文給大家分享openstack中的rpc遠(yuǎn)程調(diào)用的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-07-07
Python實(shí)現(xiàn)識(shí)別手寫數(shù)字 Python圖片讀入與處理
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)識(shí)別手寫數(shù)字,Python圖片的讀入與處理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
Python實(shí)現(xiàn)對(duì)excel文件列表值進(jìn)行統(tǒng)計(jì)的方法
這篇文章主要介紹了Python實(shí)現(xiàn)對(duì)excel文件列表值進(jìn)行統(tǒng)計(jì)的方法,涉及Python基于win32com組件操作表格文件的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
Iconfont(矢量圖標(biāo))+iconmoon(圖標(biāo)svg互轉(zhuǎn))配合javascript實(shí)現(xiàn)社交分享系統(tǒng)
這篇文章主要介紹了Iconfont(矢量圖標(biāo))+iconmoon(圖標(biāo)svg互轉(zhuǎn))配合javascript實(shí)現(xiàn)社交分享系統(tǒng),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04

