Home > Software engineering >  matplotlib pyplot display ticks and values which are in scientific form
matplotlib pyplot display ticks and values which are in scientific form

Time:12-15

I have a plot which looks like this:

enter image description here The values displayed on the blue line are the cost ratio.

The corresponding code looks like this:

    fpr=[some values]
    tpr=[some values]
    CR = 
    plt.plot(tpr,fpr)
    plt.plot(x,y)
    plt.plot(*intersection.xy, 'ro')
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.legend(["Cost Ratio"])
    for x,y,z in zip(tpr,fpr,CR):
        label = "{:.2f}".format(z) 
        plt.annotate(label, # this is the text
                     (x,y),annotation_clip=True, # these are the coordinates to position the label
                     textcoords="offset points", # how to position the text
                     xytext=(0,10), # distance from text to points (x,y)
                     ha='center') # horizontal alignment can be left, right or center
    
    
    plt.show()

The cost ratio values are :

[3.436400227231698e-11
6.872800454463395e-11
1.374560090892679e-10
2.749120181785358e-10
5.498240363570716e-10
1.0996480727141433e-09
2.1992961454282866e-09
4.398592290856573e-09
8.797184581713146e-09
1.7594369163426292e-08
37.7836200753334]

I want to display the following values:

[3.4e-11
6.8e-11
1.3e-10
2.7e-10
5.4e-10
1.0e-09
2.1e-09
4.3e-09
8.7e-09
1.7e-08
37.7]

CodePudding user response:

When you use label = "{:.2f}".format(z), the .2f refers to fixed point notation with two decimals. This gives you 0.00 when your small numbers are presented with two decimals.

For scientific notation with one decimal, you need to use .1e, that is label = "{:.1e}".format(z). This will give you the numbers you want to display.

Note that this will not work for 37.7 as the scientific notation with 1 decimal of this number will be 3.8e 01. You could use an if/else to apply the scientific notation to all the numbers but 37.7.

The different string format types are found in the documentation here.

  • Related