Adjust exponent text after setting scientific limits on matplotlib axis

后端 未结 5 982
旧时难觅i
旧时难觅i 2020-12-05 16:13

At the moment if I set matplotlib y axis ticklabels to scientific mode it gives me an exponent at the top of the y axis of the form 1e-5

I\'d like to ad

5条回答
  •  [愿得一人]
    2020-12-05 17:00

    You get offset and set the text value but there doesn't seem to be a way to actually apply this to the axis... Even calling ax.yaxis.offsetText.set_text(offset) doesn't update the offset displayed. A work around it to remove the offset text and replace with brackets on the axis label,

    ax.yaxis.offsetText.set_visible(False)
    ax.set_ylabel("datalabel " +  r'$\left(\mathregular{10^{-5}}\right)$')
    

    Or replace it with a manual text box, as a minimal example,

    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Create a figure and axis
    fig, ax = plt.subplots()
    mpl.rc('text', usetex = True)
    
    # Plot 100 random points 
    # the y values of which are very small
    large = 100000.0
    x = np.random.rand(100)
    y = np.random.rand(100)/large
    
    ax.scatter(x,y)
    
    # Set the y limits appropriately
    ax.set_ylim(0, 1/large)
    
    # Change the y ticklabel format to scientific format
    ax.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))
    
    #print(ax.yaxis.offsetText.get_position())
    ax.yaxis.offsetText.set_visible(False)
    ax.text(-0.21, 1.01/large, r'$\mathregular{10^{-2}}$')
    
    # And show the figure
    plt.show()
    

    I know this isn't ideal but it may be that offset text cannot be changed manually or can only be the consistent with the numerical values...

提交回复
热议问题