принудительное изменение графа направленного цвета при наведении курсора - PullRequest
0 голосов
/ 04 мая 2018

У меня есть силовой ориентированный граф с разными узлами, я хочу изменить цвет выбранного узла и всех подключенных (соседних) узлов, когда пользователь наведет на него указатель мыши.

Я пытаюсь сделать это ..

function onMouseover(d){
  node.style("fill", function(o){
    var color = isConnected(d, o) ? 'red' : 'blue';
    return color;
  })
  force.resume();
}

function isConnected(d, o){
  return o.index === d,index || 
         (d.children && d.children.indexOf(o.index) !== -1) ||
         (o.children && o.children.indexOf(d.index) !== -1) ||
         (o.parents && o.parents.indexOf(d.index) !== -1) ||
         (d.parents && d.parents.indexOf(o.index) !== -1);
}

Может ли кто-нибудь помочь мне здесь, или укажите мне на подобный график d3.

1 Ответ

0 голосов
/ 05 мая 2018

Вот демонстрация, основанная на сило-ориентированном графике Майка Бостока , который меняет цвет наведенного узла и его напрямую соединенных узлов:

var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

var color = d3.scaleOrdinal(d3.schemeCategory20);

var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return d.id; }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));

d3.json("https://gist.githubusercontent.com/mbostock/4062045/raw/5916d145c8c048a6e3086915a6be464467391c62/miserables.json", function(error, graph) {
  if (error) throw error;

  var link = svg.append("g")
      .attr("class", "links")
    .selectAll("line")
    .data(graph.links)
    .enter().append("line")
      .attr("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = svg.append("g")
      .attr("class", "nodes")
    .selectAll("circle")
    .data(graph.nodes)
    .enter().append("circle")
      .attr("r", 5)
      .attr("fill", function(d) { return color(d.group); })
      .call(d3.drag()
          .on("start", dragstarted)
          .on("drag", dragged)
          .on("end", dragended));

  node.append("title")
      .text(function(d) { return d.id; });

  node.on("mouseover", function(d) {

    var connectedNodeIds = graph
      .links
      .filter(x => x.source.id == d.id || x.target.id == d.id)
      .map(x => x.source.id == d.id ? x.target.id : x.source.id);

    d3.select(".nodes")
      .selectAll("circle")
      .attr("fill", function(c) {
        if (connectedNodeIds.indexOf(c.id) > -1 || c.id == d.id) return "red";
        else return color(c.group);
      });
  });

  node.on("mouseout", function(d) {
    d3.select(".nodes")
      .selectAll("circle")
      .attr("fill", function(c) { return color(c.group); });
  });

  simulation
      .nodes(graph.nodes)
      .on("tick", ticked);

  simulation.force("link")
      .links(graph.links);

  function ticked() {
    link
        .attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  }
});

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}
.links line {
  stroke: #999;
  stroke-opacity: 0.6;
}

.nodes circle {
  stroke: #fff;
  stroke-width: 1.5px;
}
<svg width="500" height="350"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>

Во время наведения мыши идея заключается в следующем:

  1. Получение идентификатора зависшего узла,
  2. Из всех ссылок получите те, чей источник или цель является идентификатором этого зависшего узла,
  3. Из этих совпадающих ссылок получить идентификатор связанного узла, подключенного к наведенному узлу,
  4. Пройдите по всем узлам и измените цвет тех, которые соответствуют ранее найденным узлам.

таким образом:

node.on("mouseover", function(d) {

  var connectedNodeIds = graph
    .links
    .filter(x => x.source.id == d.id || x.target.id == d.id)
    .map(x => x.source.id == d.id ? x.target.id : x.source.id);

  d3.select(".nodes")
    .selectAll("circle")
    .attr("fill", function(c) {
      if (connectedNodeIds.indexOf(c.id) > -1 || c.id == d.id) return "red";
      else return color(c.group);
    });
});

Во время наведения мыши , мы проходим все узлы и возвращаем исходный цвет:

node.on("mouseout", function(d) {
  d3.select(".nodes")
    .selectAll("circle")
    .attr("fill", function(c) { return color(c.group); });
});
...