Displaying rich HTML elements in the Notebook

Displaying SVG in the Notebook

In [1]:
def svg_disc(radius, color):
    return """<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
          <circle cx="{0:d}" cy="{0:d}" r="{0:d}" fill="{1:s}" />
          </svg>""".format(radius, color)
In [2]:
class Disc(object):
    def __init__(self, radius, color='red'):
        self.radius = radius
        self.color = color

    def _repr_svg_(self):
        return svg_disc(self.radius, self.color)
In [3]:
Disc(60, 'purple')

JavaScript and D3 in the Notebook

In [4]:
from IPython.display import display_javascript
In [5]:
JS_TEMPLATE = """
// We load the d3.js library from the Web.
require.config({paths: {d3: "http://d3js.org/d3.v3.min"}});
require(["d3"], function(d3) {
    // Example from http://bost.ocks.org/mike/bar/

    // Define the data.
    var data = %s;

    // We normalize the data.
    var x = d3.scale.linear()
        .domain([0, d3.max(data)])
        .range([0, 420]);

    // We define a categorical color map.
    var color = d3.scale.category10();

    // We create the chart.
    d3.select(".chart")
      .selectAll("div")
        .data(data)
      .enter().append("div")
        .style("width", function(d) { return x(d) + "px"; })
        .text(function(d) { return d; });

});
"""
In [6]:
my_list = [2, 3, 5, 7, 11, 13]
In [7]:
JS = JS_TEMPLATE % str(my_list)
In [8]:
%%HTML
<style>
.chart div {
  font: 18px sans-serif;
  background-color: steelblue;
  text-align: right;
  padding: 5px;
  margin: 3px;
  color: white;
}
</style>
<div class="chart"></div>
In [9]:
display_javascript(JS, raw=True)