canvas_wrapper.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Helper module for displaying ROOT canvases in ipython notebooks
  3. Usage example:
  4. # Save this file as rootnotes.py to your working directory.
  5. import rootnotes
  6. c1 = rootnotes.canvas()
  7. fun1 = TF1( 'fun1', 'abs(sin(x)/x)', 0, 10)
  8. c1.SetGridx()
  9. c1.SetGridy()
  10. fun1.Draw()
  11. c1
  12. More examples: http://mazurov.github.io/webfest2013/
  13. @author alexander.mazurov@cern.ch
  14. @author andrey.ustyuzhanin@cern.ch
  15. @date 2013-08-09
  16. """
  17. import ROOT
  18. ROOT.gROOT.SetBatch()
  19. import tempfile
  20. from IPython.core import display
  21. def canvas(name="icanvas", size=(800, 600)):
  22. """Helper method for creating canvas"""
  23. assert len(size) == 2
  24. if len(size) != 2:
  25. raise ValueError("Size must be a 2 element tuple")
  26. # Check if icanvas already exists
  27. canvas = ROOT.gROOT.FindObject(name)
  28. if canvas:
  29. return canvas
  30. else:
  31. return ROOT.TCanvas(name, name, size[0], size[1])
  32. def _display_canvas(canvas):
  33. file = tempfile.NamedTemporaryFile(suffix=".png")
  34. canvas.SaveAs(file.name)
  35. ip_img = display.Image(filename=file.name, format='png', embed=True)
  36. return ip_img._repr_png_()
  37. def _display_any(obj):
  38. file = tempfile.NamedTemporaryFile(suffix=".png")
  39. obj.Draw()
  40. ROOT.gPad.SaveAs(file.name)
  41. ip_img = display.Image(filename=file.name, format='png', embed=True)
  42. return ip_img._repr_png_()
  43. # register display function with PNG formatter:
  44. png_formatter = get_ipython().display_formatter.formatters['image/png'] # noqa
  45. # Register ROOT types in ipython
  46. #
  47. # In [1]: canvas = canvas_wrapper.canvas()
  48. # In [2]: canvas
  49. # Out [2]: [image will be here]
  50. png_formatter.for_type(ROOT.TCanvas, _display_canvas)
  51. png_formatter.for_type(ROOT.TF1, _display_any)