Interactions that affect multiple separate charts

2019-02-18 14:46发布

I'm trying to create a data visualization in d3.js that contains two charts: a parallel-axis plot, and horizontal colorbar chart (I just made up that name, but it's basically a series of colored rectangles). Each line in the parallel-axis plot is associated with a set of rectangles in the colorbar chart.

Right now, mousing over a given line highlights that line, and mousing over a given rectangle highlights that set of rectangles. My goal is to also highlight the associated line or set of rectangles on the opposite chart anytime the user mouses over either chart. This seems like it would be pretty straightforward if I generated both charts with the same function. However, it would be much neater (and more reusable) coding style to give each chart its own function and just connect them somehow. I tried having each within-chart mouseover function call a function defined at a higher level that affected both charts, but this didn't seem to have any effect on the chart that wasn't moused-over. Since I still don't feel like I fully understand how d3.js works on an underlying level, I'd really like to have confirmation that this is a viable way to set up my code. My code is long and complicated, and I really just want advice on the structure, so here is the basic outline:

function chart1(){
    make chart
    function mouseover(d,i){
         do stuff
         chart1_globalmouseover(d,i);
    }
    chartElement.on("mouseover", function(d,i){mouseover(d,i)});
}

function chart2(){
    make chart
    function mouseover(d,i){
         do stuff
         chart2_globalmouseover(d,i);
    }
    chartElement.on("mouseover", function(d,i){mouseover(d,i)});
}

function chart1_globalmouseover(d,i){
    do stuff in chart 2's mouseover function
}

function chart2_globalmouseover(d,i){
    do stuff in chart 1's mouseover function
}

c1 = chart1();
c2 = chart2();

1条回答
对你真心纯属浪费
2楼-- · 2019-02-18 15:30

One way to link the two graphs independent of the code used to create them would be to assign IDs or classes to the elements you may want to select. That is, if graph 2 has an element with ID foo, then in a mouse handler for an element of graph 1, you could say d3.select("#foo").style("stroke", "red") for example. Similarly with classes.

This approach allows you to keep the code completely separate. Moreover, if you use classes, you can assign the same class to things you would want to highlight together (e.g. elements representing the same data). Then d3.selectAll(".class") would select and allow you to manipulate all of them. This would work for an arbitrary number of graphs, not just two -- what changes is simply the number of elements that will be selected.

查看更多
登录 后发表回答