Python 数据分析三剑客之 Matplotlib(四):线性图的绘制
CSDN 課程推薦:《Python 數據分析與挖掘》,講師劉順祥,浙江工商大學統計學碩士,數據分析師,曾擔任唯品會大數據部擔任數據分析師一職,負責支付環節的數據分析業務。曾與聯想、亨氏、網魚網咖等企業合作多個企業級項目。
Matplotlib 系列文章:
- Python 數據分析三劍客之 Matplotlib(一):初識 Matplotlib 與其 matplotibrc 配置文件
- Python 數據分析三劍客之 Matplotlib(二):文本描述 / 中文支持 / 畫布 / 網格等基本圖像屬性
- Python 數據分析三劍客之 Matplotlib(三):圖例 / LaTeX / 刻度 / 子圖 / 補丁等基本圖像屬性
- Python 數據分析三劍客之 Matplotlib(四):線性圖的繪制
- Python 數據分析三劍客之 Matplotlib(五):散點圖的繪制
- Python 數據分析三劍客之 Matplotlib(六):直方圖 / 柱狀圖 / 條形圖的繪制
- Python 數據分析三劍客之 Matplotlib(七):餅狀圖的繪制
- Python 數據分析三劍客之 Matplotlib(八):等高線 / 等值線圖的繪制
- Python 數據分析三劍客之 Matplotlib(九):極區圖 / 極坐標圖 / 雷達圖的繪制
- Python 數據分析三劍客之 Matplotlib(十):3D 圖的繪制
- Python 數據分析三劍客之 Matplotlib(十一):最熱門最常用的 50 個圖表【譯文】
另有 NumPy、Pandas 系列文章已更新完畢,歡迎關注:
- NumPy 系列文章:https://itrhx.blog.csdn.net/category_9780393.html
- Pandas 系列文章:https://itrhx.blog.csdn.net/category_9780397.html
推薦學習資料與網站(博主參與部分文檔翻譯):
- NumPy 官方中文網:https://www.numpy.org.cn/
- Pandas 官方中文網:https://www.pypandas.cn/
- Matplotlib 官方中文網:https://www.matplotlib.org.cn/
- NumPy、Matplotlib、Pandas 速查表:https://github.com/TRHX/Python-quick-reference-table
文章目錄
- 【1x00】方法描述
- 【2x00】基本示例
- 【3x00】多條數據
- 【4x00】設置顏色 / 樣式 / 圖例
- 【5x00】設置刻度
- 【6x00】隱藏畫布邊框
- 【7x00】移動坐標軸
- 【8x00】指定位置顯示文本
這里是一段防爬蟲文本,請讀者忽略。 本文原創首發于 CSDN,作者 TRHX。 博客首頁:https://itrhx.blog.csdn.net/ 本文鏈接:https://itrhx.blog.csdn.net/article/details/105839855 未經授權,禁止轉載!惡意轉載,后果自負!尊重原創,遠離剽竊!
【1x00】方法描述
matplotlib.pyplot.plot() 函數可以用于繪制線性圖。
本文用到的其他圖像屬性可參考前面的兩篇文章:
《Python 數據分析三劍客之 Matplotlib(二):文本描述 / 中文支持 / 畫布 / 網格等基本圖像屬性》
《Python 數據分析三劍客之 Matplotlib(三):圖例 / LaTeX / 刻度 / 子圖等基本圖像屬性》
基本語法:matplotlib.pyplot.plot(x, y[, fmt, \*\*kwargs])
| x | x 軸數據,數組類型或者標量,x 值是可選的,默認為 range(len(y)),通常為一維數組 |
| y | y 軸數據,數組類型或者標量,通常為一維數組 |
| fmt | str 類型,格式字符串,由標記、線條和顏色部分組成 fmt = '[marker][line][color]',例如 ro 表示紅色圓圈,三個參數的取值見后表 |
| **kwargs | 可選項,其他 Line2D 屬性,常用屬性見下表 |
部分常見 Line2D 屬性如下表,完整屬性參見官方文檔。
| alpha | 線條透明度,float 類型,取值范圍:[0, 1],默認為 1.0,即不透明 |
| antialiased / aa | 是否使用抗鋸齒渲染,默認為 True |
| color / c | 線條顏色,支持英文顏色名稱及其簡寫、十六進制顏色碼等,更多顏色示例參見官網 Color Demo |
| linestyle / ls | 線條樣式:'-' or 'solid', '--' or 'dashed', '-.' or 'dashdot' ':' or 'dotted', 'none' or ' ' or '' |
| linewidth / lw | 線條寬度,float 類型,默認 0.8 |
| markeredgecolor / mec | marker 標記的邊緣顏色 |
| markeredgewidth / mew | marker 標記的邊緣寬度 |
| markerfacecolor / mfc | marker 標記的顏色 |
| markerfacecoloralt / mfcalt | marker 標記的備用顏色 |
| markersize / ms | marker 標記的大小 |
fmt 中 marker、line、color 三個參數的取值:
| marker:線條標記樣式(線條上每個數據點的樣式) |
| '.' | 點標記(point marker) |
| ',' | 像素點標記(pixel marker) |
| 'o' | 圓圈標記(circle marker) |
| 'v' | 下三角標記(triangle_down marker) |
| '^' | 上三角標記(triangle_up marker) |
| '<' | 左三角標記(triangle_left marker) |
| '>' | 右三角標記(triangle_right marker) |
| '1' | 下三叉星標記(tri_down marker) |
| '2' | 上三叉星標記(tri_up marker) |
| '3' | 左三叉星標記(tri_left marker) |
| '4' | 右三叉星標記(tri_right marker) |
| 's' | 正方形標記(square marker) |
| 'p' | 五角形標記(pentagon marker) |
| '*' | 星號標記(star marker) |
| 'h' | 六邊形標記(hexagon1 marker) |
| 'H' | 六邊形標記(hexagon2 marker) |
| '+' | 加號標記(plus marker) |
| 'x' | X 號標記(x marker) |
| 'D' | 菱形標記(diamond marker) |
| 'd' | 細菱形標記(thin_diamond marker) |
| '|' | 垂直線標記(vline marker) |
| '_' | 水平線標記(hline marker) |
| line:線條樣式 |
| '-' | 實線樣式(solid line style) |
| '--' | 虛線樣式(dashed line style) |
| '-.' | 點劃線樣式(dash-dot line style) |
| ':' | 點樣式(dotted line style) |
| color:線條顏色,支持英文顏色名稱及其簡寫、十六進制顏色碼等 |
| 'b' | 藍色(blue) |
| 'g' | 綠色(green) |
| 'r' | 紅色(red) |
| 'c' | 青色(cyan) |
| 'm' | 品紅(magenta) |
| 'y' | 黃色(yellow) |
| 'k' | 黑色(black) |
| 'w' | 白色(white) |
fmt 舉例:
'b' # 默認形狀的藍色標記 'or' # 紅圈 '-g' # 綠色實線 '--' # 默認顏色的虛線 '^k:' # 黑色三角形標記,由虛線連接【2x00】基本示例
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 設置顯示中文x = np.arange(-2*np.pi, 2*np.pi, 0.01) y = np.sin(3*x)/x plt.title('線性圖示例') # 設置標題 plt.xlabel('x 軸') # 設置 x 軸標簽 plt.ylabel('y 軸') # 設置 y 軸標簽plt.plot(x, y) plt.show()【3x00】多條數據
繪制多條數據,設置不同數據,然后多次調用 plt.plot() 函數即可,不同數據的線條顏色會不同,系統隨機,可單獨指定不同顏色。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('多數據線性圖示例') plt.xlabel('x 軸') plt.ylabel('y 軸')plt.plot(x, y1) plt.plot(x, y2) plt.plot(x, y3)plt.show()【4x00】設置顏色 / 樣式 / 圖例
設置線條顏色樣式等屬性直接在 plot() 函數里面添加相應參數即可,設置圖例則需要調用 legend() 方法。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x1 = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x1)/x1 y2 = np.sin(2*x1)/x1x3 = np.arange(-2*np.pi, 2*np.pi, 2) y3 = np.array([0, 2, 1.5, 1, 2.4, -0.2, 1.7])plt.title('線性圖自定義樣式示例') plt.xlabel('x 軸') plt.ylabel('y 軸')plt.plot(x1, y1, '--r', label='x1, y1') # 線條樣式為 --,顏色為 r(紅色) plt.plot(x1, y2, color='green', label='x1, y2') # 樣式默認,顏色為綠色 plt.plot(x3, y3, marker='o', mfc='r', linestyle=':', label='x3, y3') # 標記樣式為 o,顏色為 r(紅色),線條樣式為 : plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5') # 圖例plt.show()這里是一段防爬蟲文本,請讀者忽略。 本文原創首發于 CSDN,作者 TRHX。 博客首頁:https://itrhx.blog.csdn.net/ 本文鏈接:https://itrhx.blog.csdn.net/article/details/105839855 未經授權,禁止轉載!惡意轉載,后果自負!尊重原創,遠離剽竊!
【5x00】設置刻度
調用 xticks() 和 yticks() 函數可以對坐標刻度進行自定義,該函數接收兩個參數,第一個參數表示要顯示的刻度位置,第二個參數表示在對應刻度線上要顯示的標簽信息,標簽信息支持 LeTeX 數學公式,使用時要用美元符號 $ 包圍起來。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('線性圖設置刻度示例') plt.xlabel('x 軸') plt.ylabel('y 軸')plt.plot(x, y1, '--r', label='sin(3*x)/x') plt.plot(x, y2, color='green', linestyle=':', label='sin(2*x)/x') plt.plot(x, y3, label='sin(1*x)/x') plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5')plt.xticks((-2*np.pi, -np.pi, 0, np.pi, 2*np.pi), (r'$-2\pi$', r'$-\pi$', '$0$', r'$\pi$', r'$2\pi$')) plt.yticks((-1, 0, 1, 2, 3))plt.show()【6x00】隱藏畫布邊框
Matplotlib 所繪制的圖表中的每個繪圖元素,例如線條 Line2D、文字 Text、刻度等在內存中都有一個對象與之對應。
matplotlib.pyplot.gca() 函數用于獲取當前的繪圖區 Axes(Get Current Axes)
matplotlib.pyplot.gcf() 函數用于獲取當前的畫布 Figure(Get Current Figure)
例如:matplotlib.pyplot.plot() 實際上會通過 matplotlib.pyplot.gca() 獲得當前的 Axes 對象 ax,然后再調用 ax.plot() 方法實現真正的繪圖。我們可以通過這種方法來實現畫布邊框的隱藏和坐標軸的移動。
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('線性圖隱藏畫布邊框示例') plt.xlabel('x 軸') plt.ylabel('y 軸')plt.plot(x, y1, '--r', label='sin(3*x)/x') plt.plot(x, y2, color='green', linestyle=':', label='sin(2*x)/x') plt.plot(x, y3, label='sin(1*x)/x') plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5')plt.xticks((-2*np.pi, -np.pi, 0, np.pi, 2*np.pi), (r'$-2\pi$', r'$-\pi$', '$0$', r'$\pi$', r'$2\pi$')) plt.yticks((-1, 0, 1, 2, 3))ax = plt.gca() # 獲取當前的畫布, gca = get current axes ax.spines['right'].set_visible(False) # 獲取繪圖區的軸對象(spines),設置右邊框不顯示 ax.spines['top'].set_visible(False) # 獲取繪圖區的軸對象(spines),設置上邊框不顯示 # ax.spines['right'].set_color('none') # 設置顏色為 none,效果與上面的一致 # ax.spines['top'].set_color('none')plt.show()【7x00】移動坐標軸
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('線性圖移動坐標軸示例') plt.xlabel('x 軸') plt.ylabel('y 軸')plt.plot(x, y1, '--r', label='sin(3*x)/x') plt.plot(x, y2, color='green', linestyle=':', label='sin(2*x)/x') plt.plot(x, y3, label='sin(1*x)/x') plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5')plt.xticks((-2*np.pi, -np.pi, 0, np.pi, 2*np.pi), (r'$-2\pi$', r'$-\pi$', '$0$', r'$\pi$', r'$2\pi$')) plt.yticks((-1, 0, 1, 2, 3))ax = plt.gca() # 獲取當前的畫布, gca = get current axes ax.spines['right'].set_visible(False) # 獲取繪圖區的軸對象(spines),設置右邊框不顯示 ax.spines['top'].set_visible(False) # 獲取繪圖區的軸對象(spines),設置上邊框不顯示 # ax.spines['right'].set_color('none') # 設置顏色為 none,效果與上面的一致 # ax.spines['top'].set_color('none')ax.spines['left'].set_position(('data', 0)) # 設置兩個坐標軸在(0, 0)位置相交 ax.spines['bottom'].set_position(('data', 0)) ax.xaxis.set_ticks_position('bottom') # 設置 x 坐標軸標簽的位置 ax.yaxis.set_ticks_position('left') # 設置 y 坐標軸標簽的位置plt.show()【8x00】指定位置顯示文本
matplotlib.pyplot.annotate() 方法可以在指定坐標點添加文本或 LaTeX 描述,也可以在其他位置添加描述后,使用箭頭指向某個坐標點。
基本語法:matplotlib.pyplot.annotate(text, xy, xytext, xycoords, textcoords, ha, va, arrowprops, \*\*kwargs)
| text | str 類型,注釋的文本 |
| xy | 被注釋的坐標點,格式:(x, y) |
| xytext | 注釋文本的坐標點,格式:(x, y),默認與 xy 相同 |
| xycoords | 被注釋的坐標點的參考系,取值參見表一,默認為 ‘data’ |
| textcoords | 注釋文本的坐標點的參考系,取值參見表二,默認為 xycoords 的值 |
| ha | 注釋點在注釋文本的左邊、右邊或中間(left、right、center) |
| va | 注釋點在注釋文本的上邊、下邊、中間或基線 (top、bottom、center、baseline) |
| arrowprops | dict 字典類型,箭頭的樣式 如果 arrowprops 不包含鍵 arrowstyle,則允許的鍵參見表三 如果 arrowprops 包含鍵 arrowstyle,則允許的鍵參見表四 |
| 表一:xycoords 取值類型 |
| ‘figure points’ | 以畫布左下角為參考,單位為點數 |
| ‘figure pixels’ | 以畫布左下角為參考,單位為像素 |
| ‘figure fraction’ | 以畫布左下角為參考,單位為百分比 |
| ‘axes points’ | 以繪圖區左下角為參考,單位為點數 |
| ‘axes pixels’ | 以繪圖區左下角為參考,單位為像素 |
| ‘axes fraction’ | 以繪圖區左下角為參考,單位為百分比 |
| ‘data’ | 使用被注釋對象的坐標系,即數據的 x, y 軸(默認) |
| ‘polar’ | 使用(θ,r)形式的極坐標系 |
| 表二:textcoords 取值類型 |
| ‘figure points’ | 以畫布左下角為參考,單位為點數 |
| ‘figure pixels’ | 以畫布左下角為參考,單位為像素 |
| ‘figure fraction’ | 以畫布左下角為參考,單位為百分比 |
| ‘axes points’ | 以繪圖區左下角為參考,單位為點數 |
| ‘axes pixels’ | 以繪圖區左下角為參考,單位為像素 |
| ‘axes fraction’ | 以繪圖區左下角為參考,單位為百分比 |
| ‘data’ | 使用被注釋對象的坐標系,即數據的 x, y 軸 |
| ‘polar’ | 使用(θ,r)形式的極坐標系 |
| ‘offset points’ | 相對于被注釋點的坐標 xy 的偏移量,單位是點 |
| ‘offset pixels’ | 相對于被注釋點的坐標 xy 的偏移量,單位是像素 |
| 表三:arrowprops 不包含鍵 arrowstyle 時的取值 |
| width | 箭頭的寬度,以點為單位 |
| headwidth | 箭頭底部的寬度,以點為單位 |
| headlength | 箭頭的長度,以點為單位 |
| shrink | 箭頭兩端收縮占總長的百分比 |
| ? | 其他 matplotlib.patches.FancyArrowPatch 中的關鍵字,部分常用關鍵字參見表五 |
| 表四:arrowprops 包含鍵 arrowstyle 時的取值 |
| '-' | None |
| '->' | head_length=0.4,head_width=0.2 |
| '-[' | widthB=1.0,lengthB=0.2,angleB=None |
| ']-' | widthA=1.0, lengthA=0.2, angleA=None |
| ]-[ | widthA=1.0, lengthA=0.2, angleA=None, widthB=1.0, lengthB=0.2, angleB=None |
| '|-|' | widthA=1.0,widthB=1.0 |
| '-|>' | head_length=0.4,head_width=0.2 |
| '<-' | head_length=0.4,head_width=0.2 |
| '<->' | head_length=0.4,head_width=0.2 |
| '<|-' | head_length=0.4,head_width=0.2 |
| '<|-|>' | head_length=0.4,head_width=0.2 |
| 'fancy' | head_length=0.4,head_width=0.4,tail_width=0.4 |
| 'simple' | head_length=0.5,head_width=0.5,tail_width=0.2 |
| 'wedge' | tail_width=0.3,shrink_factor=0.5 |
| 表五:matplotlib.patches.FancyArrowPatch 常用的鍵 |
| arrowstyle | 箭頭樣式,取值參見表四 |
| connectionstyle | 連接方式,默認為 arc3,有以下五種取值: angle:angleA=90, angleB=0, rad=0.0 angle3:angleA=90, angleB=0 arc:angleA=0, angleB=0, armA=None, armB=None, rad=0.0 arc3:rad=0.0 bar:armA=0.0, armB=0.0, fraction=0.3, angle=None angle 為箭頭旋轉的角度,rad 為弧度 |
| relpos | 箭頭起始點相對注釋文本的位置,默認為 (0.5, 0.5),即文本的中心 (0,0)表示左下角,(1,1)表示右上角 |
| patchA | 箭頭起點處的圖形,默認為文本的邊框 |
| patchB | 箭頭終點處的圖形,默認為空 |
| shrinkA | 箭頭起點的縮進點數,默認為2 |
| shrinkB | 箭頭終點的縮進點數,默認為2 |
| ? | 其他鍵值,參見官方文檔 matplotlib.patches.PathPatch |
| connectionstyle 樣式舉例 |
應用舉例:
import numpy as np import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['Microsoft YaHei']x = np.arange(-2*np.pi, 2*np.pi, 0.01) y1 = np.sin(3*x)/x y2 = np.sin(2*x)/x y3 = np.sin(1*x)/x plt.title('線性圖顯示文本注釋示例') plt.xlabel('x 軸') plt.ylabel('y 軸')plt.plot(x, y1, '--r', label='sin(3*x)/x') plt.plot(x, y2, color='green', linestyle=':', label='sin(2*x)/x') plt.plot(x, y3, label='sin(1*x)/x') plt.legend(edgecolor='#87A3CC', facecolor='#F5F5F5')plt.xticks((-2*np.pi, -np.pi, 0, np.pi, 2*np.pi), (r'$-2\pi$', r'$-\pi$', '$0$', r'$\pi$', r'$2\pi$')) plt.yticks((-1, 0, 1, 2, 3))ax = plt.gca() # 獲取當前的畫布, gca = get current axes ax.spines['right'].set_visible(False) # 獲取繪圖區的軸對象(spines),設置右邊框不顯示 ax.spines['top'].set_visible(False) # 獲取繪圖區的軸對象(spines),設置上邊框不顯示 # ax.spines['right'].set_color('none') # 設置顏色為 none,效果與上面的一致 # ax.spines['top'].set_color('none')ax.spines['left'].set_position(('data', 0)) # 設置兩個坐標軸在(0, 0)位置相交 ax.spines['bottom'].set_position(('data', 0)) ax.xaxis.set_ticks_position('bottom') # 設置 x 坐標軸標簽的位置 ax.yaxis.set_ticks_position('left') # 設置 y 坐標軸標簽的位置plt.annotate(r'$\lim_{x\to 0}\frac{\sin(x)}{x}=1$', # 插入 LaTeX 表達式xy=[0, 1], # 被標記的坐標xycoords='data', # 被標記的坐標的參考系xytext=[30, 30], # 注釋文本的坐標textcoords='offset points', # 注釋文本的坐標的參考系fontsize=16, # 字體大小arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=.2")) # 箭頭樣式plt.show()這里是一段防爬蟲文本,請讀者忽略。 本文原創首發于 CSDN,作者 TRHX。 博客首頁:https://itrhx.blog.csdn.net/ 本文鏈接:https://itrhx.blog.csdn.net/article/details/105839855 未經授權,禁止轉載!惡意轉載,后果自負!尊重原創,遠離剽竊!
總結
以上是生活随笔為你收集整理的Python 数据分析三剑客之 Matplotlib(四):线性图的绘制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对标苹果!Nothing Phone 1
- 下一篇: 【Python CheckiO 题解】S