Embed Plotly Figure (HTML) in Markdown Post

Hi! New to Hugo. I exported a plotly graph to html via using the write_html method (Python Jupyter). Now I want to embed this plotly generated graph in one of my markdown posts. I cannot find the answer yet. I tried to look at shortcodes, I’m not sure how it’s done. Any help will be greatly appreciated. Thank you.

There are several ways to go about this, but I would write the HTML files to somewhere below /assets, e.g. “assets/plotly/mygraph.html”.

Then you can do something like this from a shortcode:

{{ $r := resources.Get (printf "plotly/%s.html" ($.Get 0)) }}
{{ $r.Content | safeHTML }}

And then send in the graph name as the shortcode param, e.g. “{{< plotly mygraph >}}”

1 Like

Thank you! I will try this. I also found a solution online where one can use two simple Hugo shortcodes. The input file would be a json file.

I have successfully rendered the figure on my local machine. However, when I uploaded and made it live, the plotly objects don’t show anymore. I will try to figure out what’s happening here.

Yes, the JSON approach makes sense.

Thank you. But it looks like the shortcode does not automatically add the baseURL that’s why I was getting errors locating the json file. Now, I’m trying to explicitly put the baseURL when calling the json file via the shortcode.

The shortcode looks like this:

{{ $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>

Then, in the body of my Markdown, I initially used

{{< plotly json="/plotly/fig1.json" height="700">}} 

But, my baseURL is

http://thisismy.site/random-hugo-project/public/

And, when I debugged the error, I noticed that it was looking for my fig1.json file at

http://thisismy.site/plotly/fig1.json

when it should be looking at

http://thisismy.site/random-hugo-project/public/plotly/fig1.json

Is there a more elegant way to fix this? Thank you!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.