Is there a way to modify Vega charts with D3.js?
Asked Answered
K

1

6

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?

Karlie answered 18/2, 2021 at 8:30 Comment(1)
This is a very relevant question! I've been also wondering how this could be done but haven't found anything yet. AFAIK it should be possible to render the chart with vega-embed to an SVG?Worthy
N
6

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

Nathannathanael answered 25/2, 2021 at 16:57 Comment(1)
Wow! That's exactly what I was looking for! Thank you so much @93degree!Karlie

© 2022 - 2024 — McMap. All rights reserved.