I recently started getting into Vega to reduce the amount of D3.js
coding for more or less typical charts. However, for complex dashboards, interactions between the Vega
charts using signals is still a bit tricky for me.
Is there a way to load "standard" Vega
chart into HTML
page and then access its elements using D3? When I deploy Vega
examples using Vega-Embed , the only element connected to a chart is a canvas:
<canvas width="542" height="297" class="marks" style="width: 434px; height: 238px;"></canvas>
In other words, is there a solution to export Vega
with accessible DOM elements?
Passing opt={renderer: 'svg'}
as an argument to the embed
function allows one to access and modify the different visualization elements through the DOM. Find below a simple example where I access and change the color of the first bar using D3:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/vega@5"></script> <script src="https://cdn.jsdelivr.net/npm/vega-lite@4"></script> <script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script> <div id="vis"></div> <script> var spec = "https://vega.github.io/vega/examples/grouped-bar-chart.vg.json"; vegaEmbed('#vis', spec, opt = { renderer: 'svg' }).then(() => { d3.select('g.mark-rect.role-mark').select('path').attr('fill', 'firebrick') }) </script>
In addition to the default CSS class names that Vega uses, the name and role mark properties values will be exposed as CSS class names on the enclosing SVG group (g) element containing the mark instances (Source: https://vega.github.io/vega/docs/marks/ ).
You can also check a more complex example in this observable notebook: https://observablehq.com/@oliviafvane/hacking-a-vega-lite-map-label-positioning-custom-fonts-stri
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.