Create a Chart with Code Block and D3 Library
Last updated
Last updated
Beside the Chart element that you can use to build charts, you can also use a combination of Code Block and javascript d3 library to create more customized data visualization.
The following link https://d3-graph-gallery.com/graph/barplot_horizontal.html showcases a basic horizontal bar chart from D3.js Graph Gallery, this tutorial will guide you on how can you use Code block to create a same plot in app builder.
Load D3.js:
The Code Block element requires manually adding the D3 library to the document body using $script=document.createElement("script")
and document.body.appendChild($script)
.
To ensure that the dependent code runs after the library is loaded, place the code inside $script.onload = function () { }
.
Set root ID and select by ID:
In the D3 gallery example, a div was created to contain the chart. However, in the Code Block element, we typically want the chart to be placed at the position of the Code Block element itself, allowing us to arrange it within the app builder. In order to do that, set the ID of the current Code Block element to "my_dataviz
" using root.id = "my_dataviz".
When creating the SVG, use the same ID to select the Code Block element and create the SVG inside it: var svg = d3.select("#my_dataviz")
Remember to replace "my_dataviz
" with your desired ID name.
Write the remaining code in $script.onload = function () { }
.
Within this block, you can write the custom code using the D3.js library to generate the desired chart.
Utilize the rich D3.js API and functions to create interactive and visually appealing data visualizations within the Code Block element.
Following these steps, we could create a chart in Code Block element same as the one in D3 gallary. Click preview to see the final result.
Define event to enhance interaction(Optional).
Customized events allow you to pass data from within a Code Block to app or trigger other actions.
Using defineEvent() function, fill title, name and event to define an event in Code Block. Note that it should be defined outside render function
Setup trigger to emit the event.
The new defined event will appear in the Code Block's interaction panel. Use it to create Interactions
To be more specific, if you want to define a barclick event, try:
And add add .on("click", function (event, d) { console.log([event,d]) emit('barclick', { country: d.Country, value: d.Value}); });
at the end of the svg.append command.
Source code in Code Block