我如何使用默认的 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 以便我可以获得它会生成的字符串。
使用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 将处理定位。
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |