简体   繁体   中英

how to round the yaxis using matplotlib.ticker in python

I am trying to adjust the y-axis using matplotlib.ticker.

The value I've got for y-axis is 10000, 20000, 30000, 40000, 50000 and I want to change it as 10,20,30,40,50. I can not adjust the raw data because I am getting from straight from database.

I tried to round the number using the matplotlib.ticker.

import matplotlib.ticker as tkr

ax.yaxis.set_major_formatter(tkr.FuncFormatter(round(y)))

The code doesn't work. Is there any better idea?

According to the documentation of 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.
    """

So, you have to pass a function that accepts the value x and a position pos and returns a string containing the label. In your example, you provided a value, because round(y) actually rounds whatever is in y before evaluating. That is, you're not passing a function. You could pass round , without parentheses, but that wouldn't work because it wasn't built to do so. The easiest way is to use a 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
)

Note how I ignored the position, with _ , because it's inconsequential to the label.

In your case, if you want to reduce 10000 to 10 , then use in the lambda expression f'{x / 1000}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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