%pylab inline from IPython.core.pylabtools import print_figure from IPython.display import Image, SVG, Math class Gaussian(object): """A simple object holding data sampled from a Gaussian distribution. """ def __init__(self, mean=0, std=1, size=1000): self.data = np.random.normal(mean, std, size) self.mean = mean self.std = std self.size = size # For caching plots that may be expensive to compute self._png_data = None self._svg_data = None def _figure_data(self, format): fig, ax = plt.subplots() ax.plot(self.data, 'o') ax.set_title(self._repr_latex_()) data = print_figure(fig, format) # We MUST close the figure, otherwise IPython's display machinery # will pick it up and send it as output, resulting in a double display plt.close(fig) return data # Here we define the special repr methods that provide the IPython display protocol # Note that for the two figures, we cache the figure data once computed. def _repr_png_(self): if self._png_data is None: self._png_data = self._figure_data('png') return self._png_data def _repr_svg_(self): if self._svg_data is None: self._svg_data = self._figure_data('svg') return self._svg_data def _repr_latex_(self): return r'$\mathcal{N}(\mu=%.2g, \sigma=%.2g),\ N=%d$' % (self.mean, self.std, self.size) # We expose as properties some of the above reprs, so that the user can see them # directly (since otherwise the client dictates which one it shows by default) @property def png(self): return Image(self._repr_png_(), embed=True) @property def svg(self): return SVG(self._repr_svg_()) @property def latex(self): return Math(self._repr_svg_()) # An example of using a property to display rich information, in this case # the histogram of the distribution. We've hardcoded the format to be png # in this case, but in production code it would be trivial to make it an option @property def hist(self): fig, ax = plt.subplots() ax.hist(self.data, bins=100) ax.set_title(self._repr_latex_()) data = print_figure(fig, 'png') plt.close(fig) return Image(data, embed=True) x = Gaussian() x x.png x.svg display(x.png) display(x.svg) x2 = Gaussian(0.5, 0.2, 2000) x2 display(x.hist) display(x2.hist) p = np.polynomial.Polynomial([1,2,3], [-10, 10]) p def poly2latex(p): terms = ['%.2g' % p.coef[0]] if len(p) > 1: term = 'x' c = p.coef[1] if c!=1: term = ('%.2g ' % c) + term terms.append(term) if len(p) > 2: for i in range(2, len(p)): term = 'x^%d' % i c = p.coef[i] if c!=1: term = ('%.2g ' % c) + term terms.append(term) px = '$P(x)=%s$' % '+'.join(terms) dom = r', domain: $[%.2g,\ %.2g]$' % tuple(p.domain) return px+dom poly2latex(p) from IPython.display import Latex Latex(poly2latex(p)) ip = get_ipython() latex_formatter = ip.display_formatter.formatters['text/latex'] latex_formatter.for_type_by_name('numpy.polynomial.polynomial', 'Polynomial', poly2latex) p p2 = np.polynomial.Polynomial([-20, 71, -15, 1]) p2