如何使用格式化程序在matplotlib中进行自定义标记?

2024-10-03 17:19:21 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用默认的tickformatters(我喜欢并且不想重新创建)来创建自己的自定义tickmarks?我试图解决的问题是,我想对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()

但这不起作用: enter image description here

我理解它为什么不起作用,我正在尝试找出如何实际调用ScalarFormatter,以便获得它将生成的字符串


Tags: 函数posimport程序matplotlibmyformatterplt
3条回答

找到了一个非常好的答案:

class MyFormatter(ScalarFormatter):
    def __call__(self, x, pos=None):
        return super().__call__(x ** 2, pos=pos)

ax.yaxis.set_major_formatter(MyFormatter())

我认为您可以尝试设置:ax.set_xticklabels(),而不必定义一个函数来传递它

定义标签:

labels = x**2  # x is a np.array
ax.set_yticklabels(labels)

使用^{}可以使用函数修改记号的值(而不是位置)

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

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()

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

enter image description here

相关问题 更多 >