Search code examples
htmlcsssvgd3.js

Position a DIV element inside an SVG viewport


How can I position a HTML DIV element relative to a SVG element?

I use D3 to generate a chart in SVG:

enter image description here

I would like to add a dropdown list on the bottom-right corner, next to the legend. I do have the corresponding element (a plain HTML DIV element,) but I do not know how to position it properly on the chart.

I understand positioning of SVG elements, but I do not know how to apply something similar to a DIV element.

Any idea, besides positioning it outside the viewport (e.g. below)?


Solution

  • Look into CSS Position. You can create a relatively positioned DIV to hold your SVG. You can then lay down an absolutely positioned DIV on top of it to hold the select element; you can place that second DIV anywhere you want using it's left and top styles.

    Here it is all put together:

    let w = 500;
    let h = 300;
    let pad = 10;
    let xmin = -2 * Math.PI;
    let xmax = 2 * Math.PI;
    let ymin = -1.1;
    let ymax = 1.1;
    
    let svg = d3.select("#graph")
        .append("svg")
        .attr("max-width", `${w}px`)
        .attr("viewBox", [0, 0, w, h]);
        
    let x_scale = d3
      .scaleLinear()
      .domain([xmin, xmax])
      .range([pad, w - pad]);
    let y_scale = d3
      .scaleLinear()
      .domain([ymin, ymax])
      .range([h - pad, pad]);
    let path = d3
      .line()
      .x((d) => x_scale(d[0]))
      .y((d) => y_scale(d[1]));
    
    svg
      .append("g")
      .attr("transform", `translate(0, ${y_scale(0)})`)
      .call(d3.axisBottom(x_scale).tickFormat(d3.format("d")).tickSizeOuter(0));
    svg
      .append("g")
      .attr("transform", `translate(${x_scale(0)})`)
      .call(d3.axisLeft(y_scale).ticks(5).tickSizeOuter(0));
      
    d3.select('#function')
      .on('change', function() {
        draw_graph(this.value)
      })
      
      
    draw_graph('sine')
      
    
    function draw_graph(f_string) {
      svg.select('path.graph').remove()
      let f
      if(f_string == "sine") {
        f = Math.sin;
      }
      else {
        f = Math.cos;
      }
      let pts = d3.range(xmin, xmax, 0.01)
        .map((x) => [x, f(x)]);
      svg
        .append("path")
        .attr('class', 'graph')
        .attr("d", path(pts))
        .attr("fill", "none")
        .attr("stroke", "black")
        .attr("stroke-width", 3);
    }
    <script src="https://d3js.org/d3.v7.min.js"></script>
    
    <div style="position: relative" id="viz">
      <svg id="graph" width=500 height=300 style="border: solid 2px black"></svg>
      <div style="border: solid 0.5px black; background-color: rgba(255,255,255,0.7); position: absolute; left: 20px; top: 30px">
        <label for="function">function:</label>
        <select name="function" id="function">
          <option value="sine">sine</option>
          <option value="cosine">cosine</option>
        </select>
       </div>
    </div>