如何在python中使用matplotlib.ticker对yaxis进行舍入
我正在尝试使用matplotlib.ticker调整y轴如何在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.
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}'