Evans测试

一个模型“Foo”单元类,它根据“单元”支持转换和不同的刻度格式。 这里的“单位”只是一个标量转换因子,但是这个例子表明Matplotlib完全不知道客户端软件包使用哪种单位。

Evans测试示例

  1. from matplotlib.cbook import iterable
  2. import matplotlib.units as units
  3. import matplotlib.ticker as ticker
  4. import matplotlib.pyplot as plt
  5. class Foo(object):
  6. def __init__(self, val, unit=1.0):
  7. self.unit = unit
  8. self._val = val * unit
  9. def value(self, unit):
  10. if unit is None:
  11. unit = self.unit
  12. return self._val / unit
  13. class FooConverter(object):
  14. @staticmethod
  15. def axisinfo(unit, axis):
  16. 'return the Foo AxisInfo'
  17. if unit == 1.0 or unit == 2.0:
  18. return units.AxisInfo(
  19. majloc=ticker.IndexLocator(8, 0),
  20. majfmt=ticker.FormatStrFormatter("VAL: %s"),
  21. label='foo',
  22. )
  23. else:
  24. return None
  25. @staticmethod
  26. def convert(obj, unit, axis):
  27. """
  28. convert obj using unit. If obj is a sequence, return the
  29. converted sequence
  30. """
  31. if units.ConversionInterface.is_numlike(obj):
  32. return obj
  33. if iterable(obj):
  34. return [o.value(unit) for o in obj]
  35. else:
  36. return obj.value(unit)
  37. @staticmethod
  38. def default_units(x, axis):
  39. 'return the default unit for x or None'
  40. if iterable(x):
  41. for thisx in x:
  42. return thisx.unit
  43. else:
  44. return x.unit
  45. units.registry[Foo] = FooConverter()
  46. # create some Foos
  47. x = []
  48. for val in range(0, 50, 2):
  49. x.append(Foo(val, 1.0))
  50. # and some arbitrary y data
  51. y = [i for i in range(len(x))]
  52. fig, (ax1, ax2) = plt.subplots(1, 2)
  53. fig.suptitle("Custom units")
  54. fig.subplots_adjust(bottom=0.2)
  55. # plot specifying units
  56. ax2.plot(x, y, 'o', xunits=2.0)
  57. ax2.set_title("xunits = 2.0")
  58. plt.setp(ax2.get_xticklabels(), rotation=30, ha='right')
  59. # plot without specifying units; will use the None branch for axisinfo
  60. ax1.plot(x, y) # uses default units
  61. ax1.set_title('default units')
  62. plt.setp(ax1.get_xticklabels(), rotation=30, ha='right')
  63. plt.show()

下载这个示例