文章目錄
- 1 反轉坐標軸
- 2 繪制雙軸
- 3 設定坐標軸范圍
- 4 設定主副刻度
- 5 設定刻度顯示密度
- 6 設定刻度文本樣式
- 7 設定刻度文本內容
作為Python生態中應用最廣泛的繪圖庫,Matplotlib用起來非常簡單,也很容易上手,不過有些細節想要做得盡善盡美,就需要仔細閱讀它的檔案了,對于初學者來說,反轉坐標軸、繪制雙軸(將兩個動態范圍不同的資料繪制在一張圖上,分別使用兩個不同的坐標軸)有一定難度,改變坐標軸刻度的樣式或內容,更是無從下手,
本文匯總了和軸、刻度相關的七個Matplotlib使用技巧,并給出了實體代碼,
1 反轉坐標軸
使用axes.invert_xaxis() 函式和axes.invert_yaxis() 函式可分別反轉x軸和y軸,這兩個函式均不需要任何引數,下面的例子使用影像繪制函式 imshow() 來演示反轉軸,imshow() 函式通過origin引數實作y軸反轉,這里將其固定為“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("反轉X軸")
ax3.set_title("反轉Y軸")
ax4.set_title("反轉X、Y軸")
plt.show()
反轉軸后的效果如下圖 所示,

2 繪制雙軸
Matplotlib支持在一個子圖上顯示兩個x軸或兩個y軸,使用axes.twinx()函式可顯示雙x軸,使用 axes.twiny() 函式可顯示雙 y 軸,以下代碼演示了使用 axes.twiny() 函式顯示雙 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 設定坐標軸范圍
使用axes.set_xlim(left, right) 和axes.set_ylim(bottom, top) 函式設定x 與y軸的顯示范圍,函式引數分別是能夠顯示的最小值和最大值,如果最大值或最小值為 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()
以上代碼重新設定了子圖坐標軸范圍,效果如下圖所示,左圖縮小了 y 軸的范圍,右圖擴大了 x 軸的范圍,

4 設定主副刻度
主副刻度常用于日期時間軸,如主刻度顯示年份,副刻度顯示月份,非線性的對數軸往往也需要顯示副刻度,Matplotlib提供了4個函式來設定x軸和y軸的主副刻度,
- ax.xaxis.set_major_locator(locator) :用于設定 x 軸主刻度,
- ax.xaxis.set_minor_locator(locator) :用于設定 x 軸副刻度,
- ax.yaxis.set_major_locator(locator) :用于設定 y 軸主刻度,
- ax.yaxis.set_minor_locator(locator) :用于設定 y 軸副刻度,
函式的locator引數實體有兩種,分別是來自ticker和dates兩個子模塊中有關刻度的子類實體,下面的代碼演示了在x軸上設定日期時間相關的主副刻度,
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 設定刻度顯示密度
Matplotlib的ticker子模塊包含的Locator類是所有刻度類的基類,負責根據資料的范圍自動調整視覺間隔以及刻度位置的選擇,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軸刻度自動調整,Y軸設定刻度間隔0.3')
ax2.set_title('X軸設定主刻度間隔3副刻度間隔0.6,Y軸刻度自動調整')
plt.show()
以上代碼創建了兩個子圖,繪圖結果如下圖所示,左圖演示了如何設定 y 軸的主刻度密度,右圖演示了如何設定 x 軸主刻度和副刻度的密度,

6 設定刻度文本樣式
設定刻度文本的顏色、字體、字號或旋轉文本等樣式,需要使用axes.get_xticklabels() 或axes.get_yticklabels() 函式獲取x軸或y軸的文本物件串列,文本物件中包含設定文本大小、顏色、旋轉角度的函式,使用對應函式即可完成設定,
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()
以上代碼設定 x 軸的刻度文本字號大小為 12 號、顏色為藍色,并將刻度文本逆時針旋轉35°,效果如下圖所示,

7 設定刻度文本內容
在有些應用場景中,需要將 x 軸或 x 軸刻度上的文字設定為更有標識意義的內容,使用set_xticklabels( ) 和 set_yticklabels( ) 函式可以替換刻度文本,不過只適用于所有可能的取值都已經顯示在坐標軸上的情況,例如,x 軸對應的是串列[0,1,2,3],共4個取值,顯示的刻度也是4個,此時可以使用 [’ 一季度 ‘,’ 二季度 ‘,’ 三季度 ‘,’ 四季度 '] 替換對應的數值,
Matplotlib 提供了強大的刻度文本格式化功能,ticker.Formatter 作為基類派生出了多種形式的格式化類,FuncFormatter就是其中之一,使用FuncFormatter可以更加靈活地設定刻度文本內容,
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
plt.rcParams['font.sans-serif'] = ['FangSong'] # 設定字體以便正確顯示漢字
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軸的刻度文本格式化為百分之一的精度,并附帶度量單位,繪圖結果如下圖所示,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/275402.html
標籤:AI
上一篇:Android WebView 踩坑日記,字體怎么突然變小了???
下一篇:疑難雜癥:導航裝置的高可用
