Note

Go to the endto download the full example code.

Evans test#

A mockup "Foo" units class which supports conversion and different tickformatting depending on the "unit". Here the "unit" is just a scalarconversion factor, but this example shows that Matplotlib is entirely agnosticto what kind of units client packages use.

Custom units, default units, xunits = 2.0
importmatplotlib.pyplotaspltimportnumpyasnpimportmatplotlib.tickerastickerimportmatplotlib.unitsasunitsclassFoo:def__init__(self,val,unit=1.0):self.unit=unitself._val=val*unitdefvalue(self,unit):ifunitisNone:unit=self.unitreturnself._val/unitclassFooConverter(units.ConversionInterface):@staticmethoddefaxisinfo(unit,axis):"""Return the Foo AxisInfo."""ifunit==1.0orunit==2.0:returnunits.AxisInfo(majloc=ticker.IndexLocator(8,0),majfmt=ticker.FormatStrFormatter("VAL:%s"),label='foo',)else:returnNone@staticmethoddefconvert(obj,unit,axis):"""        Convert *obj* using *unit*.        If *obj* is a sequence, return the converted sequence.        """ifnp.iterable(obj):return[o.value(unit)foroinobj]else:returnobj.value(unit)@staticmethoddefdefault_units(x,axis):"""Return the default unit for *x* or None."""ifnp.iterable(x):forthisxinx:returnthisx.unitelse:returnx.unitunits.registry[Foo]=FooConverter()# create some Foosx=[Foo(val,1.0)forvalinrange(0,50,2)]# and some arbitrary y datay=[iforiinrange(len(x))]fig,(ax1,ax2)=plt.subplots(1,2)fig.suptitle("Custom units")fig.subplots_adjust(bottom=0.2)# plot specifying unitsax2.plot(x,y,'o',xunits=2.0)ax2.set_title("xunits = 2.0")ax2.tick_params(axis='x',rotation=30,rotation_mode='xtick')# plot without specifying units; will use the None branch for axisinfoax1.plot(x,y)# uses default unitsax1.set_title('default units')ax1.tick_params(axis='x',rotation=30,rotation_mode='xtick')plt.show()

Gallery generated by Sphinx-Gallery