Home > Article > Backend Development > How to Control the Format of Float Tick Labels in Matplotlib?
To use specific decimal formatting in your tick labels, employ the FormatStrFormatter class. This class takes a string specifying the desired format as an argument. For instance:
<code class="python">from matplotlib.ticker import FormatStrFormatter fig, ax = plt.subplots() ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))</code>
In this example, the format string '%.2f' specifies that tick labels should have two decimal places. See the Matplotlib documentation for further formatting options.
Alternatively, use the ScalarFormatter class with the useOffset and useLocale arguments. useOffset disables scientific notation, while useLocale uses the system's locale settings to determine the formatting style (e.g., decimal separator, thousands separator).
<code class="python">fig, ax = plt.subplots() # Disable scientific notation ax.yaxis.set_major_formatter(ScalarFormatter(useOffset=False, useLocale=False)) # Specify decimal places ax.yaxis.set_major_locator(MultipleLocator(0.5))</code>
To remove decimal digits entirely, set the format string to '%d'. This will display integers without any fractional part:
<code class="python">from matplotlib.ticker import StrMethodFormatter ax.yaxis.set_major_formatter(StrMethodFormatter('{x:.0f}'))</code>
The above is the detailed content of How to Control the Format of Float Tick Labels in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!