Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show decimal places and scientific notation on the axis of a matplotlib plot

I am plotting some big numbers with matplotlib in a pyqt program using python 2.7. I have a y-axis that ranges from 1e+18 to 3e+18 (usually). I'd like to see each tick mark show values in scientific notation and with 2 decimal places. For example 2.35e+18 instead of just 2e+18 because values between 2e+18 and 3e+18 still read just 2e+18 for a few tickmarks. Here is an example of that problem.

import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(0, 300, 20) y = np.linspace(0,300, 20) y = y*1e16 ax.plot(x,y)   ax.get_xaxis().set_major_formatter(plt.LogFormatter(10,  labelOnlyBase=False)) ax.get_yaxis().set_major_formatter(plt.LogFormatter(10,  labelOnlyBase=False)) plt.show() 
like image 968
tempneff Avatar asked Sep 09 '14 16:09

tempneff


People also ask

How do I use scientific notation in MatPlotLib?

(m, n), pair of integers; if style is 'sci', scientific notation will be used for numbers outside the range 10m to 10n. Use (0,0) to include all numbers. Use (m,m) where m <> 0 to fix the order of magnitude to 10m.

How do I get rid of MatPlotLib scientific notation?

MatPlotLib with Python To prevent scientific notation, we must pass style='plain' in the ticklabel_format method.


1 Answers

This is really easy to do if you use the matplotlib.ticker.FormatStrFormatter as opposed to the LogFormatter. The following code will label everything with the format '%.2e':

import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as mtick  fig = plt.figure()  ax = fig.add_subplot(111)  x = np.linspace(0, 300, 20)  y = np.linspace(0,300, 20) y = y*1e16  ax.plot(x,y)  ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))  plt.show() 

Example plot

like image 64
Ffisegydd Avatar answered Sep 20 '22 07:09

Ffisegydd