Search code examples
pythonmatplotlibplotaxis-labels

Python: change labels of a plot using matplotlib


I want to change the labels of a plot

fig=figure(figsize=(7.5,7.5))
labels = [0,0.00001,0.0001,0.001,0.01,0.1,1]
plt.xscale('log')
plt.xlim(10^-6,1.1) 
plt.xticks(y, labels)

enter image description here

However I would like to have the labels in the format 10^-5, 10^-4, 10^-3, 10^-2, 10^-1, 1 instead of 1e-05, 0.0001, 0,001, 0,01, 0.1, 1


Solution

  • You need this FormatStrFormatter('%.2e')

    Since you didn't post your whole script I can only show you an example:

    If we take this demo from matplolib

    Simply change majorFormatter = FormatStrFormatter('%d') to what I showed you earlier and you'll see

    enter image description here

    You'll simply reformat the major axis to:

    ax.xaxis.set_major_formatter(FormatStrFormatter('%.2e'))