虽然我不确定这是最好的方法,但您可以使用matplotlib.ticker.FuncFormatter http://matplotlib.sourceforge.net/api/ticker_api.html#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()
运行此代码会生成以下直方图。
请注意,刻度标签满足问题中要求的条件。