Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中使用matplotlib.ticker对yaxis进行舍入_Python_Matplotlib - Fatal编程技术网

如何在python中使用matplotlib.ticker对yaxis进行舍入

如何在python中使用matplotlib.ticker对yaxis进行舍入,python,matplotlib,Python,Matplotlib,我正在尝试使用matplotlib.ticker调整y轴 import matplotlib.ticker as tkr ax.yaxis.set_major_formatter(tkr.FuncFormatter(round(y))) y轴的值是10000,20000,30000,40000,50000,我想把它改成10,20,30,40,50。 我无法调整原始数据,因为我直接从数据库获取 我试图使用matplotlib.ticker对数字进行四舍五入 import matplotlib.

我正在尝试使用matplotlib.ticker调整y轴

import matplotlib.ticker as tkr

ax.yaxis.set_major_formatter(tkr.FuncFormatter(round(y)))
y轴的值是10000,20000,30000,40000,50000,我想把它改成10,20,30,40,50。 我无法调整原始数据,因为我直接从数据库获取

我试图使用matplotlib.ticker对数字进行四舍五入

import matplotlib.ticker as tkr

ax.yaxis.set_major_formatter(tkr.FuncFormatter(round(y)))
代码不起作用。
有更好的主意吗?

根据
FuncFormatter
的文档:

class FuncFormatter(Formatter):
    """
    Use a user-defined function for formatting.

    The function should take in two inputs (a tick value ``x`` and a
    position ``pos``), and return a string containing the corresponding
    tick label.
    """
因此,必须传递一个函数,该函数接受值
x
和位置
pos
,并返回包含标签的字符串。在您的示例中,您提供了一个值,因为在计算之前,
round(y)
实际上对
y
中的任何内容进行了取整。也就是说,您没有传递函数。您可以在不带括号的情况下传递
round
,但这不起作用,因为它不是为此而构建的。最简单的方法是使用lambda函数

import matplotlib.pyplot as plt
import matplotlib.ticker as tkr

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 3, 4])

ax.set_xticks([0.997, 2.01, 3.23]) # Ugly ticks
ax.xaxis.set_major_formatter(   
    tkr.FuncFormatter(lambda x, _: f'{round(x)}') # rounds them nicely back to 1, 2, 3
)
请注意,我是如何用
\uu
忽略该位置的,因为它与标签无关

在您的情况下,如果要将
10000
减少到
10
,则在lambda表达式
f'{x/1000}'