You can use UliEngineering’s format_value()
to easily make a custom matplotlib tick formatter that formats values with SI-prefixes like k
, M
, G
, T
, …
Formatting the Y axis ticks
The following example formats the Y axis in the Unit J
(Joule). For example, 100000
would be formatted as 100 kJ
.
The formatter function we use is
def format_joules(value, pos=None): return format_value(value, 'J')
In order to set the formatter, function, use
# Set our formatter as Y axis formatter plt.gca().yaxis.set_major_formatter(mtick.FuncFormatter(format_joules))
Example:
import matplotlib.ticker as mtick from UliEngineering.EngineerIO import format_value from matplotlib import pyplot as plt def format_joules(value, pos=None): return format_value(value, 'J') # Set our formatter as Y axis formatter plt.gca().yaxis.set_major_formatter(mtick.FuncFormatter(format_joules))
Formatting the X axis ticks
In order to format the X axis ticks instead, use the same formatter function but activate it using
# Set our formatter as Y axis formatter plt.gca().xaxis.set_major_formatter(mtick.FuncFormatter(format_joules))
How to set the number of decimal places
UliEngineering’s format_value()
allows you set the decimal places using e.g. significant_digits=4
def format_joules(value, pos=None): return format_value(value, 'J', significant_digits=4)
Full example
This example generates the Y axis plot shown above
import matplotlib.ticker as mtick from UliEngineering.EngineerIO import format_value from matplotlib import pyplot as plt plt.style.use("ggplot") import numpy as np def format_joules(value, pos=None): return format_value(value, 'J') # Set our formatter as Y axis formatter plt.gca().yaxis.set_major_formatter(mtick.FuncFormatter(format_joules)) # Generate test data test_data = np.arange(1, 1.2e6) plt.plot(test_data) plt.gcf().set_size_inches(10,5) plt.savefig("/ram/mpl-si-formatter.svg")