Python 正在从matplotlib记号标签格式中删除前导0
如何在matplotlib中将数字十进制数据(例如0和1之间)的标签更改为“0”、“0.1”、“0.2”,而不是“0.0”、“0.1”、“0.2”?比如说,Python 正在从matplotlib记号标签格式中删除前导0,python,plot,matplotlib,Python,Plot,Matplotlib,如何在matplotlib中将数字十进制数据(例如0和1之间)的标签更改为“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”: 这是一个很好的开始,但我还想去掉“0.2”和“0.4”等上的“0”前缀。如何做到这一点?将所有值乘以10。虽然我不确定这是最好的方法,但您可以使
hist(rand(100))
xticks([0, .2, .4, .6, .8])
将标签的格式设置为“0.0”、“0.2”等。我知道这将去掉“0.0”的前导“0”和“1.0”的尾随“0”:
这是一个很好的开始,但我还想去掉“0.2”和“0.4”等上的“0”前缀。如何做到这一点?将所有值乘以10。虽然我不确定这是最好的方法,但您可以使用a来做到这一点。例如,定义以下函数
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
运行此代码将生成以下直方图
请注意,勾号标签满足问题中要求的条件
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
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()