如何正确使用FuncFormatter(func)?

时间:2016-11-09 16:16:30

标签: python matplotlib

class matplotlib.ticker.FuncFormatter(func) 该函数应该接受两个输入(刻度值x和位置pos)并返回一个字符串

def millions(x, pos):
    'The two args are the value and tick position'
    return '$%1.1fM' % (x*1e-6)

pos参数怎么了?它甚至没有设置为None。

我添加了print(pos)并得到0 1 2 3 4,当我将鼠标移到图像上时加上很多无。只有我不知道如何处理这些信息。

我见过x is used但不是pos的例子,我不明白它应该如何使用。有人能举个例子吗?感谢

2 个答案:

答案 0 :(得分:3)

Here是Maplotlib文档提供的示例。

from matplotlib.ticker import FuncFormatter
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(4)
money = [1.5e5, 2.5e6, 5.5e6, 2.0e7]


def millions(x, pos):
    'The two args are the value and tick position'
    return '$%1.1fM' % (x*1e-6)

formatter = FuncFormatter(millions)

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.bar(x, money)
plt.xticks(x + 0.5, ('Bill', 'Fred', 'Mary', 'Sue'))
plt.show()

产生

enter image description here

答案 1 :(得分:0)

FuncFormatter为您提供了一种非常灵活的方式来定义自己的(例如动态)刻度标签格式为轴。

您的自定义函数应接受 x pos 参数,其中 pos 是当前正在被标记的刻度号(位置)格式, x 是要(漂亮)打印的实际值。

在这方面,每次生成一个可见的刻度线时都会调用该函数-这就是为什么您总是会得到一系列函数调用,其位置参数从1到轴的最大可见参数数量(包括它们的相应的值)。

尝试运行此示例,并缩放绘图:

from matplotlib.ticker import FuncFormatter
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(4)
y = x**2


def MyTicks(x, pos):
    'The two args are the value and tick position'
    if pos is not None:
        tick_locs=ax.yaxis.get_majorticklocs()      # Get the list of all tick locations
        str_tl=str(tick_locs).split()[1:-1]         # convert the numbers to list of strings
        p=max(len(i)-i.find('.')-1 for i in str_tl) # calculate the maximum number of non zero digit after "."
        p=max(1,p)                                  # make sure that at least one zero after the "." is displayed
        return "pos:{0}/x:{1:1.{2}f}".format(pos,x,p)

formatter = FuncFormatter(MyTicks)

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.plot(x,y,'--o')
plt.show()

结果应如下所示:

Example image