如何将 plotly.js 应用于现有 svg 组 <g> 作为目标而不是将其应用于目标 <div> 元素?

How to apply plotly.js to an existing svg group <g> as target instead of applying it to a target <div> element?

如果我的DOM中有一个目标div,例如

<div id="graph"></div>

我可以使用 plotly 在其中创建一个情节 div(下面是一个完整的例子):

Plotly.newPlot('graph', data, layout);

这将在 div 中创建一个包含 svg 元素的嵌套结构。 在那个 svg 元素上有一个等高线图,由一些元素表示(参见下面的 DOM 结构)。效果不错。

但是,我有一个 已经存在的 svg 元素(使用 d3.js 创建),我想在我的 [=44= 中包含 plotly 的等高线图]目标 svg 组:

<div id="myDiv">
  <svg id = "mySvgElement">
      ...
      <rect id="someExistingContent"></rect>
      ...
      <g id = "targetGroupForPlotly"></g>
  </svg>
</div>

是否可以告诉 plotly.js 使用现有的 svg 组而不是 div 元素?

好吧,作为一个丑陋的解决方法,我可以绘制到一个不可见的虚拟对象 div,然后使用 jquery 从那里复制内容,但也许有一些直接绘制的替代工作流程到给定的目标 svg 组?

(我现有的 svg 元素内的嵌套 svg 元素也是一个选项)。

乡村情节示例

使用https://cdn.plot.ly/plotly-latest.min.js

var data = [ {
  z: [[10, 10.625, 12.5, 15.625, 20],
       [5.625, 6.25, 8.125, 11.25, 15.625],
       [2.5, 3.125, 5., 8.125, 12.5],
       [0.625, 1.25, 3.125, 6.25, 10.625],
       [0, 0.625, 2.5, 5.625, 10]],
  x: [-9, -6, -5 , -3, -1],
  y: [0, 1, 4, 5, 7],
  type: 'contour',  
  colorscale: 'Jet',
  showscale: false,
  autocontour: false,  
  contours: {
    start: 0,
    end: 8,
    size: 0.4
  }
}];

var layout = {
margin: {
b: 0,
l: 0,
r: 0,
t: 0
},
height: 600,
width: 600,
  title: '',
  xaxis: {
        ticks: '',
      showticklabels: false           
  },
  yaxis: {
       ticks: '',
       showticklabels: false     
  } 
};

Plotly.newPlot('graph', data, layout);

https://jsfiddle.net/tmLuj6uf/

DOM 结构:

JQuery 的复制解决方法似乎是最简单的解决方案:

Plotly.newPlot('graph', data, layout);
$('.contour').appendTo('#mySvgElement');            
$('#graph').empty();

您可以尝试将 foreignObject 标签添加到 g 标签并将 div 放入其中。

<div id="myDiv">
  <svg id = "mySvgElement">
      ...
      <rect id="someExistingContent"></rect>
      ...
      <g id = "parentOfTarget">
      <foreignObject>
      <div id="Target"/>
      </foreignObject>
      </g>
  </svg>
</div>