Skip to content

1.Selection

yuanlii edited this page Jun 29, 2019 · 21 revisions

Selection

  • D3.select --> selects the first matching element
  • d3.selectAll --> selects all matching elements.

Update selection with functions

an example:

d3.selectAll('circle')
.attr('cx', function(d, i) {
	return i * 100;
});
  • d is the joined data
  • i is the index of the element within the selection
<html>
    <head>
        <link rel="stylesheet" href="index.css">
        <title>Learn D3.js</title>
    </head>

    <style>
        rect {
	        fill: #ddd;
        }        
    </style>

    <body>
        <!-- begin by creating several squares  -->
        <svg width='800' height='600'>
            <g transform="translate(70, 20)">
                <rect width="30" height="30" y="0" />
                <rect width="30" height="30" y="40" />
                <rect width="30" height="30" y="80" />
                <rect width="30" height="30" y="120" />
            </g>
        </svg>

        <!-- define an action button -->
        <div class="menu">
            <button onClick="update();">Click to update rect elements using function(d, i)</button>
        </div>
        
        <script src="https://d3js.org/d3.v4.min.js"></script>
        <!-- reference to index.js -->
        <script src="index.js"></script>
    </body>
</html>

Clone this wiki locally