首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何正确使用函数(FuncFormatter)?

如何正确使用函数(FuncFormatter)?
EN

Stack Overflow用户
提问于 2016-11-10 00:16:30
回答 2查看 16.7K关注 0票数 14

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

代码语言:javascript
运行
复制
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的例子,我不明白它是如何使用的。谁能给我举个例子?谢谢

EN

回答 2

Stack Overflow用户

发布于 2016-11-10 00:23:53

Here是Maplotlib文档提供的一个示例。

代码语言:javascript
运行
复制
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()

它会产生

票数 11
EN

Stack Overflow用户

发布于 2019-10-23 23:28:58

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

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

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

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

代码语言:javascript
运行
复制
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()

结果应该如下所示:

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40511476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档