I have an existing <svg>
and I have defined groups <g>
where each group has its own unique id.
<g id="id_1"><text>...</text></g>
<g id="id_2"><text>...</text></g>
<g id="id_3"><text>...</text></g>
<g id="id_4"><text>...</text></g>
Similarly I have data formatted as
data = { "id_2" : { "name" : value1, "description" : value2, ... },
"id_4" : { "name" : value1, "description" : value2, ... },
"id_9" : { "name" : value1, "description" : value2, ... } };
for each row. Notice that not all id's match!
I do not wish to replace the <g>
, instead I would like to bind each data row to the correct <g>
tag where the id's match. The default behavior of d3.select('g').data(d3.values(data))
does not support this as it will bind by index. How can I do this?
I have sample code at jsbin with indexed data binding that you can modify.
You are missing the remove command. Add nodesUpdate.exit().remove();
to remove the unmapped svg elements. You will also need to change .data(d3.values)
to .data(d3.entries)
to ensure the keys match up.
var data = { "id_2": { "Name": "John Doe", "Description": "A common fella" }, "id_4": { "Name": "Ann Lady", "Description": "Has long hair" }, "id_8": { "Name": "Luke Force", "Description": "Green Lightsaber" } }; window.addEventListener("load", function() { bind(data); }); function bind(data) { // get svg element var svg = d3.select("svg"); // select and bind data by index nodesUpdate = svg .selectAll("g") .data(d3.entries(data)); // update the data nodesUpdate .select("text") .text(function(d) { return d.value.Name + " : " + d.value.Description; }); nodesUpdate.exit().remove(); // What I really want though is to match the data such that data[id_2] is matched // to <g class="id_2"> and so on. Nodes 1 and 3 should not be included in the update set! }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <svg style=""> <g id="id_1" transform="translate(20, 30)"> <text>-- 1 --</text> </g> <g id="id_2" transform="translate(20, 60)"> <text>-- 2 --</text> </g> <g id="id_3" transform="translate(20, 90)"> <text>-- 3 --</text> </g> <g id="id_4" transform="translate(20, 120)"> <text>-- 4 --</text> </g> </svg>
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.