2

If there is a target div in my DOM, e.g.

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

I can use plotly to create a plot in that div (a full example is below):

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

This will create a nested structure in the div that contains an svg element. Tn that svg element there is a contour plot, represented by some elements (see DOM structure below). That works fine.

However, I have an already existing svg element (created with d3.js) and I would like to include a contour plot from plotly in my target svg group:

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

Is it possible to tell plotly.js to use that existing svg group instead of a div element?

Well, as an ugly work around, I could plot to an invisible dummy div and then copy the content from there with jquery, but maybe there is some alternative work flow that plots directly to a given target svg group?

(A nested svg element inside my existing svg element would also be an option).

Countour plot example

using 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 structure:

DOM structure

Community
  • 1
  • 1
Stefan
  • 10,010
  • 7
  • 61
  • 117

2 Answers2

0

The copy workaround with JQuery seems to be the easiest solution:

Plotly.newPlot('graph', data, layout);
$('.contour').appendTo('#mySvgElement');            
$('#graph').empty();
Stefan
  • 10,010
  • 7
  • 61
  • 117
0

You could try adding a foreignObject tag to the g tag and putting the div into that.

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