# 如何在 matplotlib 中将轴刻度格式化为有效数字

[英]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.我想知道 matplotlib 中是否有任何方法可以用有效数字控制轴刻度，而不是用小数位数控制。 For instance, the following numbers: 2, 15, 120 should be written as 2.00, 15.0, 120例如，以下数字： 2、15、120应写为2.00、15.0、120

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)` .您可以通过定义一个字符串格式说明符并将其应用于例如带有`ax.xaxis.set_major_formatter(format_specifier)`的 x 轴刻度标签来做到这一点。

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` .在以下示例中，格式说明符为`{x:9<5.1f}`其中`9`是填充字符（而不是 0，以便使示例更清晰）， `<`将数字左对齐， `5`是字符数（数字 + 小数点）通过将填充值添加到定点表示法`f`的精度限制`.1`的右侧来保持不变。

``````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'

plt.show()
``````

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).如您所见， `120`后有一个小数点和零，因为`.1`是使用定点表示法`f`显示小数点时可以使用的最小精度（显示较小值的小数点所需的精度）。 If you change the precision to `.0` , the values are shown as integers followed by the fill characters.如果将精度更改为`.0` ，则值将显示为整数，后跟填充字符。

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.如果要删除多余的零和小数点，可以通过从 x 刻度创建刻度标签来完成，如下例所示。 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:与以前一样使用相同的值和相同的字符串格式说明符，但这次使用`0`作为填充值，然后进一步编辑格式化的字符串：

``````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'