Removing lead 0 from matplotlib tag label format

How to change label labels of numeric decimal data (for example, from 0 to 1) as "0", ".1", ".2", and not "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 this eliminates the leading "0" from "0.0" and "0" to "1.0":

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

This is a good start, but I also want to get rid of the prefix "0" to "0.2" and "0.4", etc. How can I do that?

+4
source share
2 answers

Although I'm not sure if this is the best way, you can use matplotlib.ticker.FuncFormatter for 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." (eg, 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 

Now you can use majorFormatter = FuncFormatter(my_formatter) to replace majorFormatter in the question.

Full example

Take a look at the full 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." (eg, 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.

Histogram with modified tick labels.

Please note that the tick marks satisfy the conditions asked in the question.

+8
source

Many of your values ​​are 10.

-one
source

All Articles