Code export
Consider the example from Bar Area Graph. Clicking on Code Export in the chart view prompts below code.
Copy below code and paste in index.html
How to
Gramex Charts uses one function, up to three variables. Integration example.
function - Main function that draws the chart.
variable | type | usage | Description |
data |
Array of Objects | required | Data for chart |
el |
DOM selector | required | Example usage: $('.chart').get(0) |
options |
Object | required | Attributes to control chart interactions |
Variables
variable | type | usage | description |
data
|
Array of Objects | required | Data for chart. Replace this with data from a JSON or data endpoint in your application. |
data_coltypes |
Object | required | Used to control scales for axes. Derived from g1.types |
base_spec
|
JSON file or URL | optional | Typically, used for Vega charts. Docs. Example |
Code structure
Target container for the chart
<div class="chart"></div>
Load JavaScript dependencies for the chart. We use Vega library to draw this chart. Vega docs
<script src="https://unpkg.com/jquery"></script>
<script src="https://unpkg.com/lodash"></script>
<script src="https://unpkg.com/vega"></script>
<script src="https://unpkg.com/vega-tooltip"></script>
Vega supports data in two formats, `url` (endpoint) and `values` (raw values).
data = {"name": "table", "url": "https://gist.githubusercontent.com/bkamapantula/677c0aee77115c60eda89e9d979525fc/raw/ddd5e03a47e105f43eef8bfda48c80ec1ffb8b06/columnline-data.json"}
Vega supports data in two formats, `url` (endpoint) and `values` (raw values).
data = {"name": "table", "values": [{}, {}...]}
`draw()` uses three parameters, read the table above on how to use them.
function draw(data, el, options) {}
Vega chart specification is defined in a JSON format. This is a powerful declarative way and human readable.
base_spec = "https://gist.githubusercontent.com/bkamapantula/677c0aee77115c60eda89e9d979525fc/raw/351a17d8579a326d17a1bfe75f8b07c63f0e9ebb/bararea.json"
$.getJSON(base_spec).done(function (spec) {
// use the spec to render the chart
})
We won't go in to the details here. Read our Vega docs on its attributes and modifying them. Vega docs
{
"$schema": "https://vega.github.io/schema/vega/v5.json",
"description": "",
"width": "",
"height": "",
"data": [],
"scales": [],
"signals": [],
"axes": [],
"marks": []
...
}
Typically, you might need to update the specification according to the situation. Since Vega spec is practically JSON you can modify the object easily.
spec.width = 650
spec.title = "My chart title"
...
Vega runtime supports different attributes including tooltip, chart background, SVG or canvas rendering among others. Vega view
new vega.View(vega.parse(spec))
.renderer('svg')
.tooltip(new vegaTooltip.Handler().call)
.logLevel(vega.Warn)
.initialize(el)
.background(opts.background || '#f0f3f8')
.hover()
.run()
Once the setup is complete, draw the chart.
draw(data, el, options)
Next: Chart Integration