I have to draw a graph by d3js. To represent a graph I use the adjacent list data structure. Every item in the adjacent list is the destination vertex of the edge (the source vertex is the vertex itself).
According to this representation, my data is:
data = [
{ id: 1, pos: [10, 50], adj: [
{id: 2, pos: [30, 60]},
{id: 3, pos: [20, 30]}
]
},
{ id: 2, pos: [30, 60], adj: [{id: 1, pos: [10, 50]}]},
{ id: 3, pos: [20, 30], adj: [{id: 1, pos: [10, 50]}]}
]
How can I draw this graph?
I tried this but it doesn't work
var vertex = svg.selectAll("g").data(graph.vertices, function (d) {
return d.id; });
// NEW
vertex.enter().append("g")
.attr("class", function(d) { return d.id });
var edges = vertex.selectAll("line")
.data(function(d) { return d.adj }, function(d,i) {
console.log(d); return d; });
// UPDATE
edges.classed("selected", function(d) { return d === selected; })
.attr("x0", function(d) {
return d.pos[0]; })
.attr("y1", function(d) { return d.pos[1]; })
.attr("x1", function(d,i) {
return d.adj[i][0]; })
.attr("y1", function(d,i) { return d.adj[i][1]; });
// NEW
edges.enter().append("line")
.filter(function(d,i) {
return d.id < d.adj[i].id })
.attr("class", "line")
.attr("x0", function(d) { return d.pos[0]; })
.attr("y0", function(d) { return d.pos[1]; })
.attr("x1", function(d,i) { return d.adj[i].pos[0]; })
.attr("y1", function(d,i) { return d.adj[i].pos[1]; });
// OLD
vertex.exit().remove();
P.S : I can't use the force layout.