We are trying to create 3D network using D3.js, we tried to give the co-ordinates on the basis of all three axis (x,y,z) but on display it 2D network instead of 3D.
Is there any way to find the issue out...
Thanks in advance
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
<style>
#myDiv {
width: 70%;
float: left;
}
#lineGraph {
width: 30%;
height: 300px;
float: right;
background-color: lightgray;
}
</style>
</head>
<body>
<div id="myDiv"></div>
<div id="lineGraph"></div>
<script>
const nodes = [
{ x: 0, y: 0, z: 0, value: [1, 2, 3] },
{ x: 1, y: 1, z: 1, value: [4, 5, 6] },
{ x: 2, y: 0, z: 2, value: [7, 8, 9] },
{ x: 3, y: 1, z: 3, value: [10, 11, 12] },
{ x: 4, y: 0, z: 4, value: [13, 14, 15] }
];
const edges = [
{ source: 0, target: 1 },
{ source: 1, target: 2 },
{ source: 2, target: 3 },
{ source: 3, target: 4 }
];
const svg = d3.select("#myDiv")
.append("svg")
.attr("width", 500)
.attr("height", 500);
const node = svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("cx", function(d) { return d.x * 50 + 100; })
.attr("cy", function(d) { return d.y * 50 + 100; })
.attr("cz", function(d) { return d.z * 50 + 100; })
.attr("r", 10)
.style("fill", "red")
.on("click", function(d) {
const lineData = [{
x: [0, 1, 2],
y: d.value,
type: "scatter"
}];
Plotly.newPlot("lineGraph", lineData);
});
const line = svg.selectAll(".line")
.data(edges)
.enter().append("line")
.attr("x1", function(d) { return nodes[d.source].x * 50 + 100; })
.attr("y1", function(d) { return nodes[d.source].y * 50 + 100; })
.attr("z1", function(d) { return nodes[d.source].z * 50 + 100; })
.attr("x2", function(d) { return nodes[d.target].x * 50 + 100; })
.attr("y2", function(d) { return nodes[d.target].y * 50 + 100; })
.attr("z2", function(d) { return nodes[d.target].z * 50 + 100; })
.style("stroke", "red")
.style("stroke-width", 2);
</script>
</body>
</html>
We are expecting a 3D graph, since we have assinged all the co-ordinates in terms of x,y,z but when it is displayed in web browser, it doesn't show a 3D network.
I am trying to make a custom SVG that looks like this.
So far I have got this.
All of the data will be dynamic so I am trying to figure out how to use the radius to set the x/y axis. I have a example
const w = 400,
h = 400,
r = 160;
const STREAMS = [{
label: 'Emissions',
isSelected: true,
yAxis: -40
}, {
label: 'Energy Produced',
isSelected: false,
yAxis: -20
}, {
label: 'Energy Consumed',
isSelected: false,
yAxis: 0
}, {
label: 'Intensity',
isSelected: false,
yAxis: 20
}]
const SUB_STREAMS = [{
value: 0.15,
label: 'Total',
isSelected: true
}, {
value: 0.2,
label: 'CO2',
isSelected: false
}, {
value: 0.25,
label: 'Methane',
isSelected: false
}, {
value: 0.30,
label: 'N2O',
isSelected: false
}, {
value: 0.35,
label: 'Other',
isSelected: false
}];
const svg = d3.select("#foo")
.append("svg")
.attr("width", w)
.attr("height", h);
const g = svg.append("g")
.attr("transform", "translate(" + [w / 2, h / 2] + ")");
g.append("circle")
.attr("r", r)
.style("fill", "none")
.style("stroke", "black");
const points = g.selectAll(null)
.data(SUB_STREAMS)
.enter()
.append("circle")
.attr('stroke', 'dodgerblue')
.attr('stroke-width', 1)
.style("fill", function(d) {
return d.isSelected ? 'dodgerblue' : 'white'
})
.attr("r", 12)
.attr("cx", function(d) {
return r * Math.cos(d.value * Math.PI * 2 - Math.PI / 2)
})
.attr("cy", function(d) {
return r * Math.sin(d.value * Math.PI * 2 - Math.PI / 2)
})
points.on("click", function(d) {
console.log(d)
})
g.selectAll(null)
.data(SUB_STREAMS)
.enter()
.append('text')
.style('cursor', 'pointer')
.style('fill', 'black')
.attr('text-anchor', 'right')
.attr('font-size', '1.3em')
.attr('dx', (d) => r * Math.cos(d.value * Math.PI * 2 - Math.PI / 2))
.attr('dy', (d) => r * Math.sin(d.value * Math.PI * 2 - Math.PI / 2))
.text((d) => d.label)
const text = g
.selectAll('path')
.data(STREAMS)
.enter()
.append("text")
.attr("text-anchor", "left")
.attr('font-size', '1em')
.attr("y", function(d, a) {
return d.yAxis
})
.text((d) => d.label);
text.on("click", function(d) {
console.log(d)
})
var arc = d3.symbol().type(d3.symbolTriangle)
var line = g.selectAll('path')
.data(STREAMS)
.enter()
.append('path')
.attr('d', arc)
.attr('fill', 'red')
.attr('stroke', '#000')
.attr('stroke-width', 1)
.attr('transform', function(d) {
return `translate(-10,${d.yAxis - 5}) rotate(210)`;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="foo" />
Set the dominant-baseline (e.g., central) accordingly, and move the texts by the size of the circles, plus a little padding.
Here is your code with those changes:
const w = 500,
h = 400,
r = 160;
const STREAMS = [{
label: 'Emissions',
isSelected: true,
yAxis: -40
}, {
label: 'Energy Produced',
isSelected: false,
yAxis: -20
}, {
label: 'Energy Consumed',
isSelected: false,
yAxis: 0
}, {
label: 'Intensity',
isSelected: false,
yAxis: 20
}]
const SUB_STREAMS = [{
value: 0.15,
label: 'Total',
isSelected: true
}, {
value: 0.2,
label: 'CO2',
isSelected: false
}, {
value: 0.25,
label: 'Methane',
isSelected: false
}, {
value: 0.30,
label: 'N2O',
isSelected: false
}, {
value: 0.35,
label: 'Other',
isSelected: false
}];
const svg = d3.select("#foo")
.append("svg")
.attr("width", w)
.attr("height", h);
const g = svg.append("g")
.attr("transform", "translate(" + [w / 2, h / 2] + ")");
g.append("circle")
.attr("r", r)
.style("fill", "none")
.style("stroke", "black");
const points = g.selectAll(null)
.data(SUB_STREAMS)
.enter()
.append("circle")
.attr('stroke', 'dodgerblue')
.attr('stroke-width', 1)
.style("fill", function(d) {
return d.isSelected ? 'dodgerblue' : 'white'
})
.attr("r", 12)
.attr("cx", function(d) {
return r * Math.cos(d.value * Math.PI * 2 - Math.PI / 2)
})
.attr("cy", function(d) {
return r * Math.sin(d.value * Math.PI * 2 - Math.PI / 2)
})
points.on("click", function(d) {
console.log(d)
})
g.selectAll(null)
.data(SUB_STREAMS)
.enter()
.append('text')
.style('cursor', 'pointer')
.style('fill', 'black')
.attr('text-anchor', 'right')
.attr('font-size', '1.3em')
.attr('dx', (d) => 14 + r * Math.cos(d.value * Math.PI * 2 - Math.PI / 2))
.attr('dy', (d) => r * Math.sin(d.value * Math.PI * 2 - Math.PI / 2))
.text((d) => d.label)
const text = g
.selectAll('path')
.data(STREAMS)
.enter()
.append("text")
.attr("text-anchor", "left")
.attr('font-size', '1em')
.attr("y", function(d, a) {
return d.yAxis - 5
})
.text((d) => d.label);
text.on("click", function(d) {
console.log(d)
})
var arc = d3.symbol().type(d3.symbolTriangle)
var line = g.selectAll('path')
.data(STREAMS)
.enter()
.append('path')
.attr('d', arc)
.attr('fill', 'red')
.attr('stroke', '#000')
.attr('stroke-width', 1)
.attr('transform', function(d) {
return `translate(-10,${d.yAxis - 5}) rotate(210)`;
});
text {
dominant-baseline: central;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="foo" />
I am trying to create two charts, a stacked bar and a bar, each displaying a different dataset. But I would like to transition from the stacked bar chart to the bar chart when I click on a button and vice versa. The code I put together works only the first time, then after that when I want to transition back to the stacked bar chart from the bar chart all the bars stack on top of each other in the form of a single bar. Can someone point me in the right direction of how to transition back from bar to stacked bar? Any help would be appreciated. (I haven't really messed with the axes yet so it is normal that they are not changing).
Here is a link to how it currently looks:https://jhjanicki.github.io/stackbartobar/
Below is my code:
var value = 'stack';
var data = [{
name: "Shihuahuaco",
value: 1067,
china: 772
}, {
name: "Cachimbo",
value: 283,
china: 1
}, {
name: "Estoraque",
value: 204,
china: 150
}, {
name: "Cumala",
value: 154,
china: 0
}, {
name: "Ishpingo",
value: 108,
china: 3
}, {
name: "Huayruro",
value: 108,
china: 1
}, {
name: "Tornillo",
value: 61,
china: 4
}, {
name: "Congona",
value: 54,
china: 0
}, {
name: "Capirona",
value: 37,
china: 5
}, {
name: "Tahuari",
value: 33,
china: 14
}, {
name: "Marupa",
value: 33,
china: 1
}, {
name: "Quinilla",
value: 28,
china: 4
}, {
name: "Azucar huayo",
value: 22,
china: 15
}, {
name: "Protium sp.",
value: 19,
china: 0
}, {
name: "Nogal",
value: 15,
china: 6
}, {
name: "Ana Caspi",
value: 14,
china: 2
}, {
name: "Cedro",
value: 14,
china: 0
}, {
name: "Carapa guianensis",
value: 12,
china: 0
}, {
name: "Leche caspi",
value: 12,
china: 0
}, {
name: "Andiroba",
value: 11,
china: 0
}, {
name: "Copaiba",
value: 7,
china: 4
}, {
name: "Palo baston",
value: 6,
china: 0
}, {
name: "Moena",
value: 5,
china: 0
}, {
name: "Almendro",
value: 5,
china: 0
}, {
name: "Chancaquero",
value: 4,
china: 0
}, {
name: "Caimitillo",
value: 3,
china: 1
}, {
name: "Nogal amarillo",
value: 3,
china: 0
}, {
name: "Couma macrocarpa",
value: 3,
china: 0
}, {
name: "Tulpay",
value: 3,
china: 0
}, {
name: "Carapa",
value: 3,
china: 0
}, {
name: "Dacryodes olivifera",
value: 2,
china: 0
}, {
name: "Capinuri",
value: 2,
china: 2
}, {
name: "Brosimum alicastrum",
value: 2,
china: 0
}, {
name: "Paramachaerium ormosioide",
value: 2,
china: 0
}, {
name: "Brosimum sp.",
value: 2,
china: 0
}, {
name: "Manchinga",
value: 2,
china: 0
}];
// data for stacked bar
var points = [{
'lon': 105.3,
'lat': 33.5,
'name': 'China',
'GTF': 1024,
"ID": "CHN"
},
{
'lon': -70.9,
'lat': 18.8,
'name': 'Dominican Republic',
'GTF': 470,
"ID": "DOM"
},
{
'lon': -101,
'lat': 38,
'name': 'USA',
'GTF': 248,
"ID": "USA"
},
{
'lon': -102.5,
'lat': 22.7,
'name': 'Mexico',
'GTF': 220,
"ID": "MEX"
},
{
'lon': 2.98,
'lat': 46,
'name': 'France',
'GTF': 85,
"ID": "FRA"
}
];
//data for bar
var margin = {
top: 20,
right: 30,
bottom: 150,
left: 60
},
widthB = 700 - margin.left - margin.right,
heightB = 500 - margin.top - margin.bottom;
var dataIntermediate = ['value', 'china'].map(function(key, i) {
return data.map(function(d, j) {
return {
x: d['name'],
y: d[key]
};
})
})
var dataStackLayout = d3.layout.stack()(dataIntermediate);
var svg = d3.select("#chart").append("svg")
.attr("width", widthB + margin.left + margin.right)
.attr("height", heightB + margin.top + margin.bottom)
var gBar = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr('class', 'gBar');
var x = d3.scale.ordinal()
.rangeRoundBands([0, widthB], .2);
var y = d3.scale.linear()
.range([heightB, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(8)
.tickFormat(function(d) {
return y.tickFormat(4, d3.format(",d"))(d)
});
data.forEach(function(d) {
d.value = +d.value; // coerce to number
d.china = +d.china;
});
x.domain(dataStackLayout[0].map(function(d) {
return d.x;
}));
y.domain([0, d3.max(dataStackLayout[dataStackLayout.length - 1],
function(d) {
return d.y0 + d.y;
})]).nice();
var layer;
var bars;
//axes
gBar.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (heightB + 10) + ")")
.call(xAxis)
.selectAll("text")
.style('font-size', '14px')
.style('font-family', 'Alegreya')
.style("text-anchor", "end")
.attr("dx", "-0.40em")
.attr("dy", ".10em")
.attr("transform", function(d) {
return "rotate(-65)"
});
gBar.append("g")
.attr("class", "y axis")
.call(yAxis)
.selectAll("text")
.style('font-size', '16px')
.style('font-family', 'Alegreya');
function draw() {
if (value == 'stack') {
layer = gBar.selectAll(".stack")
.data(dataStackLayout);
layer.exit()
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(1500)
.style("fill", "none")
.remove();
layer.enter().append("g")
.attr("class", "stack")
.style("fill", function(d, i) {
return i == 0 ? '#b4d5c3' : '#ecaeb3';
});
bars = layer.selectAll("rect")
.data(function(d) {
return d;
});
// the "EXIT" set:
bars.exit()
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(1500)
.attr("y", y(0))
.attr("height", heightB - y(0))
.style('fill-opacity', 1e-6)
.remove();
// the "ENTER" set:
bars.enter().append("rect")
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(3000)
.attr("x", function(d) {
return x(d.x);
})
.attr("y", function(d) {
return y(d.y + d.y0);
})
.attr("height", function(d) {
return y(d.y0) - y(d.y + d.y0);
})
.attr("width", x.rangeBand());
// the "UPDATE" set:
bars.transition().delay(function(d, i) {
return 30 * i;
}).duration(1500).attr("x", function(d) {
return x(d.x);
})
.attr("width", x.rangeBand()) // constant, so no callback function(d) here
.attr("y", function(d) {
return y(d.y + d.y0);
})
.attr("height", function(d) {
return y(d.y0) - y(d.y + d.y0);
});
} else { // draw bar
x.domain(points.map(function(d) {
return d.name;
}));
y.domain([0, 1024]).nice();
bars = layer.selectAll("rect")
.data(points);
// the "EXIT" set:
bars.exit()
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(1500)
.attr("y", y(0))
.attr("height", heightB - y(0))
.style('fill-opacity', 1e-6)
.remove();
// the "ENTER" set:
bars.enter().append("rect")
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(3000)
.attr("x", function(d) {
return x(d.name);
})
.attr("y", function(d) {
return y(d.GTF);
})
.attr("height", function(d) {
return heightB - y(d.GTF);;
})
.attr("width", x.rangeBand());
// the "UPDATE" set:
bars.transition().delay(function(d, i) {
return 30 * i;
}).duration(1500).attr("x", function(d) {
return x(d.name);
})
.attr("width", x.rangeBand()) // constant, so no callback function(d) here
.attr("y", function(d) {
return y(d.GTF);
})
.attr("height", function(d) {
return heightB - y(d.GTF);
});
}
}
window.onload = draw();
$("#click").on('click', function() {
if (value == 'stack') {
value = 'bar';
} else {
value = 'stack';
}
draw();
});
body {
font-family: 'Alegreya', serif;
}
.axis text {
font: 10px sans-serif;
}
.axis path {
fill: none;
stroke: #000;
stroke-width: 0px;
shape-rendering: crispEdges;
}
.axis line {
fill: none;
stroke: #000;
stroke-width: 0.5px;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://d3js.org/d3.v3.js"></script>
<div id="chart"></div>
<p id="click"> click here to change </p>
The problem in your code is that you're changing the scales' domain for the bar chart, but you're not changing them back for the stacked bar chart.
Therefore, you should put this in the draw() section (conditional statement) for the stacked bar:
x.domain(dataStackLayout[0].map(function(d) {
return d.x;
}));
y.domain([0, d3.max(dataStackLayout[dataStackLayout.length - 1],
function(d) {
return d.y0 + d.y;
})]).nice();
Here is your code with that change (I also put a call for the x axis):
var value = 'stack';
var data = [{
name: "Shihuahuaco",
value: 1067,
china: 772
}, {
name: "Cachimbo",
value: 283,
china: 1
}, {
name: "Estoraque",
value: 204,
china: 150
}, {
name: "Cumala",
value: 154,
china: 0
}, {
name: "Ishpingo",
value: 108,
china: 3
}, {
name: "Huayruro",
value: 108,
china: 1
}, {
name: "Tornillo",
value: 61,
china: 4
}, {
name: "Congona",
value: 54,
china: 0
}, {
name: "Capirona",
value: 37,
china: 5
}, {
name: "Tahuari",
value: 33,
china: 14
}, {
name: "Marupa",
value: 33,
china: 1
}, {
name: "Quinilla",
value: 28,
china: 4
}, {
name: "Azucar huayo",
value: 22,
china: 15
}, {
name: "Protium sp.",
value: 19,
china: 0
}, {
name: "Nogal",
value: 15,
china: 6
}, {
name: "Ana Caspi",
value: 14,
china: 2
}, {
name: "Cedro",
value: 14,
china: 0
}, {
name: "Carapa guianensis",
value: 12,
china: 0
}, {
name: "Leche caspi",
value: 12,
china: 0
}, {
name: "Andiroba",
value: 11,
china: 0
}, {
name: "Copaiba",
value: 7,
china: 4
}, {
name: "Palo baston",
value: 6,
china: 0
}, {
name: "Moena",
value: 5,
china: 0
}, {
name: "Almendro",
value: 5,
china: 0
}, {
name: "Chancaquero",
value: 4,
china: 0
}, {
name: "Caimitillo",
value: 3,
china: 1
}, {
name: "Nogal amarillo",
value: 3,
china: 0
}, {
name: "Couma macrocarpa",
value: 3,
china: 0
}, {
name: "Tulpay",
value: 3,
china: 0
}, {
name: "Carapa",
value: 3,
china: 0
}, {
name: "Dacryodes olivifera",
value: 2,
china: 0
}, {
name: "Capinuri",
value: 2,
china: 2
}, {
name: "Brosimum alicastrum",
value: 2,
china: 0
}, {
name: "Paramachaerium ormosioide",
value: 2,
china: 0
}, {
name: "Brosimum sp.",
value: 2,
china: 0
}, {
name: "Manchinga",
value: 2,
china: 0
}];
var points = [{
'lon': 105.3,
'lat': 33.5,
'name': 'China',
'GTF': 1024,
"ID": "CHN"
}, {
'lon': -70.9,
'lat': 18.8,
'name': 'Dominican Republic',
'GTF': 470,
"ID": "DOM"
}, {
'lon': -101,
'lat': 38,
'name': 'USA',
'GTF': 248,
"ID": "USA"
}, {
'lon': -102.5,
'lat': 22.7,
'name': 'Mexico',
'GTF': 220,
"ID": "MEX"
}, {
'lon': 2.98,
'lat': 46,
'name': 'France',
'GTF': 85,
"ID": "FRA"
}];
var margin = {
top: 20,
right: 30,
bottom: 150,
left: 60
},
widthB = 700 - margin.left - margin.right,
heightB = 500 - margin.top - margin.bottom;
var dataIntermediate = ['value', 'china'].map(function(key, i) {
return data.map(function(d, j) {
return {
x: d['name'],
y: d[key]
};
})
})
var dataStackLayout = d3.layout.stack()(dataIntermediate);
var svgBar = d3.select("#chart").append("svg")
.attr("width", widthB + margin.left + margin.right)
.attr("height", heightB + margin.top + margin.bottom)
var gBar = svgBar.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr('class', 'gBar');
var x = d3.scale.ordinal()
.rangeRoundBands([0, widthB], .2);
var y = d3.scale.linear()
.range([heightB, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(8)
.tickFormat(function(d) {
return y.tickFormat(4, d3.format(",d"))(d)
});
data.forEach(function(d) {
d.value = +d.value; // coerce to number
d.china = +d.china;
});
x.domain(dataStackLayout[0].map(function(d) {
return d.x;
}));
y.domain([0, d3.max(dataStackLayout[dataStackLayout.length - 1],
function(d) {
return d.y0 + d.y;
})]).nice();
var layer;
// this part
var bars;
var gX = gBar.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (heightB + 10) + ")");
gBar.append("g")
.attr("class", "y axis")
.call(yAxis)
.selectAll("text")
.style('font-size', '16px')
.style('font-family', 'Alegreya');
function draw() {
if (value == 'stack') {
x.domain(dataStackLayout[0].map(function(d) {
return d.x;
}));
y.domain([0, d3.max(dataStackLayout[dataStackLayout.length - 1],
function(d) {
return d.y0 + d.y;
})]).nice();
layer = gBar.selectAll(".stack")
.data(dataStackLayout);
layer.exit()
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(1500)
.style("fill", "none")
.remove();
layer.enter().append("g")
.attr("class", "stack")
.style("fill", function(d, i) {
return i == 0 ? '#b4d5c3' : '#ecaeb3';
});
bars = layer.selectAll("rect")
.data(function(d) {
return d;
});
bars.exit()
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(1500)
.attr("y", y(0))
.attr("height", heightB - y(0))
.style('fill-opacity', 1e-6)
.remove();
bars.enter().append("rect")
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(3000)
.attr("x", function(d) {
return x(d.x);
})
.attr("y", function(d) {
return y(d.y + d.y0);
})
.attr("height", function(d) {
return y(d.y0) - y(d.y + d.y0);
})
.attr("width", x.rangeBand());
// the "UPDATE" set:
bars.transition().delay(function(d, i) {
return 30 * i;
}).duration(1500).attr("x", function(d) {
return x(d.x);
}) // (d) is one item from the data array, x is the scale object from above
.attr("width", x.rangeBand()) // constant, so no callback function(d) here
.attr("y", function(d) {
return y(d.y + d.y0);
})
.attr("height", function(d) {
return y(d.y0) - y(d.y + d.y0);
})
.style("fill-opacity", 1);
gX.call(xAxis)
.selectAll("text")
.style('font-size', '14px')
.style('font-family', 'Alegreya')
.style("text-anchor", "end")
.attr("dx", "-0.40em")
.attr("dy", ".10em")
.attr("transform", function(d) {
return "rotate(-65)"
});
} else {
x.domain(points.map(function(d) {
return d.name;
}));
y.domain([0, 1024]).nice();
// this part
bars = layer.selectAll("rect")
.data(points);
bars.exit()
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(1500)
.attr("y", y(0))
.attr("height", heightB - y(0))
.style('fill-opacity', 1e-6)
.remove();
bars.enter().append("rect")
.transition()
.delay(function(d, i) {
return 30 * i;
})
.duration(3000)
.attr("x", function(d) {
return x(d.name);
})
.attr("y", function(d) {
return y(d.GTF);
})
.attr("height", function(d) {
return heightB - y(d.GTF);;
})
.attr("width", x.rangeBand());
// the "UPDATE" set:
bars.transition().delay(function(d, i) {
return 30 * i;
}).duration(1500).attr("x", function(d) {
return x(d.name);
}) // (d) is one item from the data array, x is the scale object from above
.attr("width", x.rangeBand()) // constant, so no callback function(d) here
.attr("y", function(d) {
return y(d.GTF);
})
.attr("height", function(d) {
return heightB - y(d.GTF);
});
gX.call(xAxis);
}
}
window.onload = draw();
$("#click").on('click', function() {
if (value == 'stack') {
value = 'bar';
} else {
value = 'stack';
}
draw();
});
body {
font-family: 'Alegreya', serif;
}
.axis text {
font: 10px sans-serif;
}
.axis path {
fill: none;
stroke: #000;
stroke-width: 0px;
shape-rendering: crispEdges;
}
.axis line {
fill: none;
stroke: #000;
stroke-width: 0.5px;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://d3js.org/d3.v3.js"></script>
<div id="chart"></div>
<button id="click"> click here to change </button>
PS: Besides that, there is a lot of other minor changes you should do in your code, both for performance and design. As this is (now) a running code, I suggest you post further questions about how to improve it on Code Review, using the d3.js tag.
I'm having issues with my update() function. Here, within svg.append('rect') I have .on('click') where I simply change the data, then run update().
Why doesn't this work? How do I make it work?
var width = 640,
height = 480;
var graphNodes = [
{ id: 0, x: 39, y: 343, r: 15 },
{ id: 1, x: 425, y: 38, r: 15 },
{ id: 2, x: 183, y: 417, r: 15 },
{ id: 3, x: 564, y: 31, r: 15 },
{ id: 4, x: 553, y: 351, r: 15 },
{ id: 5, x: 454, y: 298, r: 15 },
{ id: 6, x: 493, y: 123, r: 15 },
{ id: 7, x: 471, y: 427, r: 15 },
{ id: 8, x: 142, y: 154, r: 15 }
];
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
svg.append('rect')
.attr('class', 'graph')
.attr('width', width)
.attr('height', height)
.attr('fill', 'lightblue')
.attr('opacity', 0.3)
.on('click', function(){
graphNodes[8].id = 'hey there'; // <----- Why doesn't this happen?
update();
});
var nodeGroup = svg.selectAll('.nodes')
.data(graphNodes, function(d){ return d.id; })
.enter().append('g')
.attr('class', 'node');
nodeGroup.append('circle')
.attr('cx', function(d) { return d.x })
.attr('cy', function(d) { return d.y })
.attr("r", function(d){ return d.r; })
.attr("fill", "gray");
nodeGroup.append('text')
.attr("dx", function(d){ return d.x + 20; })
.attr("dy", function(d){ return d.y + 5; })
.text(function(d) { return d.id });
function update() {
if(nodeGroup){
// Update nodes
var node = nodeGroup.data(graphNodes, function(d){ return d.id; }),
nodeEnter = node.enter().append('g')
.attr('class', 'node');
nodeEnter.append('circle')
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', function(d){ return d.r; })
.attr('fill', 'gray');
nodeEnter.append('text')
.attr("dx", function(d){ return d.x + 20; })
.attr("dy", function(d){ return d.y + 5; })
.text(function(d) { return d.id });
nodeGroup = nodeEnter.merge(node);
node.exit().remove();
}
}
Here's a fiddle
Typed this as a comment in the message you left me, but here it is as an answer.
You need to separate out the things you do on enter, on update and on exit. On enter you want to just append and set any attributes that never change. On update you want to add/change the text and add/change the radius. On exit you remove. Here I've properly handled the enter, update, exit paradigm:
// bind the data
var node = nodeGroup.data(graphNodes, function(d){ return d.id; }),
// this is the enter selection
nodeEnter = node.enter().append('g')
.attr('class', 'node');
// append to enter selection
// append and set color, we never change color
nodeEnter.append('circle')
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('fill', 'gray');
// again entering, append text and set position
nodeEnter.append('text')
.attr("dx", function(d){ return d.x + 20; })
.attr("dy", function(d){ return d.y + 5; });
// nodeGroup is the enter + update selection
nodeGroup = nodeEnter.merge(node);
// change the things we want to change on every update
nodeGroup.select("text")
.text(function(d) { return d.text ? d.text : d.id });
nodeGroup.select("circle")
.attr('r', function(d){ return d.r; })
// exit, just remove
node.exit().remove();
Running code:
var width = 640,
height = 480;
var graphNodes = [
{ id: 0, x: 39, y: 343, r: 15 },
{ id: 1, x: 425, y: 38, r: 15 },
{ id: 2, x: 183, y: 417, r: 15 },
{ id: 3, x: 564, y: 31, r: 15 },
{ id: 4, x: 553, y: 351, r: 15 },
{ id: 5, x: 454, y: 298, r: 15 },
{ id: 6, x: 493, y: 123, r: 15 },
{ id: 7, x: 471, y: 427, r: 15 },
{ id: 8, x: 142, y: 154, r: 15 }
];
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
svg.append('rect')
.attr('class', 'graph')
.attr('width', width)
.attr('height', height)
.attr('fill', 'lightblue')
.attr('opacity', 0.3)
.on('click', function(){
/*graphNodes.push({
x: d3.mouse(this)[0],
y: d3.mouse(this)[1],
id: graphNodes.length,
r: 15
});*/
graphNodes.splice(2, 1);
graphNodes[Math.floor(Math.random() * graphNodes.length)].text = "Tomato!";
graphNodes[Math.floor(Math.random() * graphNodes.length)].r = Math.random() * 30;
update();
});
var nodeGroup = svg.selectAll('.nodes')
.data(graphNodes, function(d){ return d.id; })
.enter().append('g')
.attr('class', 'node');
nodeGroup.append('circle')
.attr('cx', function(d) { return d.x })
.attr('cy', function(d) { return d.y })
.attr("r", function(d){ return d.r; })
.attr("fill", "gray");
nodeGroup.append('text')
.attr("dx", function(d){ return d.x + 20; })
.attr("dy", function(d){ return d.y + 5; })
.text(function(d) { return d.id });
function update() {
if(nodeGroup){
// Update nodes
var node = nodeGroup.data(graphNodes, function(d){ return d.id; }),
nodeEnter = node.enter().append('g')
.attr('class', 'node');
// this is the enter selection
// append and set color, we never change color
nodeEnter.append('circle')
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('fill', 'gray');
nodeEnter.append('text')
.attr("dx", function(d){ return d.x + 20; })
.attr("dy", function(d){ return d.y + 5; });
// nodeGroup is the enter + update selection
nodeGroup = nodeEnter.merge(node);
// change the things we want to change on every update
nodeGroup.select("text")
.text(function(d) { return d.text ? d.text : d.id });
nodeGroup.select("circle")
.attr('r', function(d){ return d.r; })
// exit, just remove
node.exit().remove();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>
I'm having a lot of trouble getting a circle to delete. In this example I want to delete the circle labeled "2" but it just deletes the last circle in the array. If you uncomment the commented part and comment the graphNodes.splice(2, 1), it works as it should adding a new circle. But the delete won't work.
What am I missing here?
var width = 640,
height = 480;
var graphNodes = [
{ id: 0, x: 39, y: 343, r: 15 },
{ id: 1, x: 425, y: 38, r: 15 },
{ id: 2, x: 183, y: 417, r: 15 },
{ id: 3, x: 564, y: 31, r: 15 },
{ id: 4, x: 553, y: 351, r: 15 },
{ id: 5, x: 454, y: 298, r: 15 },
{ id: 6, x: 493, y: 123, r: 15 },
{ id: 7, x: 471, y: 427, r: 15 },
{ id: 8, x: 142, y: 154, r: 15 }
];
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
svg.append('rect')
.attr('class', 'graph')
.attr('width', width)
.attr('height', height)
.attr('fill', 'lightblue')
.attr('opacity', 0.3)
.on('click', function(){
/*graphNodes.push({
x: d3.mouse(this)[0],
y: d3.mouse(this)[1],
id: graphNodes.length,
r: 15
});*/
graphNodes.splice(2, 1);
update();
});
var nodeGroup = svg.selectAll('.nodes')
.data(graphNodes, function(d){ return d.id; })
.enter().append('g')
.attr('class', 'node');
nodeGroup.append('circle')
.attr('cx', function(d) { return d.x })
.attr('cy', function(d) { return d.y })
.attr("r", function(d){ return d.r; })
.attr("fill", "gray");
nodeGroup.append('text')
.attr("dx", function(d){ return d.x + 20; })
.attr("dy", function(d){ return d.y + 5; })
.text(function(d) { return d.id });
function update() {
if(nodeGroup){
// Update nodes
var node = nodeGroup.data(graphNodes),
nodeEnter = node.enter().append('g')
.attr('class', 'node');
nodeEnter.append('circle')
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', function(d){ return d.r; })
.attr('fill', 'gray');
nodeEnter.append('text')
.attr("dx", function(d){ return d.x + 20; })
.attr("dy", function(d){ return d.y + 5; })
.text(function(d) { return d.id });
nodeGroup = nodeEnter.merge(node);
node.exit().remove();
}
}
Fiddle
When you re-bind your data in update function, you forgot your key function:
var node = nodeGroup.data(graphNodes, function(d){ return d.id; }),
Update fiddle.