如何使用格式化程序在 matplotlib 中制作自定义刻度?

Jas*_*ght 3 python matplotlib

我如何使用默认的 tickformatters(我喜欢并且不想重新创建)来制作我自己的自定义刻度线?我试图解决的问题是我想对 y 轴上的所有数字应用一个函数。

例如,假设我想对所有 y 轴刻度标签进行平方。我不想改变他们的位置或改变底层数据,我只想改变标签。我知道我可以从头开始编写自己的格式化程序,但我更愿意只围绕现有格式化程序编写一个包装器。我试过:

import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

def my_formatter(x,pos):
     return ScalarFormatter(x**2,pos)
    
x = np.arange(10)
y = x
fig, ax = plt.subplots()
plt.plot(x,y)
ax.yaxis.set_major_formatter(plt.FuncFormatter(my_formatter))
plt.show()
Run Code Online (Sandbox Code Playgroud)

但这不起作用: 在此处输入图片说明

我明白为什么它不起作用,我试图弄清楚如何实际调用 ScalarFormatter 以便我可以获得它会生成的字符串。

Ale*_*lex 6

使用mpl.ticker.FuncFormatter它允许您通过函数修改您的报价(而不是位置)的值。

我更喜欢像这样装饰格式化程序:

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

@FuncFormatter
def my_formatter(x, pos):
     return "{}".format(x ** 2)
    
x = np.arange(10)
y = x
fig, ax = plt.subplots()
ax.plot(x, y)

# As we decorated the function we can just use 
#   the function name as the formatter argument

ax.yaxis.set_major_formatter(my_formatter)
plt.show()
Run Code Online (Sandbox Code Playgroud)

您应该从格式化程序返回一个字符串,matplotlib 将处理定位。

在此处输入图片说明