去掉matplotlib刻度标签格式中的前导0

6 投票
2 回答
4094 浏览
提问于 2025-04-17 08:36

我想知道怎么把数字数据(比如在0到1之间的数)在matplotlib中显示成“0”、“0.1”、“0.2”,而不是“0.0”、“0.1”、“0.2”。比如说,

hist(rand(100))
xticks([0, .2, .4, .6, .8])

这样会把标签格式化成“0.0”、“0.2”等等。我知道这样可以去掉“0.0”前面的“0”和“1.0”后面的“0”:

from matplotlib.ticker import FormatStrFormatter
majorFormatter = FormatStrFormatter('%g')
myaxis.xaxis.set_major_formatter(majorFormatter) 

这已经是个不错的开始了,但我还想去掉“0.2”、“0.4”等等前面的“0”。这该怎么做呢?

2 个回答

-3

把你所有的数值都乘以10。

13

虽然我不确定这是不是最好的方法,但你可以使用matplotlib.ticker.FuncFormatter来实现这个功能。比如,你可以定义一个这样的函数。

def my_formatter(x, pos):
    """Format 1 as 1, 0 as 0, and all values whose absolute values is between
    0 and 1 without the leading "0." (e.g., 0.7 is formatted as .7 and -0.4 is
    formatted as -.4)."""
    val_str = '{:g}'.format(x)
    if np.abs(x) > 0 and np.abs(x) < 1:
        return val_str.replace("0", "", 1)
    else:
        return val_str

现在,你可以用majorFormatter = FuncFormatter(my_formatter)来替换问题中的majorFormatter

完整示例

接下来,我们来看一个完整的示例。

from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np

def my_formatter(x, pos):
    """Format 1 as 1, 0 as 0, and all values whose absolute values is between
    0 and 1 without the leading "0." (e.g., 0.7 is formatted as .7 and -0.4 is
    formatted as -.4)."""
    val_str = '{:g}'.format(x)
    if np.abs(x) > 0 and np.abs(x) < 1:
        return val_str.replace("0", "", 1)
    else:
        return val_str

# Generate some data.
np.random.seed(1) # So you can reproduce these results.
vals = np.random.rand((1000))

# Set up the formatter.
major_formatter = FuncFormatter(my_formatter)

plt.hist(vals, bins=100)
ax = plt.subplot(111)
ax.xaxis.set_major_formatter(major_formatter)
plt.show()

运行这段代码会生成下面这个直方图。

带有修改过的刻度标签的直方图。

注意,刻度标签满足了问题中要求的条件。

撰写回答