Plotly support
Jorge Martínez Garrido
November 26, 2024
This website supports now plotly. By using Quarto for rendering the content of a notebook, you can include plotly figures in your posts. The figures must be saved as a JSON file. This file is then passed to the following shortcode:
{{ $json := .Get "json" }}
{{ $height := .Get "height" | default "200px" }}
{{ if $json }}
<div id="{{ $json | htmlEscape }}" class="plotly" style="height:{{ $height | htmlEscape }}"></div>
<script>
(function() {
var plotId = '{{ $json | htmlEscape }}';
var plotHeight = '{{ $height | htmlEscape }}';
Plotly.d3.json(plotId, function(err, fig) {
if (err) {
console.error("Error loading JSON for Plotly:", err);
return;
}
Plotly.plot(plotId, fig.data, fig.layout, { responsive: true });
});
})();
</script>
{{ else }}
<p>Error: No JSON URL provided for Plotly visualization.</p>
{{ end }}
Which can be used as follows:
{{< plotly json="path/to/the/image.json" height="400px" >}}
Example
import numpy as np
import plotly.graph_objects as go
# Generate x values
x = np.linspace(0, 2 * np.pi, 500)
# Compute y values for sin and cos
y_sin = np.sin(x)
y_cos = np.cos(x)
# Create plotly traces
trace_sin = go.Scatter(
x=x, y=y_sin, mode='lines', name='sin(x)', line=dict(color='blue')
)
trace_cos = go.Scatter(
x=x, y=y_cos, mode='lines', name='cos(x)', line=dict(color='red')
)
# Create layout
layout = go.Layout(
title='Sine and Cosine Functions',
xaxis=dict(title='x'),
yaxis=dict(title='f(x)'),
legend=dict(x=0, y=1)
)
# Create figure
fig = go.Figure(data=[trace_sin, trace_cos], layout=layout)
fig.write_json("image.json")