Python數據分析之Matplotlib的常用操作總結
更新時間:2022年01月04日 15:45:52 作者:€€-飛翔?-~£
Matplotlib是Python的繪圖庫,它可與NumPy一起使用,提供了一種有效的MatLab開源替代方案,下面這篇文章主要給大家介紹了關于Python數據分析之Matplotlib常用操作的相關資料,需要的朋友可以參考下
使用準備
使用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)) # 設置視圖長寬
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')
# 設置xy刻度值
# 從-2到2上取11個點,最后生成一個一維數組
new_sticks = np.linspace(-2, 2, 11)
plt.xticks(new_sticks)
# 使用文字代替數字刻度
plt.yticks([-1, 0, 1, 2, 3], ['level1', 'level2', 'level3', 'level4', 'level5'])
# 獲取坐標軸 gca get current axis
ax = plt.gca()
ax.spines['right'].set_color('red') # 設置右邊框為紅色
ax.spines['top'].set_color('none') # 設置頂部邊框為沒有顏色,即無邊框
# 把x軸的刻度設置為'bottom'
ax.xaxis.set_ticks_position('bottom')
# 把y軸的刻度設置為'left'
ax.yaxis.set_ticks_position('left')
# 設置xy軸的位置,以下測試xy軸相交于(1,0)
# bottom對應到0點
ax.spines['bottom'].set_position(('data', 0))
# left對應到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() # 這里沒有設置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生圖例的關系線,labels中傳入對應的名稱,
# 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)
# 標注,xytext:位置,textcoords設置起始位置,arrowprops設置箭頭,connectionstyle設置弧度
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的數組繪制
x = np.random.normal(0, 1, 500) # 正態(tài)分布的500個數
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')
# 設置數值位置
for x, y in zip(x, y): # zip將x和y結合在一起
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傳入一個網格中
# 8表示條形線的數量,數量越多越密集
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動圖繪制
需額外導入依賴:
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)
# 產生30個學生身高數據
hight = np.random.randint(low=140, high=190, size=30)
print("身高數據", hight)
# 繪制直方圖 plt.hist
# 參數1:要統(tǒng)計的數據; 參數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部分內容
# 1. 每個區(qū)間的數據量
# 2. 區(qū)間信息
# 3. 區(qū)間內數據數據信息 是個對象 不能直接查看
# print("直方圖的返回值", out)
# cnt, bins_info, _ = out
# 修改x軸刻度
plt.xticks(bins_info)
# 增加網格線
# 參數1:b bool類型 是否增加網格線
# 參數 axis 網格線 垂直于 哪個軸
plt.grid(b=True,
? ? ? ? ?axis='y',
? ? ? ? ?# axis='both'
? ? ? ? ?alpha=0.3
? ? ? ? ?)
# 增加標注信息 plt.text
print("區(qū)間信息", bins_info)
print("區(qū)間數據量", 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', ?# 垂直居中
? ? ? ? ? ? ?)
# 調整y軸刻度
plt.yticks(np.arange(0, 20, 2))
plt.show()
更多見官方文檔:教程 | Matplotlib 中文
總結
到此這篇關于Python數據分析之Matplotlib常用操作的文章就介紹到這了,更多相關Python Matplotlib常用操作內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python創(chuàng)建一個自定義視頻播放器的實現(xiàn)
本文主要介紹了Python創(chuàng)建一個自定義視頻播放器的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02
Python使用Selenium與pytest進行高效測試的示例詳解
隨著軟件開發(fā)的快速發(fā)展,自動化測試成為了提高開發(fā)效率、降低錯誤率的重要工具,Python作為一種高效且易于使用的編程語言,已經成為自動化測試領域的重要工具之一,本文將介紹如何使用Python、Selenium和pytest進行自動化測試,并展示一個簡單的自動化測試示例2025-01-01

