Search code examples
javascriptcytoscape.js

Is it possible to color just one node of the graph in CytoscapeJS?


Can I select a specific node and color it with a different color of the rest of the graph?

Thanks.


Solution

  • There are many ways to do it. You can change the color of a node by its ID using cy.nodes([id="NODE_ID"]) and set any style you want (more info).

    If what you need is to change the color of a node when it is selected (clicked on) you can use cy.on('tap', ...) in a similar way (more info).

    Here is a small demo of both:

    var eleArray = [
      { group: 'nodes', data: { id: 'N1'} },
      { group: 'nodes', data: { id: 'N2'} },
      { group: 'nodes', data: { id: 'N3'} },
      { group: 'edges', data: { id: 'E0', source: 'N1', target: 'N2' } },
      { group: 'edges', data: { id: 'E1', source: 'N2', target: 'N3' } }
    ];
    
    var stylesArray = [{
      selector: 'node',
      style: {'label': 'data(id)'}
    }];
    
    var cy = cytoscape({
      container: document.getElementById('cy'),
      style: stylesArray,
      elements: eleArray
    });
    
    // Set color of a node by ID
    cy.nodes('[id="N2"]').style('background-color', 'red');
    
    // Set color of a node when clicked
    cy.on('tap', 'node', function(evt) {
      evt.target.style({
        'background-color': 'blue'
      });
    });
    #cy {
      width: 90%;
      height: 200px;
      display: block;
    }
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.14.1/cytoscape.min.js"></script>
    <div id="cy"></div>

    Notice how I changed the color of the node N2 to red directly, and how the color changes to blue when you click on a node.

    If your graph is very complex, maybe a better way would be to add the color as a property of your nodes and using that property data on your style definition. Something like this:

    // New 'color' property on your nodes
    var eleArray = [
       { group: 'nodes', data: { id: 'N1', color: 'red'} }
       // ...
    ];
    
    // Use the property on your styles
    var stylesArray = [{
       selector: 'node',
       style: {'label': 'data(id)', 'background-color': 'data(color)'}
    }];