Visualization
This post tries out different (interactive) ways to add visualizations directly from codeblocks.
Using chart.js
Show code
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
Using altair and vega-lite
Show code
import altair as alt
# Create a selection that chooses the nearest point & selects based on x-value
nearest = alt.selection(type='single', nearest=True, on='mouseover',
fields=['date'], empty='none')
# The basic line
line = alt.Chart().mark_line(interpolate='basis').encode(
alt.X('date:T', axis=alt.Axis(title='')),
alt.Y('price:Q', axis=alt.Axis(title='',format='$f')),
color='symbol:N'
)
# Transparent selectors across the chart. This is what tells us
# the x-value of the cursor
selectors = alt.Chart().mark_point().encode(
x='date:T',
opacity=alt.value(0),
).add_selection(
nearest
)
# Draw points on the line, and highlight based on selection
points = line.mark_point().encode(
opacity=alt.condition(nearest, alt.value(1), alt.value(0))
)
# Draw text labels near the points, and highlight based on selection
text = line.mark_text(align='left', dx=5, dy=-5).encode(
text=alt.condition(nearest, 'price:Q', alt.value(' '))
)
# Draw a rule at the location of the selection
rules = alt.Chart().mark_rule(color='gray').encode(
x='date:T',
).transform_filter(
nearest
)
# Put the five layers into a chart and bind the data
chart = alt.layer(line, selectors, points, rules, text,
data='https://raw.githubusercontent.com/altair-viz/vega_datasets/master/vega_datasets/_data/stocks.csv',
width=600, height=300,title='Stock History')
json_result = chart.to_json()
html = """<div id="vis"></div>
<script type="text/javascript">
var spec ="""+json_result+"""
vegaEmbed('#vis', spec).then(function(result) {
// Access the Vega view instance (https://vega.github.io/vega/docs/api/view/) as result.view
}).catch(console.error);
</script>"""
return html