当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。