我使用Add Plots With Hugo Shortcodes - Plotly中的代码来实现功能。但是我对文章中的代码稍作修改。
我新建了plotly.html作为shortcodes。代码如下,可以看到我将原文章中的第23行Plotly.plot
改为Plotly.newPlot
。因为Plotly官方函数最新的为Plotly.newPlot
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<div class="figure">
<div class="figure-plot" id="{{ .Get 0 }}">
Code could not finish, this are some reasons why this happen.
- Plot name not defined. The first parameter of the shortcode is the name.
- There is a syntax error. check browser console.
</div>
<script>
function draw(){
test = document.getElementById("{{ .Get 0 }}");
if (test == null){
console.log("The plot name is not defined")
return
}
fig = null
{{ .Inner | safeJS }}
if (!fig) {
test.innerText = "ERROR: fig variable is not defined"
return
}
test.innerText = null
Plotly.newPlot(test ,fig);
}
draw()
</script>
</div>
|
然后我在head.html中引入了Plotly的CDN
1
2
3
|
{{- if .Params.Plotly }}
<script src="https://cdn.bootcdn.net/ajax/libs/plotly.js/2.13.3/plotly.min.js"></script>
{{- end }}
|
最后在文章的Front Matter中增加plotly: true
就可以使用Plotly了,以下是示例代码。{{< plotly plot >}}
中的plot
为绘图名称,必须定义。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
{{< plotly plot >}}
var trace1 = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
type: 'scatter'
};
var trace2 = {
x: [1, 2, 3, 4],
y: [16, 5, 11, 9],
type: 'scatter'
};
data = [trace1, trace2];
fig = {
data: data
}
{{< /plotly >}}
|
显示效果如下: