Search code examples
matplotlibhistogramscientific-notation

How to add scientific labels to histogram plots?


example

I'm trying to print scientific labels above each bar plot, similar to my y-axis that already is set to a scientific notation. I've tried using "{:.2E}".format but that doesnt work as i'm trying to convert an entire array (count). Any ideas?

xx= np.arange(0,10) , labels = [0.2,0.1,0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0]

plt.figure(figsize=(7, 4.5)) , plt.bar(xx, count), plt.xlabel('base.distance') , plt.xticks(xx, labels)

addlabels(xx,count.astype('int32'))

plt.ticklabel_format(axis='y', style='sci', scilimits=(0,0))

plt.ylabel('Count'), plt.title(file), plt.show()


Solution

  • Barplots have a helper function to add labels, which will format them, but the docs for it show an old style of formatting-string (often called printf formatting). If you want all the control of format-strings, you can make a list of labels. Try this:

    import numpy as np
    import matplotlib.pyplot as plt
    import random
    
    xx= np.arange(0,10)
    labels = [0.2,0.1,0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0]
    count = random.sample(range(3000,14000), len(xx))
    
    fig, ax = plt.subplots(figsize=(7, 4.5))
    barplot = ax.bar(xx, count)
    plt.xlabel('base.distance')
    plt.xticks(xx, labels)
    
    #ax.bar_label(barplot) # the whole numbers
    #ax.bar_label(barplot, fmt='%2.1e') #old school
    ax.bar_label(barplot, labels=map(lambda x: '{:.2E}'.format(x), count))
    
    
    plt.ticklabel_format(axis='y', style='sci', scilimits=(0,0))
    
    plt.ylabel('Count')
    plt.show()
    
    

    enter image description here