Plotly Figure Sample - 2018-11-05

Including plotly figures in Hugo posts

Custom shortcodes allow easy integration of interactive plotly figures.

Example

Above figure is included in Hugo using the following lines in the markdown:

{{< load-plotly >}}
{{< plotly json="/plotly/test.json" height="400px" >}}

The figure was exported to json using plotly.py and placed in static/plotly/test.json.

Implementation

Two simple Hugo shortcodes are required - simply place the files in layouts/shortcodes. A basic understanding of plotly.js is helpful.

The first one, load-plotly.html, loads the plotly.js library:

{{ if not ($.Page.Scratch.Get "plotlyloaded") }}
  {{ $.Page.Scratch.Set "plotlyloaded" 1 }}
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
{{ end }}

The second one, plotly.html, takes the json and height parameters, loads a figure description from the specified file, and creates a responsive, interactive figure:

{{ $json := .Get "json" }}
{{ $height := .Get "height" | default "200px" }}
<div id="{{$json}}" class="plotly" style="height:{{$height}}"></div>
<script>
Plotly.d3.json({{$json}}, function(err, fig) {
    Plotly.plot('{{$json}}', fig.data, fig.layout, {responsive: true});
});
</script>

One more example

I’ve added the extra modebar argument, and added a plotly slider for a bit of interactivity:

{{< plotly json="post/2018-11-05-plotly-sample/slider.json" height="500px" modebar="false">}}
comments powered by Disqus