简体   繁体   中英

Plot within a tooltip in d3.js

I would like to create a d3-based plot which graphs a plot within a tooltip. Unfortunately, I haven't found any examples on the web. Here is a sample JSON file.

[{"x":[0.4],
  "y":[0.2],
  "scatter.x":[0.54,0.9297,0.6024,-1.9224,2.2819],
  "scatter.y":[0.4139,1.1298,-0.1119,2.3624,-1.1947]},
 {"x":[0.1],
  "y":[0.9],
  "scatter.x":[-0.8566,-0.5806,-0.9326,0.8329,-0.5792],
  "scatter.y":[-0.5462,-0.7054,1.0264,-3.4874,-1.0431]}] 

The idea is to have a scatter plot for (x,y) coordinates first. However, when one mouses over a point, a different scatter plot within a tooltip appears based on [scatter.x, scatter.y] coordinates for that respective point.

I can do the scatter plots separately but have been struggling to put them together. Could anyone shed some light on this and/or provide a minimal example?

This was too long for a comment but I'm not certain if it's the answer you were looking for. One of the issues you might find is that your nested data is formatted differently-- one uses JSON objects with x and y , while the other uses two arrays of points.

My solution to this would be to create an extensible function:

function makeScatterPlot(elem, width, height, data, fill)

elem , width , height , and data are the core parameters: which element to attach the chart to, the size of the chart, and the data for the chart (in the JSON object format).

This function would generate all necessary items for the chart and add the chart to the provided element.

Then you want to bind to mouseover of your main chart, and in that function you'll have to do a bit of data modification to re-organize the two arrays into the JSON object structure.

function mainMouseover(d){
  var newData = [];
  for (var i = 0; i < d["scatter.x"].length; i++){
    var t = {x: [0], y: [0]};
    t.x[0] = d["scatter.x"][i];
    t.y[0] = d["scatter.y"][i];
    newData.push(t);
  }
  var newG = mainG.append("g").attr("transform", "translate(200,200)");
  makeScatterPlot(newG, 100,100, newData, "red");
}

Of course, you would modify the translate to match wherever you want your tooltip to be.

Putting this all together you get the following (very crude) fiddle . Hover over either of the black dots to see the sub-chart. Obviously this needs quite a bit of work to be a solid example (ie remove the sub-chart on mouseout ), but hopefully it will set you in the right direction.

If the tooltip chart is significantly different styling-wise compared to your main chart it may not be the best idea to use an extensible function, and you could just create another custom function instead.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM