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])
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)
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.FuncFormatterto do this. For example, define the following function.Now, you can use
majorFormatter = FuncFormatter(my_formatter)to replace themajorFormatterin the question.Complete example
Let’s look at a complete example.
Running this code generates the following histogram.
Notice the tick labels satisfy the conditions requested in the question.