从 matplotlib 刻度标签格式中删除前导 0 [英] removing leading 0 from matplotlib tick label formatting
问题描述
如何在 matplotlib 中将数字十进制数据(例如 0 和 1 之间)的刻度标签更改为0"、.1"、.2"而不是0.0"、0.1"、0.2"?例如,
How can I change the ticklabels of numeric decimal data (say between 0 and 1) to be "0", ".1", ".2" rather than "0.0", "0.1", "0.2" in matplotlib? For example,
hist(rand(100))
xticks([0, .2, .4, .6, .8])
会将标签的格式设置为"0.0","0.2"等.我知道这可以摆脱"0.0"中的前导"0"和"1.0"中的尾随"0":
will format the labels as "0.0", "0.2", etc. I know that this gets rid of the leading "0" from "0.0" and the trailing "0" on "1.0":
from matplotlib.ticker import FormatStrFormatter
majorFormatter = FormatStrFormatter('%g')
myaxis.xaxis.set_major_formatter(majorFormatter)
这是一个好的开始,但是我也想摆脱"0.2"和"0.4"等上的"0"前缀,这怎么办?
That's a good start, but I also want to get rid of the "0" prefix on "0.2" and "0.4", etc. How can this be done?
推荐答案
Although I am not sure it is the best way, you can use a matplotlib.ticker.FuncFormatter
to do this. For example, define the following function.
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
.
Now, you can use majorFormatter = FuncFormatter(my_formatter)
to replace the majorFormatter
in the question.
让我们看一个完整的例子.
Let's look at a complete example.
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()
运行此代码会生成以下直方图.
Running this code generates the following histogram.
注意刻度标签满足问题中要求的条件.
Notice the tick labels satisfy the conditions requested in the question.
这篇关于从 matplotlib 刻度标签格式中删除前导 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!