Matplotlib: Specify format of floats for tick labels Matplotlib: Specify format of floats for tick labels python-3.x python-3.x

Matplotlib: Specify format of floats for tick labels


See the relevant documentation in general and specifically

from matplotlib.ticker import FormatStrFormatterfig, ax = plt.subplots()ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

enter image description here


If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:

from matplotlib.ticker import StrMethodFormatterplt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal placesplt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places

From the documentation:

class matplotlib.ticker.StrMethodFormatter(fmt)

Use a new-style format string (as used by str.format()) to format the tick.

The field used for the value must be labeled x and the field used for the position must be labeled pos.


The answer above is probably the correct way to do it, but didn't work for me.

The hacky way that solved it for me was the following:

ax = <whatever your plot is> # get the current labels labels = [item.get_text() for item in ax.get_xticklabels()]# Beat them into submission and set them back againax.set_xticklabels([str(round(float(label), 2)) for label in labels])# Show the plot, and go home to family plt.show()