繁体   English   中英

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

[英]how to round the yaxis using matplotlib.ticker in python

我正在尝试使用 matplotlib.ticker 调整 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的 function 和一个 position pos并返回一个包含 label 的字符串。 在您的示例中,您提供了一个值,因为round(y)实际上在评估之前舍入了y中的任何内容。 也就是说,您没有传递 function。 可以传递round ,不带括号,但这行不通,因为它不是为此而构建的。 最简单的方法是使用 lambda function。

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
)

请注意我是如何忽略 position 和_的,因为它与 label 无关。

在您的情况下,如果您想将10000减少到10 ,请在 lambda 表达式中使用f'{x / 1000}'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM