edited on 05.12.2020
Plotly is a visualization library that allows us to write code in Python, R, or Julia and generates interactive graphs using Javascript. So, we don’t have to deal with Javascript. You can checkout Plotly gallery, there are interesting works. Anyway, last week, I’ve started learning Plotly, and as a weekend project, I wanted to find a good way of displaying Plotly plots on my website which is a static site built using Hugo.
Before we start, I didn’t write any of the code in this post, just found them on the internet.
- Firstly, I found this one: metalblueberry
- Then, this one: ig248
The first one is good if you are ok with writing javascript in your markdown. The second one is probably what most people are looking for. You have created the Plotly plot using your favorite data analysis language, Python or R, and you want to display the result.
As ig248 explained, you need a shortcode plotly.html
. If you don’t know what a shortcode is, it’s a code snippet, that can take input arguments. Shortcodes live in /layouts/shortcodes/
.
{{ $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 use the shortcode in your markdown file, don’t forget to remove the escape characters.
{{/*< plotly json="/plotly/plotly-hugo/scatter3d.json" height="400px" >*/}}
Here is a less fancy, more classic example. Histogram of some data, I’ve worked on recently.
{{/*< plotly json="/plotly/plotly-hugo/ccpp_ep_hist.json" height="400px" >/*}}
OK, but how did we get the JSON files?
from plotly.io import write_image
#... Generate the fig here.
fig.write_json("plot_name.json")
Now, your figure is in JSON format. Give that JSON as an input to Plotly shortcode and it’ll generate the plot using plotly.js. We have to embed plotly.js
library into the web page which is the easiest part. Add these lines to <head>
:
{{ if .Params.plotly }}
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
{{ end }}
It’ll only add the script if the page has plotly: true
in it’s front-matter. So, don’t forget to add the front-matter parameter for the pages you are going to use plotly library.
Even though, this post is focused on displaying “plotly graphs in Hugo sites”, the logic will be the same in any site. It won’t matter how you build them. After all, there is a JSON that explains the graph and the javascript library that reads that explanation and plot it.
Lastly, we can always save the result as an image then use the good ol' static images in our blog posts. To do that, we have to use the write_image
function from plotly.io
just like write_json
.
from plotly.io import write_image
#... Generate the fig here.
fig.write_image("fig_name.png")