JMJ*_*JMJ 13 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)
Run Code Online (Sandbox Code Playgroud)
pos 参数怎么了?它甚至没有设置为无。
当我将鼠标移到图像上时,我添加了 print(pos) 并得到了 0 1 2 3 4,加上很多 None 。只有我不知道如何处理这些信息。
我见过使用 x而不是 pos 的例子,我不明白它应该如何使用。有人可以举个例子吗?谢谢
Spa*_*ine 10
这是 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()
Run Code Online (Sandbox Code Playgroud)
产生
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()
Run Code Online (Sandbox Code Playgroud)
结果应如下所示:
归档时间: |
|
查看次数: |
15282 次 |
最近记录: |