I recently implemented some interactive plots in a Jupyter notebook to play with some simple population dynamics models introduced in the lecture on modeling and simulation I’m currenly taking. In a next step I wanted to see how to get something similar in the browser. plotly.js seems to be quite a common choice, (they also have a Python binding, but I used matplotlib in my Jupyter notebook), but was new to me.

Fortunately, it was quite easy to get interactive plots working in these posts. In the markdown of this very post, I added some HTML to create a place for the plot to live in, while also loading the JS library.

<!-- Latest compiled and minified plotly.js JavaScript -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="plotarea" style="width:600px;height:250px;"></div>

Then I added the following script to the post:

PLOT_AREA = document.getElementById('plotarea');

const a = 0.03134;
const b = 1.55 * Math.pow(10,-10);
const p0 = 3929214;

const logistic = (t) => (a*p0) / (b*p0 + (a-b*p0) * Math.exp(-a*t));

const x = Array.from({length: 161}, (x,i) => i);
y = x.map(logistic);

Plotly.plot(PLOT_AREA, [{x:x.map(xi => xi + 1790),y:y}],{margin:{t:0}});

That’s it! The plot shows a simple logistic growth model for the US population between 1790 and 1950.

The Result

There is a lot to improve here, but for now I’m very happy with how easy and quick this was! Next up is adding sliders as a way to interactively change the model’s parameters.