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的例子,我不明白它是如何使用的。谁能给我举个例子?谢谢
发布于 2016-11-10 00:23:53
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()它会产生

发布于 2019-10-23 23:28:58
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()结果应该如下所示:

https://stackoverflow.com/questions/40511476
复制相似问题