ipython / ipython/ipython

Embed an interactive plot in the _repr_html_() method of a class

Open
#13,644 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
Python
Stars
16.8k
Forks
4.5k
Avg merge
1d 2h
Merged PRs (30d)
6

Description

I am trying to embed an interactive graph in the `_repr_html_()` method of a class `C`.

What I have tried so far does not seem to be working in my Jupyter Notebook, and I think there may be many programmers that would find such a feature useful.

Plotly (python)
---------------

Here is an example plot using [Plotly](https://plotly.com/python/line-and-scatter/) saved as HTML div:

```python
import plotly.offline as opy
import plotly.io as pio
import plotly.graph_objs as go
import numpy as np

pio.templates.default = "none"

the_x = np.logspace(4,9)
data = [
go.Scattergl(
x=the_x,
y=1E10*the_x **(-1),
name="Example",
line=dict(color="Red", width=1),
)
]
layout = go.Layout(
xaxis=dict(
title="X axis",
linecolor="#000",
type="log",
tickformat=".0e",
),
yaxis=dict(
title="Y axis",
linecolor="#000",
type="log",
tickformat=".0f",
),
font=dict(family="Serif", size=14, color="#000"),
legend=dict(font=dict(family="Serif", size=12, color="#000")),
)
fig = go.Figure(data=data, layout=layout)
the_div = opy.plot(fig, auto_open=False, output_type='div')
```

and a class `ClassOne` using `the_div`:

```python
class ClassOne:
def _repr_html_(self):
ret = f"""
{the_div}
"""
return ret

ClassOne() # returns blank. Chrome's 'Inspect HTML' gives many errors that I am not
# exactly able to understand, among which:
# "Couldn't process kernel message error: Mismatched"
```

Chart.js
--------

Another test using [Chart.js](https://www.chartjs.org). Also in this case, no luck.

```python
class ClassTwo:
def _repr_html_(self):
ret = """

Click the button below:


Click Me

function youclicked(){
alert("You Clicked!");
}



{{
var bt = document.getElementById("clearBtn");
bt.onclick = function(){{ alert('hi'); }};;
}}


var xyValues = [
{x:50, y:7},
{x:60, y:8},
{x:70, y:8},
{x:80, y:9},
{x:90, y:9},
];

new Chart("myChart", {
type: "scatter",
data: {
datasets: [{
pointRadius: 4,
pointBackgroundColor: "rgb(0,0,255)",
data: xyValues
}]
},
options: {
legend: {display: false},
scales: {
xAxes: [{ticks: {min: 40, max:100}}],
yAxes: [{ticks: {min: 6, max:10}}],
}
}
});

"""
return ret

ClassTwo() # The button is rendered and the youclicked() function is run.
# Unfortunately, no plots rendered. Among the HTML errors I see
# "Uncaught ReferenceError: Chart is not defined", but I
# cannot correctly provide the CDN to the page.

```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.