i sucessfully rendered d3js area chart in a html page here is the code which is rendering sucessfully in chrome or mozilla.The name of the file is say temp.html.Here is the code
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>js graphs and charts libraries</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.js"></script>
<body>
<div id="dbar">
</div>
<script type="text/javascript">
var margin = {top:10, right: 20, bottom: 30,left: 40},
width = 960 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var svg = d3.select ("#dbar").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+")");
var parseDate = d3.time.format("%m-%Y").parse;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left");
var area = d3.svg.area().x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.count); });
d3.json("data/json.json", function(error, data) {
data.StoreVisitGraphCount.list.forEach(function(d) {
d.date = parseDate(d.date);
d.count = +d.count;
});
//console.log(data.StoreVisitGraphCount.list);
x.domain(d3.extent(data.StoreVisitGraphCount.list, function(d) {
return d.date; }));
y.domain([0, d3.max(data.StoreVisitGraphCount.list, function(d) {
`return d.count; })]);`
console.log(data.StoreVisitGraphCount.list);
svg.append("path")
.datum(data.StoreVisitGraphCount.list)
.attr("class", "area")
.attr("d", area);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
});
</script>
</body>
</html>
But when i am copy pasting this code to say "temp.jsp" page its not rendering and chart is not coming.
need suggestions
I see in your title you mention flexigrid :) You should update it.
To answer your question, there are 2 possible issues:
1. Make sure that "data/json.json" is served OK (not a 404 error)
2. Having the file as .jsp might mean you need extra code for it.
Related
I changed the attributes of the X axis to plot its values over the bars of the chart. But anywhere I put the code, the values are always plotted before ("behind") the bars and therefore we cannot see it.
//This part of the code is OUTSIDE of the update function (line 44 of the fiddle)
//append group to plot X axis
const xAxisGroup = g.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${HEIGHT})`)
//This part of the code is INSIDE the update function (line 92)
const xAxisCall = d3.axisBottom(x)
xAxisGroup.call(xAxisCall)
.selectAll("text")
.attr("x", "-5") // <<<--- I change this to 50
.attr("y", "10")
.attr("text-anchor", "end")
.attr("transform", "rotate(-45)") // <<<--- I changed this to -90
How would be possible to plot this values over the bars instead?
This is the fiddle of the original chart and this is the modified one. The month values may be behind the bars... :-/
In an SVG, whatever is painted later stays on top. So, just append your x axis <g> element after painting the rectangles. Alternatively, raise it:
xAxisGroup.raise()
Here's your code with that change:
//set general margin, width and height values
const MARGIN = {
LEFT: 128,
RIGHT: 8,
TOP: 32,
BOTTOM: 128
}
const WIDTH = 400 - MARGIN.LEFT - MARGIN.RIGHT
const HEIGHT = 300 - MARGIN.TOP - MARGIN.BOTTOM
//append svg plot area into div chart area
const svg = d3.select("#chart-area").append("svg")
.attr("width", WIDTH + MARGIN.LEFT + MARGIN.RIGHT)
.attr("height", HEIGHT + MARGIN.TOP + MARGIN.BOTTOM)
//append group into svg
const g = svg.append("g")
.attr("transform", `translate(${MARGIN.LEFT}, ${MARGIN.TOP})`)
//X label
g.append("text")
.attr("class", "x axis-label")
.attr("x", WIDTH / 2)
.attr("y", HEIGHT + 60)
.attr("font-size", "20px")
.attr("text-anchor", "middle")
.text("Month")
//Y label
g.append("text")
.attr("class", "y axis-label")
.attr("x", -(HEIGHT / 2))
.attr("y", -60)
.attr("font-size", "20px")
.attr("text-anchor", "middle")
.attr("transform", "rotate(-90)")
.text("Value")
//set scale for X axis
const x = d3.scaleBand()
.range([0, WIDTH])
.paddingInner(0.3)
.paddingOuter(0.2)
//set scale for Y axis
const y = d3.scaleLinear()
.range([HEIGHT, 0])
//append group to plot X axis
const xAxisGroup = g.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${HEIGHT})`)
//append group to plot Y axis
const yAxisGroup = g.append("g")
.attr("class", "y axis")
//import data
d3.csv("https://raw.githubusercontent.com/dbahiense/sotabook/main/revenues.csv").then(data => {
//parse values
data.forEach(d => {
d.revenue = Number(d.revenue)
d.profit = Number(d.profit)
})
//listen drop-down lists and trigger update function on change
//state
d3.select("#state")
.on("change", function(event, d) {
update(data)
})
//round
d3.select("#round")
.on("change", function(event, d) {
update(data)
})
//plot chart on page first load
update(data)
})
// update chart function
function update(data) {
//drop-down list listened values
let state = d3.select("#state").property("value")
let round = d3.select("#round").property("value")
//filter data by drop-down list values
let filteredData = data.filter(function(d) {
return d.state == state & d.round == round
})
//set domains for X and Y axes
x.domain(filteredData.map(d => d.month))
y.domain([0, d3.max(filteredData, d => d.revenue)])
const xAxisCall = d3.axisBottom(x)
const yAxisCall = d3.axisLeft(y)
//.tickFormat(d => d + "m")
yAxisGroup.call(yAxisCall)
// JOIN new data with old elements.
const rects = g.selectAll("rect")
.data(filteredData)
// EXIT old elements not present in new data.
rects.exit().remove()
// UPDATE old elements present in new data.
rects
.attr("y", d => y(d.revenue))
.attr("x", (d) => x(d.month))
.attr("width", x.bandwidth)
.attr("height", d => HEIGHT - y(d.revenue))
// ENTER new elements present in new data.
rects.enter().append("rect")
.attr("y", d => y(d.revenue))
.attr("x", (d) => x(d.month))
.attr("width", x.bandwidth)
.attr("height", d => HEIGHT - y(d.revenue))
.attr("fill", "steelblue")
xAxisGroup.raise()
.call(xAxisCall)
.selectAll("text")
.attr("x", "50")
.attr("y", "10")
.attr("text-anchor", "end")
.attr("transform", "rotate(-90)")
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<title>5.4</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- Custom styling -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- Bootstrap grid setup -->
<div class="container">
<div class="row">
<select id="state">
<option value="US">US</option>
<option value="EU">EU</option>
<option value="AS">AS</option>
</select>
<select id="round">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="row">
<div id="chart-area"></div>
</div>
</div>
<!-- External JS libraries -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!-- Custom JS below-->
</body>
</html>
I have the following example:
Please note that this code is just a combination of code I have found online.
Is there a way to prevent the Axis label/title from overlapping the axis scale/numbers? For example here the label is overlapping the numbers. In this example I could manually hardcode the label to be positioned more to the left which would work. However, what happens when we use changing data?
Say the data in the graph changes such that the y axis number may be in the 10s in one example but the next data set may have values in the 1,000,000's. Is it possible to make the graph/axis titles more dynamic/responsive to changing number lengths?
Is this something that can be done in the chart setup or is this as css issue. All suggestions or solutions are welcome.
I do not have much experience with D3.js so this may be a very simple issue to fix, I hope someone can help.
Thank you
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var width = 400,
height = 400;
var margin = {top: 50, bottom: 50, left: 50, right: 50}
var data = [0, 15, 20, 25, 30];
// Append SVG
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
// Create scale
var scale = d3.scaleLinear()
.domain([ d3.max(data) , d3.min(data)])
.range([0, width - 100]);
var yAxis = d3.axisLeft()
.scale(scale);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + eval(margin.left-3) + ",0)")
.call(yAxis);
svg.append("text")
.attr("class", "y label")
.attr("text-anchor", "end")
.attr("y", 6)
.attr("dy", ".75em")
.attr("transform", "rotate(-90)")
.text("My testing title");
d3.selectAll(".tick text")
.attr("x", "-20");
</script>
</body>
I usually go with the title coming down the right side:
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + eval(margin.left-3) + ",0)")
.call(yAxis)
.append("text")
.text("Title")
.attr("transform","rotate(90)")
.attr("y",-2)
.style('fill','black')
.style("text-anchor","start")
Recently, maybe after updating Java, I'm unable to load a scatter plot on Chrome, Firefox or Internet Explorer.
One month ago, everything loaded fine. I don't know what happened. I've updated Java to the last version and enabled ActiveX on Internet options, but nothing works for me.
I'll paste the html code. It loads the point info using a csv file saved in the same folder:
<!DOCTYPE html> <meta charset="utf-8"> <style>
body { font: 12px Arial;}
.axis path, .axis line { fill: none; stroke: grey; stroke-width: 1;
shape-rendering: crispEdges; }
</style> <body>
<script src="http://d3js.org/d3.v4.js"></script> <script>
// Set the dimensions of the canvas / graph var margin = {top: 30, right: 20, bottom: 50, left: 60}, width = 900 - margin.left - margin.right, height = 360 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.timeParse("%a %b %d %H:%M:%S %Z %Y "); // Set the ranges
var y = d3.scaleTime().range([height, 0]); var x = d3.scaleLinear().range([0, width]);
// Define the axes
var xAxis = d3.axisBottom().scale(x) .ticks(5);
var yAxis = d3.axisLeft().scale(y)
.ticks(5);
// Adds the svg canvas var svg = d3.select("body") .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 + ")"); // Get the data
d3.csv("data.csv", function(error, data) { var max = data.length; console.log(max)
data.forEach(function(d, i) { d.dateParsed = parseDate(d.date); d.close = max - i;
}); // Scale the range of the data
y.domain(d3.extent(data, function(d) { return d.dateParsed; })); x.domain([0, d3.max(data, function(d) { return d.close; })]);
// Add the scatterplot svg.selectAll("dot") .data(data)
.enter().append("circle") .attr("r", 0.5)
.attr("fill","#2980B9")
.attr("cy", function(d) { return y(d.dateParsed); }) .attr("cx", function(d) { return x(d.close); });
svg.append("g") .attr("class", "x axis")
.attr("transform", "translate(0," + height + ")") .call(xAxis);
svg.append("text") .attr("class", "x label") .attr("text-anchor", "middle") .attr("x", width / 2) .attr("y", height + 40) .text("followers");
svg.append("g")
.attr("class", "y axis") .call(yAxis);
svg.append("text") .attr("class", "y label") .attr("text-anchor", "middle") .attr("x", -height / 2 ) .attr("y", -50)
.attr("transform", "rotate(-90)") .text("account creation date");
});
</script> </body>
It looks like main issue is code is not formatted properly.
Many comments get mixed with the code caused the syntax errors.
I try to format the code and try to fix those errors.
As we don't have your data.csv file so we are not able to load that data but code creates the chart now.
You can try to use this code on your side with your data.csv file. It will help you to load the chart properly.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body { font: 12px Arial;}
.axis path, .axis line { fill: none; stroke: grey; stroke-width: 1;
shape-rendering: crispEdges; }
</style>
</head>
<body>
<script src="http://d3js.org/d3.v4.js"></script> <script>
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 50, left: 60}, width = 900 - margin.left - margin.right, height = 360 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.timeParse("%a %b %d %H:%M:%S %Z %Y "); // Set the ranges
var y = d3.scaleTime().range([height, 0]); var x = d3.scaleLinear().range([0, width]);
// Define the axes
var xAxis = d3.axisBottom().scale(x) .ticks(5);
var yAxis = d3.axisLeft().scale(y)
.ticks(5);
// Adds the svg canvas
var svg = d3.select("body") .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 + ")"); // Get the data
d3.csv("data.csv", function(error, data) { var max = data.length;
console.log(max);
data.forEach(function(d, i) { d.dateParsed = parseDate(d.date); d.close = max - i;
});
// Scale the range of the data
y.domain(d3.extent(data, function(d) { return d.dateParsed; })); x.domain([0, d3.max(data, function(d) { return d.close; })]);
// Add the scatterplot
svg.selectAll("dot") .data(data)
.enter().append("circle") .attr("r", 0.5)
.attr("fill","#2980B9")
.attr("cy", function(d) { return y(d.dateParsed); }) .attr("cx", function(d) { return x(d.close); });
svg.append("g") .attr("class", "x axis")
.attr("transform", "translate(0," + height + ")") .call(xAxis);
svg.append("text") .attr("class", "x label") .attr("text-anchor", "middle") .attr("x", width / 2) .attr("y", height + 40) .text("followers");
svg.append("g")
.attr("class", "y axis") .call(yAxis);
svg.append("text") .attr("class", "y label") .attr("text-anchor", "middle") .attr("x", -height / 2 ) .attr("y", -50)
.attr("transform", "rotate(-90)") .text("account creation date");
});
</script>
</body>
</html>
I am trying to use uploaded csv file data to be graphed using a d3. However I keep getting the error message that d3 isn't defined. Here's a sample of the code. The csv file is consists of 3 columns and 300 rows, separted by commas.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>A Plot</title>
<style>
</style>
<div id="plotA"></div>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 1000 - margin.left - margin.right,
height = 150 - margin.top - margin.bottom;
function Graph() {
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line1 = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.ECG); });
var svg1 = d3.select("#ecgplot").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 + ")");
d3.csv("#fileinput", function(error, data) {
data.forEach(function(d) {
d.date = +d.tm;
d.A = +d.A;
d.B = +d.B;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.A; }));
svg1.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("transform", "rotate(0)")
.attr("y", 28)
.attr("x", 450)
.attr("dx", ".71em")
.style("text-anchor", "end")
.text("Time (in second)");
svg1.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -35)
.attr("x", -35)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("A");
function transition1(path1) {
var totalLength1 = path1.node().getTotalLength();
path1
.attr("stroke-dasharray", totalLength1 + " " + totalLength1)
.attr("stroke-dashoffset", totalLength1)
.transition()
.duration(25000)
.ease("linear")
.attr("stroke-dashoffset", 0)
.each("end", function() { d3.select(this).call(transition1); });
}
});
}//End of Graph Function
</script>
</head>
<body>
<form>
Select a file: <input type="file" accept=".csv" id="fileinput">
<input type="button" id="addButton" value="Add to CSV File" onclick="Graph()" />
</form>
</body>
</html>
I guess this could be fixed for now by adding a timeout for all your js code, as your d3 lib is loaded from cdn which may take few seconds.
i sucessfully rendered d3js area chart in a html page here is the code which is rendering sucessfully in chrome or mozilla.The name of the file is say temp.html.Here is the code
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>js graphs and charts libraries</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.js"></script>
<body>
<div id="dbar">
</div>
<script type="text/javascript">
var margin = {top:10, right: 20, bottom: 30,left: 40},
width = 960 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var svg = d3.select ("#dbar").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+")");
var parseDate = d3.time.format("%m-%Y").parse;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left");
var area = d3.svg.area().x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.count); });
d3.json("data/json.json", function(error, data) {
data.StoreVisitGraphCount.list.forEach(function(d) {
d.date = parseDate(d.date);
d.count = +d.count;
});
//console.log(data.StoreVisitGraphCount.list);
x.domain(d3.extent(data.StoreVisitGraphCount.list, function(d) {
return d.date; }));
y.domain([0, d3.max(data.StoreVisitGraphCount.list, function(d) {
return d.count; })]);
console.log(data.StoreVisitGraphCount.list);
svg.append("path")
.datum(data.StoreVisitGraphCount.list)
.attr("class", "area")
.attr("d", area);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
});
</script>
</body>
</html>
But when i am copy pasting this code to say "temp.jsp" page its not rendering and chart is not coming.I am running this page on tomcat server.
need suggestions
It is not because you saved it as jsp or html page. You need to add charset="UTF-8" to your script declaration as d3.js uses UTF characters.
eg.
<script src="http://d3js.org/d3.v3.js" charset="UTF-8"></script>