Displaying first decimal digit in scientific notation in Matplotlib

前端 未结 3 1608
独厮守ぢ
独厮守ぢ 2021-01-22 12:56

I am currently generating different figures with a scientific notation for the y-axis leading to ticks like 2 or 6 on some plots, but 2.5 or 8.9 on some others. I would like to

3条回答
  •  长情又很酷
    2021-01-22 13:54

    The ScalarFormatter does not currently support custom formats for the ticks, such as setting numbers of decimals. However you can extend the class, so to force it to use a format that you specify. Here is an example:

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.ticker import ScalarFormatter
    
    class ScalarFormatterForceFormat(ScalarFormatter):
        def _set_format(self):  # Override function that finds format to use.
            self.format = "%1.1f"  # Give format here
    
    plt.plot(np.arange(1, 10), np.arange(1, 10)**5)
    ax = plt.gca()
    yfmt = ScalarFormatterForceFormat()
    yfmt.set_powerlimits((0,0))
    gca().yaxis.set_major_formatter(yfmt)
    plt.show()
    

    Here is how it will look.

提交回复
热议问题