當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Matplotlib.ticker.IndexFormatter用法及代碼示例

Matplotlib是Python中令人驚歎的可視化庫,用於數組的二維圖。 Matplotlib是一個基於NumPy數組的多平台數據可視化庫,旨在與更廣泛的SciPy堆棧配合使用。

matplotlib.ticker.IndexFormatter

這個 matplotlib.ticker.IndexFormatter類是的子類matplotlib.ticker類,用於格式化最接近i-th標簽的位置x,其中i = int(x + 0.5)。 i len(list)的位置帶有0刻度標簽。

用法: class matplotlib.ticker.IndexFormatter(labels)

參數:

  • labels:這是標簽列表。

範例1:



import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib as mpl 
  
   
# create dummy data     
x = ['str{}'.format(k) for k in range(20)] 
y = np.random.rand(len(x)) 
   
# create an IndexFormatter  
# with labels x 
x_fmt = mpl.ticker.IndexFormatter(x) 
   
fig,ax = plt.subplots() 
  
ax.plot(y) 
  
# set our IndexFormatter to be 
# responsible for major ticks 
ax.xaxis.set_major_formatter(x_fmt)

輸出:

範例2:

from matplotlib.ticker import IndexFormatter, IndexLocator 
import pandas as pd 
import matplotlib.pyplot as plt 
  
  
years = range(2015, 2018) 
fields = range(4) 
days = range(4) 
bands = ['R', 'G', 'B'] 
  
index = pd.MultiIndex.from_product( 
    [years, fields], names =['year', 'field']) 
  
columns = pd.MultiIndex.from_product( 
    [days, bands], names =['day', 'band']) 
  
df = pd.DataFrame(0, index = index, columns = columns) 
  
df.loc[(2015, ), (0, )] = 1
df.loc[(2016, ), (1, )] = 1
df.loc[(2017, ), (2, )] = 1
ax = plt.gca() 
plt.spy(df) 
  
xbase = len(bands) 
xoffset = xbase / 2
xlabels = df.columns.get_level_values('day') 
  
ax.xaxis.set_major_locator(IndexLocator(base = xbase, 
                                        offset = xoffset)) 
  
ax.xaxis.set_major_formatter(IndexFormatter(xlabels)) 
  
plt.xlabel('Day') 
ax.xaxis.tick_bottom() 
  
ybase = len(fields) 
yoffset = ybase / 2
ylabels = df.index.get_level_values('year') 
  
ax.yaxis.set_major_locator(IndexLocator(base = ybase,  
                                        offset = yoffset)) 
  
ax.yaxis.set_major_formatter(IndexFormatter(ylabels)) 
  
plt.ylabel('Year') 
  
plt.show()

輸出:




相關用法


注:本文由純淨天空篩選整理自RajuKumar19大神的英文原創作品 Matplotlib.ticker.IndexFormatter class in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。