Radvin
Radvin

Reputation: 163

How to format axes ticks to significant digits in matplotlib

I am wondering if there is any way in matplotlib to control the axes ticks with significant digits, instead of controling by the number of decimals. For instance, the following numbers: 2, 15, 120 should be written as 2.00, 15.0, 120

Upvotes: 1

Views: 13374

Answers (1)

Patrick FitzGerald
Patrick FitzGerald

Reputation: 3630

You can do this by defining a string format specifier and applying it for example to the x-axis tick labels with ax.xaxis.set_major_formatter(format_specifier).

In the following example, the format specifier is {x:9<5.1f} where 9 is the fill character (instead of 0 so as to make the example more clear), < aligns numbers to the left, 5 is the number of characters (digits + decimal point) that remains constant by adding the fill value to the right of the precision limit of .1 for the fixed-point notation f.

import matplotlib.pyplot as plt    # v 3.3.2

x = [2, 15, 120]
y = [0, 0, 0]

fig, ax = plt.subplots(figsize=(8,4))
ax.scatter(x, y)
ax.set_xticks(x)

# Format tick labels by aligning values to the left and filling space beyond
# value precision with nines
ax.xaxis.set_major_formatter('{x:9<5.1f}')

title = 'x-axis values are shown with 4 digits by using the x-axis major formatter'
ax.set_title(title, pad=10)

plt.show()

xaxis_format_specifier

As you can see, there is a decimal point and zero after 120 because .1 is the minimum precision that can be used when displaying decimal points with the fixed-point notation f (that is needed to show the decimals for the smaller values). If you change the precision to .0, the values are shown as integers followed by the fill characters.

If you want to remove that extra zero and decimal point, this can be done by creating the tick labels from the x ticks as shown in the following example. The same values and the same string format specifier are used as before, but this time using 0 as the fill value and then further editing the formatted strings:

fig, ax = plt.subplots(figsize=(8,4))
ax.scatter(x, y)
ax.set_xticks(x)

# Create tick labels by creating and formatting strings using a loop
labels = []
for tick in ax.get_xticks():
    label = f'{tick:0<5.1f}'
    labels.append(label[:-1].rstrip('.'))

# # Create tick labels using a list comprehension
# labels = [f'{tick:0<5.1f}'[:-1].rstrip('.') for tick in ax.get_xticks()]

ax.set_xticklabels(labels)

title = 'x-axis values are shown with 3 digits by creating tick labels from the x ticks'
ax.set_title(title, pad=10)

plt.show()

xaxis_format_labels_from_ticks

Upvotes: 3

Related Questions