Add plotly diagrams to hugo websites

#hugo#plotly

15 March 2025 | Updated on 23 March 2025

You can add interactive diagrams to your hugo page via plotly.

Add plotly script to header

Choose specific plotly version

  • find a plotly release version
  • adjust the link accordingly and use it in your head partial configuration (next section)
    https://cdn.plot.ly/plotly-3.0.1.min.js

Configure head partial

depending on your hugo theme the partial file will be named differently

  • this code will only add the plotly script to the header of a page in case plotly was enabled via a frontmatter setting
  • the small svg css entry ensures that the modebar menu symbols/buttons are placed correctly
layouts/partials/custom/head-end.html
{{ if eq .Params.Plotly true }}
<script src="https://cdn.plot.ly/plotly-3.0.1.min.js"></script>
<style>
    svg {
        display: inherit;
    }
</style>
{{- end }}

Create plotly shortcode

  • shortcodes add additional features to your hugo website
  • this shortcode includes the required javascript code to load a plotly diagram which was exported as json file
  • it also removes default margins one the left and right side to ensure that the diagram gets shown as big as possible
layouts/shortcodes/plotly.html
{{ $json := .Get "json" }}
{{ $height := .Get "height" | default "400px" }}
<div id="{{$json}}" class="plotly" style="height:{{$height}}"></div>
<script>
async function loadPlotly() {
    try {
        const response = await fetch('{{$json}}');
        const fig = await response.json();
        var layout = fig.layout || {};
        layout['modebar'] = {
            orientation: 'h'
        };
        layout['margin'] = {l: 0, r: 0, t: 40, b: 40};
        Plotly.newPlot('{{$json}}', fig.data, layout, {displaylogo: false, responsive: true});
    } catch (error) {
        console.error('Error loading plotly json:', error);
    }
}
loadPlotly();
</script>
  • now you can use this shortcode in every page for adding plotly diagrams

Add a diagram to a page

Enable plotly in frontmatter

  • required for every page that uses plotly
  • this way plotly will not be loaded on pages that do not use plotly
content/posts/some-post/index.md
---
title: 'Some post'
plotly: true
---

Add diagram itself

src/main.rs
{{< plotly json="plotly-json/a-json-file.json" height="400px">}}

Examples

Simple bar chart


3D cones


Additional resources


Related content