![](/img/trans.png)
[英]Wrong values appears… using python matplotlib.ticker (ax.xaxis.set_major_locator)
[英]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.