Matplotlib控制坐標(biāo)軸刻度間距與標(biāo)簽實(shí)例代碼
我們首先來介紹坐標(biāo)軸的范圍,坐標(biāo)軸的范圍很好理解,有的時(shí)候我們產(chǎn)出的數(shù)據(jù)的范圍可能并不是完全我們想要的。
如果我們不對(duì)坐標(biāo)軸的范圍進(jìn)行設(shè)置的話,那么matplotlib默認(rèn)會(huì)按照我們數(shù)據(jù)的范圍來自動(dòng)選擇它認(rèn)為最合適的區(qū)間來展示所有的數(shù)據(jù)。
控制刻度間距
目前為止,我們讓Matplotlib自動(dòng)處理刻度在坐標(biāo)軸上的位置,但有時(shí)我們需要覆蓋默認(rèn)的坐標(biāo)軸刻度配置,以便更加快速估計(jì)圖形中點(diǎn)的坐標(biāo)。
import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker x = np.linspace(-20, 20, 1024) y = np.sinc(x) ax = plt.axes() ax.xaxis.set_major_locator(ticker.MultipleLocator(5)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(1)) plt.plot(x, y, c = 'm') plt.show()
以上代碼,強(qiáng)制水平刻度每隔5個(gè)單位步長呈現(xiàn)一次。此外,我們還添加了副刻度,副刻度的間隔為1個(gè)單位步長,步驟說明如下:
- 首先實(shí)例化一個(gè)Axes對(duì)象——用于管理圖形中的坐標(biāo)軸:ax=plot.Axes()。
- 然后使用Locator實(shí)例設(shè)置x軸(ax.xaxis)或y軸(ax.yaxis)的主刻度和副刻度。
也為副刻度添加輔助網(wǎng)格:
import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker x = np.linspace(-20, 20, 1024) y = np.sinc(x) ax = plt.axes() ax.xaxis.set_major_locator(ticker.MultipleLocator(5)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(1)) plt.grid(True, which='both', ls='dashed') plt.plot(x, y, c = 'm') plt.show()
Tips:我們已經(jīng)知道,可以使用plt.grid()添加輔助網(wǎng)格,但此函數(shù)還有一個(gè)可選參數(shù)which,它具有三個(gè)可選值:"minor"、"major"和"both",分別用于僅顯示副刻度、僅顯示主刻度、主副刻度同時(shí)顯示。
控制刻度標(biāo)簽
是時(shí)候介紹刻度標(biāo)簽的設(shè)置了,刻度標(biāo)簽是圖形空間中的坐標(biāo),雖然數(shù)字刻度標(biāo)簽對(duì)于大多說場景來說是足夠的,但是卻并不總是能夠滿足需求。例如,我們需要顯示100個(gè)公司的營收情況,這時(shí)候我們就需要橫坐標(biāo)刻度標(biāo)簽為公司名,而非數(shù)字;同樣對(duì)于時(shí)間序列,我們希望橫坐標(biāo)刻度標(biāo)簽為日期...??紤]到此類需求,我們需要使用Matplotlib為此提供了的API控制刻度標(biāo)簽。
可以按以下步驟為任何Matplotlib圖形設(shè)置刻度標(biāo)簽:
import numpy as np import matplotlib.ticker as ticker import matplotlib.pyplot as plt name_list = ('Apple', 'Orange', 'Banana', 'Pear', 'Mango') value_list = np.random.randint(0, 99, size = len(name_list)) pos_list = np.arange(len(name_list)) ax = plt.axes() ax.xaxis.set_major_locator(ticker.FixedLocator((pos_list))) ax.xaxis.set_major_formatter(ticker.FixedFormatter((name_list))) plt.bar(pos_list, value_list, color = 'c', align = 'center') plt.show()
Tips:我們首先使用ticker.Locator實(shí)例來生成刻度的位置,然后使用ticker.Formatter實(shí)例將為刻度生成標(biāo)簽。FixedFormatter從字符串列表中獲取標(biāo)簽,然后用Formatter實(shí)例設(shè)置坐標(biāo)軸。同時(shí),我們還使用了FixedLocator來確保每個(gè)標(biāo)簽中心都正好與刻度中間對(duì)齊。
更簡單的設(shè)置方式
雖然使用上述方法可以控制刻度標(biāo)簽,但可以看出此方法過于復(fù)雜,如果刻度標(biāo)簽是固定的字符列表,那么可以用以下簡單的設(shè)置方法:
import numpy as np import matplotlib.pyplot as plt name_list = ('Apple', 'Orange', 'Banana', 'Pear', 'Mango') value_list = np.random.randint(0, 99, size = len(name_list)) pos_list = np.arange(len(name_list)) plt.bar(pos_list, value_list, color = 'c', align = 'center') plt.xticks(pos_list, name_list) plt.show()
Tips:使用plt.xticks()函數(shù)為一組固定的刻度提供固定標(biāo)簽,此函數(shù)接受位置列表和名稱列表作為參數(shù)值,可以看出,此方法比第一種方法實(shí)現(xiàn)起來更簡單。
高級(jí)刻度標(biāo)簽控制
不僅可以使用固定標(biāo)簽,使用ticker API可以使用函數(shù)生成的標(biāo)簽:
import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker def make_label(value, pos): return '%0.1f%%' % (100. * value) ax = plt.axes() ax.xaxis.set_major_formatter(ticker.FuncFormatter(make_label)) x = np.linspace(0, 1, 256) plt.plot(x, np.exp(-10 * x), c ='c') plt.plot(x, np.exp(-5 * x), c= 'c', ls = '--') plt.show()
在此示例中,刻度標(biāo)簽是由自定義函數(shù)make_label生成的。此函數(shù)以刻度的坐標(biāo)作為輸入,并返回一個(gè)字符串作為坐標(biāo)標(biāo)簽,這比給出固定的字符串列表更靈活。為了使用自定義函數(shù),需要使用FuncFormatter實(shí)例——一個(gè)以函數(shù)為參數(shù)的格式化實(shí)例。
這種將生成標(biāo)簽的實(shí)際任務(wù)指派給其他函數(shù)的方法稱為委托(delegation)模式,這是一種漂亮的編程技術(shù)。比方說,我們要將每個(gè)刻度顯示為日期,這可以使用標(biāo)準(zhǔn)的Python時(shí)間和日期函數(shù)完成:
import numpy as np import datetime import matplotlib.pyplot as plt import matplotlib.ticker as ticker start_date = datetime.datetime(1998, 1, 1) def make_label(value, pos): time = start_date + datetime.timedelta(days = 365 * value) return time.strftime('%b %y') ax = plt.axes() ax.xaxis.set_major_formatter(ticker.FuncFormatter(make_label)) x = np.linspace(0, 1, 256) plt.plot(x, np.exp(-10 * x), c ='c') plt.plot(x, np.exp(-5 * x), c= 'c', ls = '--') labels = ax.get_xticklabels() plt.setp(labels, rotation = 30.) plt.show()
Tips:可以利用ax.get_xticklabels()獲取刻度標(biāo)簽實(shí)例,然后對(duì)標(biāo)簽進(jìn)行旋轉(zhuǎn),以避免長標(biāo)簽之間重疊,旋轉(zhuǎn)使用plt.setp()函數(shù),其接受刻度標(biāo)簽實(shí)例和旋轉(zhuǎn)角度作為參數(shù)值。
總結(jié)
到此這篇關(guān)于Matplotlib控制坐標(biāo)軸刻度間距與標(biāo)簽的文章就介紹到這了,更多相關(guān)Matplotlib控制坐標(biāo)軸刻度間距內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。