Display multiple d3.js charts in a single html page - javascript

I have the the d3.js code which is pasted here.
I am trying to display more than one graphs in the same page. Though the d3.js code is same. Say one from data1.json and the other from data2.json. Following is the snippet which is bothering me.
<svg width="960" height="960"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg2 = d3.select("svg"),
margin = 20,
diameter = +svg2.attr("width"),
g = svg2.append("g").attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");
As per different answers in SO here, here, here, here or here, the solution seems to be one of the following:
Use different variable name to hold svgs such as svg1, svg2.. etc..
which I have done.
Use a method as described here.
var chart1 = d3.select("#area1")
.append("svg")
Method two is not working for me, as it shows blank page.
How to resolve this. I am sure that I am not getting the syntax correctly.

There's no problem at all using multiple SVGs on the same page. Here's an example:
var svg1 = d3.select("#svg1");
svg1.append("circle")
.attr("cx",100)
.attr("cy", 100)
.attr("r", 90)
.attr("fill", "red");
var svg2 = d3.select("#svg2");
svg2.append("circle")
.attr("cx",100)
.attr("cy", 100)
.attr("r", 90)
.attr("fill", "blue");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="200" height="200" id="svg1"></svg>
<svg width="200" height="200" id="svg2"></svg>

There is no need for repeating all the code, as you're doing right now. Don't repeat yourself.
An easy alternative is wrapping all your D3 code in a function that has two parameters, selector and url:
function draw(selector, url){
//code here
};
Then, inside that function draw, you set the position of your SVG:
var svg = d3.select(selector).append("svg")...
And the URL you get the data:
d3.json(ulr, function(error, root) {...
After that, just call the draw function twice, with different arguments:
draw(selector1, url1);
draw(selector2, url2);
Here is a demo, read it carefully to see how it works:
draw("#svg1", "#data1");
draw("#svg2", "#data2");
function draw(selector, url){
var data = d3.csvParse(d3.select(url).text())
var width = 500,
height = 150;
var svg = d3.select(selector)
.append("svg")
.attr("width", width)
.attr("height", height);
var xScale = d3.scalePoint()
.domain(data.map(function(d) {
return d.name
}))
.range([50, width - 50])
.padding(0.5);
var yScale = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.value
}) * 1.1])
.range([height - 20, 6]);
var line = d3.line()
.x(function(d){ return xScale(d.name)})
.y(function(d){ return yScale(d.value)});
svg.append("path")
.attr("d", line(data))
.attr("stroke", "teal")
.attr("stroke-width", "2")
.attr("fill", "none");
var xAxis = d3.axisBottom(xScale);
var yAxis = d3.axisLeft(yScale);
svg.append("g").attr("transform", "translate(0,130)")
.attr("class", "xAxis")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(50,0)")
.attr("class", "yAxis")
.call(yAxis);
}
pre {
display: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div>First SVG</div>
<div id="svg1"></div>
<div>Second SVG</div>
<div id="svg2"></div>
<pre id="data1">name,value
foo,8
bar,1
baz,7
foobar,9
foobaz,4</pre>
<pre id="data2">name,value
foo,1
bar,2
baz,3
foobar,9
foobaz,8</pre>

If the two charts use the same code, I think the most d3-like way to go about it would be
var width = 960,
height = 960,
margin = 30;
var svgs = d3.select('#area1')
.selectAll('svg')
.data([json1, json2])
.enter()
.append('svg')
.attr('width', width)
.attr('height', height)
svgs.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.each(function(d) {console.log(d)}) // will log json1, then json2
You'll then have json1 and json2 bound to each of the newly appended svgs, and all code that follows will be done to both.
var width = 200,
height = 100,
margin = 30;
var svgs = d3.select('#area1')
.selectAll('svg')
.data([{text:'thing1'}, {text:'thing2'}])
.enter()
.append('svg')
.attr('width', width)
.attr('height', height);
svgs.append("text")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.text(function(d) {return d.text});
<script src="https://d3js.org/d3.v4.js"></script>
<div id='area1'></div>

Related

why my two graph of d3.js is not combined in the single page?

I have made two separate graph on separate page of Bar and pie chart respectively and now i wanted to combine this two graph in the single page so that I can have a dashboard. but when i start to combine to two graph in the main page its not happening and they overlap of each other.
Code:
https://github.com/Mustafa2911/d3-design/blob/main/combine.html
Combine file contain: Code of both pie and bar chart.
Bar file contain: Code of bar chart.
Pie chart contain: Code of pie chart.
Tried this with your code.
Scroll to see the bar graph axis.
NOTE: The bar graph data will not be available ∵ it is from the demo1.csv file in your repository.
Hope this helps.
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<style>
#my_dataviz {
display: inline-block;
width: 50%;
}
</style>
</head>
<body>
<div id="my_dataviz"></div>
<script>
// set the dimensions and margins of the graph
var width = 800
height = 450
margin = 40
// The radius of the pieplot is half the width or half the height (smallest one). I subtract a bit of margin.
var radius = Math.min(width, height) / 2 - margin
// append the svg object to the div called 'my_dataviz'
var svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Create dummy data
var data = {
Corporation_Tax: 15,
Income_Tax: 15,
Customs: 5,
Union_Excise_Duties: 7,
Good_and_Service_tax: 16,
Non_tax_Revenue: 5,
Non_Dept_Capital_Receipt: 2,
Borrowings_Liabilities: 35
}
// set the color scale
var color = d3.scaleOrdinal()
.domain(["a", "b", "c", "d", "e", "f", "g", "h"])
.range(d3.schemeSet1);
// Compute the position of each group on the pie:
var pie = d3.pie()
.sort(null) // Do not sort group by size
.value(function(d) {
return d.value;
})
var data_ready = pie(d3.entries(data))
// The arc generator
var arc = d3.arc()
.innerRadius(radius * 0.5) // This is the size of the donut hole
.outerRadius(radius * 0.8)
// Another arc that won't be drawn. Just for labels positioning
var outerArc = d3.arc()
.innerRadius(radius * 0.9)
.outerRadius(radius * 0.9)
// Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
svg
.selectAll('allSlices')
.data(data_ready)
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d) {
return (color(d.data.key))
})
.attr("stroke", "white")
.style("stroke-width", "2px")
.style("opacity", 1)
// Add the polylines between chart and labels:
svg
.selectAll('allPolylines')
.data(data_ready)
.enter()
.append('polyline')
.attr("stroke", "black")
.style("fill", "none")
.attr("stroke-width", 1)
.attr('points', function(d) {
var posA = arc.centroid(d) // line insertion in the slice
var posB = outerArc.centroid(d) // line break: we use the other arc generator that has been built only for that
var posC = outerArc.centroid(d); // Label position = almost the same as posB
var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2 // we need the angle to see if the X position will be at the extreme right or extreme left
posC[0] = radius * 0.95 * (midangle < Math.PI ? 1 : -1); // multiply by 1 or -1 to put it on the right or on the left
return [posA, posB, posC]
})
// Add the polylines between chart and labels:
svg
.selectAll('allLabels')
.data(data_ready)
.enter()
.append('text')
.text(function(d) {
console.log(d.data.key);
return d.data.key
})
.attr('transform', function(d) {
var pos = outerArc.centroid(d);
var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2
pos[0] = radius * 0.99 * (midangle < Math.PI ? 1 : -1);
return 'translate(' + pos + ')';
})
.style('text-anchor', function(d) {
var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2
return (midangle < Math.PI ? 'start' : 'end')
})
</script>
<style>
#my_dataviz {
display: inline-block;
width: 50%;
}
</style>
<div id="my_dataviz_es"></div>
<script>
// set the dimensions and margins of the graph
var margin = {
top: 20,
right: 30,
bottom: 40,
left: 160
},
width = 460,
height = 400;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz_es")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Parse the Data
d3.csv("demo1.csv", function(data) {
// Add X axis
var x = d3.scaleLinear()
.domain([0, 550000])
.range([0, width]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "translate(-10,0)rotate(-45)")
.style("text-anchor", "end");
// Y axis
var y = d3.scaleBand()
.range([0, height])
.domain(data.map(function(d) {
return d.Country;
}))
.padding(.1);
svg.append("g")
.call(d3.axisLeft(y))
//Bars
svg.selectAll("myRect")
.data(data)
.enter()
.append("rect")
.attr("x", x(0))
.attr("y", function(d) {
return y(d.Country);
})
.attr("width", function(d) {
return x(d.Value);
})
.attr("height", y.bandwidth())
.attr("fill", "#69b3a2")
// .attr("x", function(d) { return x(d.Country); })
// .attr("y", function(d) { return y(d.Value); })
// .attr("width", x.bandwidth())
// .attr("height", function(d) { return height - y(d.Value); })
// .attr
})
</script>
</body>
</html>
EDIT: See here - https://codepen.io/KZJ/pen/rNpqvdq?editors=1011 - for changes made reg. the below comment
what if I want to have my bar chart at the top and on right side i want to have my pie chart
Changed -
a) Both charts were using the same name 'svg' to d3.select() the divs. This caused the charts to overlap.
b) Modified width, height, transform, and added some border CSS - only for demonstration purposes - It can be removed/edited as required.
FYR this is how it looks now -

d3.event.pageX & d3.mouse(this)[0]

I tried to figure out the difference between 'd3.event.pageX' & 'd3.mouse(this)[0]'.
I guessed both are same but,
when I console.log both,
the value was different by '8' in my code.
var height=600;
var width=600;
var graphgap=60;
d3.csv('./details.csv').then(function(data){
var svg =d3.select('section').append('svg')
.attr('width',600).attr('height',600)
.on('mousemove',mousemove)
drawrect(data);
})
function drawrect(data){
let bars=d3.select('svg').selectAll('rect').data(data);
bars.enter().append('rect').classed('bargraph',true)
.attr('x',function(d,i){return (i+1)*graphgap})
.attr('y',function(d){return height-(d.Age)*5})
.attr('width',55)
.attr('height',function(d){return (d.Age)*(5)})
}
function mousemove(){
let mouselocation =[];
d3.select('svg').append('text')
.text(d3.event.pageX)
.attr('x',d3.event.pageX)
.attr('y',d3.event.pageY)
console.log(d3.event.pageX)
console.log(d3.mouse(this)[0])
}
So, I think these two are two different things.
Can anyone let me know why it makes a difference?
The reason why I tried to figure this out is because I was re-writing the code below.
<script>
// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 60},
width = 460 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_IC.csv",function(data) {
// Add X axis --> it is a date format
var x = d3.scaleLinear()
.domain([1,100])
.range([ 0, width ]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add Y axis
var y = d3.scaleLinear()
.domain([0, 13])
.range([ height, 0 ]);
svg.append("g")
.call(d3.axisLeft(y));
// This allows to find the closest X index of the mouse:
var bisect = d3.bisector(function(d) { return d.x; }).left;
// Create the circle that travels along the curve of chart
var focus = svg
.append('g')
.append('circle')
.style("fill", "none")
.attr("stroke", "black")
.attr('r', 8.5)
.style("opacity", 0)
// Create the text that travels along the curve of chart
var focusText = svg
.append('g')
.append('text')
.style("opacity", 0)
.attr("text-anchor", "left")
.attr("alignment-baseline", "middle")
// Create a rect on top of the svg area: this rectangle recovers mouse position
svg
.append('rect')
.style("fill", "none")
.style("pointer-events", "all")
.attr('width', width)
.attr('height', height)
.on('mouseover', mouseover)
.on('mousemove', mousemove)
.on('mouseout', mouseout);
// Add the line
svg
.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", d3.line()
.x(function(d) { return x(d.x) })
.y(function(d) { return y(d.y) })
)
// What happens when the mouse move -> show the annotations at the right positions.
function mouseover() {
focus.style("opacity", 1)
focusText.style("opacity",1)
}
function mousemove() {
// recover coordinate we need
var x0 = x.invert(d3.mouse(this)[0]);
var i = bisect(data, x0, 1);
selectedData = data[i]
focus
.attr("cx", x(selectedData.x))
.attr("cy", y(selectedData.y))
focusText
.html("x:" + selectedData.x + " - " + "y:" + selectedData.y)
.attr("x", x(selectedData.x)+15)
.attr("y", y(selectedData.y))
}
function mouseout() {
focus.style("opacity", 0)
focusText.style("opacity", 0)
}
})
</script>
In documentation is written:
While you can use the native event.pageX and event.pageY, it is often
more convenient to transform the event position to the local
coordinate system of the container that received the event using
d3.mouse, d3.touch or d3.touches.
d3.event
d3.mouse - uses local coordinate (without margin (60px))
d3.event.pageX - uses global coordinate (with margin (60px))
But local cordinate start on 68px. I guess 8 pixels is used to describe the y-axis.

Need to create a line within x and y axis in d3 v5

I have a bar chart graph, created with d3 v5, which needs to have a straight line as a "limit" depending on a specific y value.
This is the graph I currently have and the line which should be created (added on paint)
Here is the code in order to create the graph
(async ()=> {
const response = await fetch('https://api);
const myJson = await response.json();
//need myJson.DailyDelvs to be the y value of the line
// set the dimensions and margins of the graph
var margin = {top: 30, right: 30, bottom: 70, left: 60},
width = 400 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom
tip = d3.tip()
.attr('class', 'd3-tip')
.html(function(d) { return "DAY: "+d.DIA+"<br/>PO: "+d.PO_ID })
// append the svg object to the body of the page
var svg = d3.select("#dailyDeliveryVolume")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")")
.call(tip)
var datos
// get the data
d3.json("https://api2").then(function(data) {
datos = data
d3.select("#dailyDeliveryVolume_spinner").remove();
var x = d3.scaleBand()
.range([ 0, width ])
.domain([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31])
.padding(0.05);
var xAxis = d3.axisBottom(x)
.tickValues(x.domain().filter(function(d,i){ return !(i%2)}));
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
var y = d3.scaleLinear()
.domain([0, d3.max(data.STD, function(d) { return +d.PO_ID })])
.range([ height, 0]);
svg.append("g")
.call(d3.axisLeft(y))
// Bars
svg.selectAll("mybar")
.data(data.STD)
.enter()
.append("rect")
.attr("x", function(d) { return x(d.DIA); })
.attr("y", function(d) { return y(d.PO_ID); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.PO_ID); })
.attr("fill", "#69b3a2")
.attr("border-color", "black")
.on("mouseover", tip.show)
.on("mouseleave", tip.hide )
})
})()
In order to create the line, I tried the following code, right after I append the bars, which is causing an error
var linea = drawLine(svg, x, y, data.STD);
var drawLine = function(svg, x, y, data) {
var lineFunc = d3.line()
.x(function(obj) {
return x(obj.DIA);
})
.y(function(obj) {
return y(obj.PO_ID);
});
var linea = svg.append("linea") //SVG Paths represent the outline of a shape that can be stroked, filled, used as a clipping path, or any combination of all three. We can draw rectangles, circles, ellipses, polylines, polygons, straight lines, and curves through path
.attr("d", lineFunc(data))
.attr("stroke", '#87CEEB')
.attr("stroke-width", 3)
.attr("fill", "black");
return linea;
};
dailyDeliveryVolume.js:64 Uncaught (in promise) TypeError: drawLine is not a function at dailyDeliveryVolume.js:64
I also tried to directly append a line to the svg with fixed attributes x1, x2, y1 and y2 but seems it is done base on the entire container and can't get to suit the x and y axis values.
The goal is that myJson.DailyDelvs is the y value (based on the y scale values) and then is just stright thru all width.
One issue is that you need to call the function (var linea = drawLine(...)) after defining the function (var drawLine = ...).
I think you can also simplify what you're doing by drawing a <line> directly:
svg.append("line")
.attr("x1", x(0))
.attr("x2", x(31))
.attr("y1", y(obj.PO_ID))
.attr("y2", y(obj.PO_ID))
.attr("stroke", '#87CEEB')
.attr("stroke-width", 3)
.attr("fill", "black");
(I'm not sure which value you are trying to use for the y-axis, but it seems like it should be similar to above...)

D3.js: Elements don't have any width

I'm trying to append four rectto my svg. I can see them appended in chrome's dev tools. However, they're never rendered because it seems I have an issue with passing on the width value.
Besides, in version 3 of D3 I receive the following error message in the browser:
d3.v3.min.js:1 Error: attribute width: Expected length, "NaN".
There's no error message in version 4.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="https://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<script type="text/javascript">
var data = [20,3,60,800];
var width = 500,
height = 500;
var widthScale = d3.scale.linear()
.domain([0, 80])
.range(0, width);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var bars = svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("width", function (d) { return widthScale(d); } )
.attr("height", 50)
.attr("fill", "steelblue")
.attr("y", function (d, i) { return i * 100});
</script>
</body>
</html>
The only difference between v3 and v4 is this line (scaleLinear):
var widthScale = d3.scaleLinear().domain([0, 80]).range(0, width);
Any help highly appreciated.
range has to be an array. The documentation is clear:
linear.range([values]):
If values is specified, sets the scale's output range to the specified array of values
So, instead of:
.range(0, width);
It should be:
.range([0, width]);
If you use .range(0, width) D3 v3.x returns a NaN, and you see in the console:
Error: attribute width: Expected length, "NaN".
However, D3 v4.x returns undefined, and you see no error message in the console.
Here is your working code:
var data = [20,3,60,800];
var width = 500,
height = 500;
var widthScale = d3.scale.linear()
.domain([0, 80])
.range([0, width]);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var bars = svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("width", function (d) { return widthScale(d); } )
.attr("height", 50)
.attr("fill", "steelblue")
.attr("y", function (d, i) { return i * 100});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

error in D3.js code regarding particular place

i am making a college project on D3.js. i copied the code of pie chart from Scott Murray's book on D3.js. It works. But now i am facing a problem.
1)i want to show the pie chart in a particular place in html page ,but i am unable to do it.
like
2)when i resubmit the data its created another pie chart very next to old one.But i want to first delete old one and then create new one at same place.
please help me.
the fiddle is-http://jsbin.com/acatof/3/edit
D3: Pie layout
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<style type="text/css">
text {
font-family: sans-serif;
font-size: 12px;
fill: white;
}
</style>
<body>
<script type="text/javascript">
//Width and height
var w = 300;
var h = 300;
var dataset = [ 5, 10, 20, 45, 6, 25 ];
var outerRadius = w / 2;
var innerRadius = 0;
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var pie = d3.layout.pie();
//Easy colors accessible via a 10-step ordinal scale
var color = d3.scale.category10();
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Set up groups
var arcs = svg.selectAll("g.arc")
.data(pie(dataset))
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");
//Draw arc paths
arcs.append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc);
//Labels
arcs.append("text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
});
</script>
</body>
To put it in an element, for example, a <div> instead on the <body>, you just need to replace the selection on which the svg will be appended, to the selector of the element where you want to put the graph.
So instead of
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
You can do:
var svg = d3.select("#container")
.append("svg")
.attr("width", w)
.attr("height", h);
Provided that there is a <div id = "container"></div> somewhere on your page.
Hope this helps :)

Categories