Matplotlib的反轉(zhuǎn)軸、繪制雙軸和定制刻度詳解
Matplotlib
作為Python生態(tài)中應(yīng)用最廣泛的繪圖庫,Matplotlib用起來非常簡單,也很容易上手。
不過有些細節(jié)想要做得盡善盡美,就需要仔細閱讀它的文檔了。
對于初學者來說,反轉(zhuǎn)坐標軸、繪制雙軸(將兩個動態(tài)范圍不同的數(shù)據(jù)繪制在一張圖上,分別使用兩個不同的坐標軸)有一定難度,改變坐標軸刻度的樣式或內(nèi)容,更是無從下手。
本文匯總了和軸、刻度相關(guān)的七個Matplotlib使用技巧,并給出了實例代碼。
1 反轉(zhuǎn)坐標軸
使用axes.invert_xaxis() 函數(shù)和axes.invert_yaxis() 函數(shù)可分別反轉(zhuǎn)x軸和y軸。
這兩個函數(shù)均不需要任何參數(shù)。下面的例子使用圖像繪制函數(shù) imshow() 來演示反轉(zhuǎn)軸。
imshow() 函數(shù)通過origin參數(shù)實現(xiàn)y軸反轉(zhuǎn),這里將其固定為“lower”。
import numpy as np from matplotlib import pyplot as plt plt.rcParams['font.sans-serif'] = ['FangSong'] plt.rcParams['axes.unicode_minus'] = False y, x = np.mgrid[-2:2:200j, -3:3:300j] z = np.exp(-x**2-y**2) - np.exp(-(x-1)**2-(y-1)**2) fig = plt.figure() ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) ax1.imshow(z, cmap='jet', origin='lower') ax2.imshow(z, cmap='jet', origin='lower') ax3.imshow(z, cmap='jet', origin='lower') ax4.imshow(z, cmap='jet', origin='lower') ax2.invert_xaxis() ax3.invert_yaxis() ax4.invert_xaxis() ax4.invert_yaxis() ax1.set_title("正常的X、Y軸") ax2.set_title("反轉(zhuǎn)X軸") ax3.set_title("反轉(zhuǎn)Y軸") ax4.set_title("反轉(zhuǎn)X、Y軸") plt.show()
反轉(zhuǎn)軸后的效果如下圖 所示。
2 繪制雙軸
Matplotlib支持在一個子圖上顯示兩個x軸或兩個y軸。
使用axes.twinx()函數(shù)可顯示雙x軸,使用 axes.twiny() 函數(shù)可顯示雙 y 軸。
以下代碼演示了使用 axes.twiny() 函數(shù)顯示雙 y 軸。
import numpy as np from matplotlib import pyplot as plt plt.rcParams['font.sans-serif'] = ['FangSong'] plt.rcParams['axes.unicode_minus'] = False x = np.linspace(-2*np.pi, 2*np.pi, 200) y1 = np.square(x) y2 = np.cos(x) fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax_twinx = ax.twinx() ax.plot(x, y1, c='r') ax_twinx.plot(x, y2, c='g', ls='-.') plt.show()
效果如下圖所示。
3 設(shè)置坐標軸范圍
使用axes.set_xlim(left, right) 和axes.set_ylim(bottom, top) 函數(shù)設(shè)置x 與y軸的顯示范圍。
函數(shù)參數(shù)分別是能夠顯示的最小值和最大值,如果最大值或最小值為 None,則表示只限制坐標軸一端的值域范圍。
import numpy as np from matplotlib import pyplot as plt x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) fig = plt.figure() ax1 = fig.add_subplot(121) ax1.plot(x, y, c='r') ax1.set_ylim(-0.8, 0.8) ax2 = fig.add_subplot(122) ax2.plot(x, y, c='g') ax2.set_xlim(-np.pi, 3*np.pi) plt.show()
以上代碼重新設(shè)置了子圖坐標軸范圍,效果如下圖所示。左圖縮小了 y 軸的范圍,右圖擴大了 x 軸的范圍。
4 設(shè)置主副刻度
主副刻度常用于日期時間軸,如主刻度顯示年份,副刻度顯示月份。
非線性的對數(shù)軸往往也需要顯示副刻度。
Matplotlib提供了4個函數(shù)來設(shè)置x軸和y軸的主副刻度。
- ax.xaxis.set_major_locator(locator) :用于設(shè)置 x 軸主刻度。
- ax.xaxis.set_minor_locator(locator) :用于設(shè)置 x 軸副刻度。
- ax.yaxis.set_major_locator(locator) :用于設(shè)置 y 軸主刻度。
- ax.yaxis.set_minor_locator(locator) :用于設(shè)置 y 軸副刻度。
函數(shù)的locator參數(shù)實例有兩種,分別是來自ticker和dates兩個子模塊中有關(guān)刻度的子類實例。
下面的代碼演示了在x軸上設(shè)置日期時間相關(guān)的主副刻度。
import numpy as np from matplotlib import pyplot as plt import matplotlib.dates as mdates x = np.arange('2019-01', '2019-06', dtype='datetime64[D]') y = np.random.rand(x.shape[0]) fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.plot(x, y, c='g') ax.xaxis.set_major_locator(mdates.MonthLocator()) ax.xaxis.set_major_formatter(mdates.DateFormatter('\n%Y-%m-%d')) ax.xaxis.set_minor_locator(mdates.DayLocator(bymonthday=(1,11,21))) ax.xaxis.set_minor_formatter(mdates.DateFormatter('%d')) plt.show()
效果如下圖所示。
5 設(shè)置刻度顯示密度
Matplotlib的ticker子模塊包含的Locator類是所有刻度類的基類,負責根據(jù)數(shù)據(jù)的范圍自動調(diào)整視覺間隔以及刻度位置的選擇。
MultipleLocator是Locator的派生類,能夠控制刻度的疏密。
import numpy as np from matplotlib import pyplot as plt from matplotlib.ticker import MultipleLocator plt.rcParams['font.sans-serif'] = ['FangSong'] plt.rcParams['axes.unicode_minus'] = False x = np.linspace(0, 4*np.pi, 500) fig = plt.figure() ax1 = fig.add_subplot(121) ax1.plot(x, np.sin(x), c='m') ax1.yaxis.set_major_locator(MultipleLocator(0.3)) ax2 = fig.add_subplot(122) ax2.plot(x, np.sin(x), c='m') ax2.xaxis.set_major_locator(MultipleLocator(3)) ax2.xaxis.set_minor_locator(MultipleLocator(0.6)) ax1.set_title('X軸刻度自動調(diào)整,Y軸設(shè)置刻度間隔0.3') ax2.set_title('X軸設(shè)置主刻度間隔3副刻度間隔0.6,Y軸刻度自動調(diào)整') plt.show()
以上代碼創(chuàng)建了兩個子圖,繪圖結(jié)果如下圖所示,左圖演示了如何設(shè)置 y 軸的主刻度密度,右圖演示了如何設(shè)置 x 軸主刻度和副刻度的密度。
6 設(shè)置刻度文本樣式
設(shè)置刻度文本的顏色、字體、字號或旋轉(zhuǎn)文本等樣式,需要使用axes.get_xticklabels() 或axes.get_yticklabels() 函數(shù)獲取x軸或y軸的文本對象列表。
文本對象中包含設(shè)置文本大小、顏色、旋轉(zhuǎn)角度的函數(shù),使用對應(yīng)函數(shù)即可完成設(shè)置。
import numpy as np from matplotlib import pyplot as plt import matplotlib.dates as mdates x = np.arange('2019-01', '2020-01', dtype='datetime64[D]') y = np.random.rand(x.shape[0]) fig = plt.figure() ax = fig.add_axes([0.1, 0.3, 0.8, 0.6]) ax.plot(x, y, c='g') ax.xaxis.set_major_locator(mdates.MonthLocator()) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d')) for lobj in ax.get_xticklabels(): lobj.set_rotation(35) lobj.set_size(12) lobj.set_color('blue') plt.show()
以上代碼設(shè)置 x 軸的刻度文本字號大小為 12 號、顏色為藍色,并將刻度文本逆時針旋轉(zhuǎn)35°,效果如下圖所示。
7 設(shè)置刻度文本內(nèi)容
在有些應(yīng)用場景中,需要將 x 軸或 x 軸刻度上的文字設(shè)置為更有標識意義的內(nèi)容。
使用set_xticklabels( ) 和 set_yticklabels( ) 函數(shù)可以替換刻度文本,不過只適用于所有可能的取值都已經(jīng)顯示在坐標軸上的情況。
例如,x 軸對應(yīng)的是列表[0,1,2,3],共4個取值,顯示的刻度也是4個,此時可以使用 [’ 一季度 ‘,’ 二季度 ‘,’ 三季度 ‘,’ 四季度 '] 替換對應(yīng)的數(shù)值。
Matplotlib 提供了強大的刻度文本格式化功能,ticker.Formatter 作為基類派生出了多種形式的格式化類,F(xiàn)uncFormatter就是其中之一。
使用FuncFormatter可以更加靈活地設(shè)置刻度文本內(nèi)容。
import numpy as np from matplotlib import pyplot as plt from matplotlib.ticker import FuncFormatter plt.rcParams['font.sans-serif'] = ['FangSong'] # 設(shè)置字體以便正確顯示漢字 plt.rcParams['axes.unicode_minus'] = False # 正確顯示連字符 x = np.linspace(0, 10, 200) y = np.square(x) def func_x(x, pos): return '%0.2f秒'%x def func_y(y, pos): return '%0.2f°C'%y formatter_x = FuncFormatter(func_x) formatter_y = FuncFormatter(func_y) fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.plot(x, y, c='r') ax.xaxis.set_major_formatter(formatter_x) ax.yaxis.set_major_formatter(formatter_y) plt.show()
以上代碼將x軸和y軸的刻度文本格式化為百分之一的精度,并附帶度量單位,繪圖結(jié)果如下圖所示。
到此這篇關(guān)于Matplotlib的反轉(zhuǎn)軸、繪制雙軸和定制刻度詳解的文章就介紹到這了,更多相關(guān)Matplotlib的使用技巧內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Win10里python3創(chuàng)建虛擬環(huán)境的步驟
在本篇文章里小編給大家整理的是一篇關(guān)于Win10里python3創(chuàng)建虛擬環(huán)境的步驟內(nèi)容,需要的朋友們可以學習參考下。2020-01-01python uvloop事件循環(huán)庫使用功能示例探究
這篇文章主要為大家介紹了python uvloop事件循環(huán)庫使用功能示例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01Python3實現(xiàn)的回文數(shù)判斷及羅馬數(shù)字轉(zhuǎn)整數(shù)算法示例
這篇文章主要介紹了Python3實現(xiàn)的回文數(shù)判斷及羅馬數(shù)字轉(zhuǎn)整數(shù)算法,涉及Python數(shù)值運算、轉(zhuǎn)換等相關(guān)操作技巧,需要的朋友可以參考下2019-03-03