Hi all i am trying to add dates in the d3.js how can i achieve this i am new to d3.js when i try add integers instead of date in the X-axis it is working good ..
How to declare date and assign them
I am here by attaching the JS and HTML file
thanks in advance:)
InitChart();
function InitChart() {
/*var lineData = [{
'x': 1,
'y': 5
}, {
'x': 20,
'y': 20
}, {
'x': 40,
'y': 10
}, {
'x': 60,
'y': 40
}, {
'x': 80,
'y': 5
}, {
'x': 100,
'y': 60
}];*/
var lineData=[{"y": 0.8076999999999999, "x": "2016-01-08 03:01:19.418110"}, {"y": 0.692666666666667, "x": "2016-01-08 05:10:19.838509"}, {"y": 0.5674333333333333, "x": "2016-01-08 09:54:13.022163"}]
var vis = d3.select("#visualisation"),
WIDTH = 1000,
HEIGHT = 500,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(lineData, function (d) {
return d.x;
}),
d3.max(lineData, function (d) {
return d.x;
})
]),
yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(lineData, function (d) {
return d.y;
}),
d3.max(lineData, function (d) {
return d.y;
})
]),
xAxis = d3.svg.axis()
.scale(xRange)
.tickSize(5)
.tickSubdivide(true),
yAxis = d3.svg.axis()
.scale(yRange)
.tickSize(5)
.orient("left")
.tickSubdivide(true);
vis.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var lineFunc = d3.svg.line()
.x(function (d) {
return xRange(d.x);
})
.y(function (d) {
return yRange(d.y);
})
.interpolate('linear');
vis.append("svg:path")
.attr("d", lineFunc(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
}
and here is the HTML
enter code here
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title> D3 trial </title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<svg id="visualisation" width="400" height="500"></svg>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'> </script>
<script src='http://d3js.org/d3.v3.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
Have a look here, the example uses TypeScripit, but the concepts are the same. You basically need to use d3.time.scale() instead of d3.scale.linear(). You also need to parse your dates. Updated xRange should look like:
xRange = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]).domain(d3.extent(lineData, function (d) {
return new Date(d.x);
}))
I used the extent function instead of d3.min and d3.max, which has the same effect but with shorter notation.
Related
I am trying to make a simple chart in d3, where I am plotting date (as string) vs frequency. But, I am getting error. Can someone help me out?
SNIPPET:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<svg width="1000" height="500"></svg>
<script>
//module declaration
var app = angular.module('myApp',[]);
//Controller declaration
app.controller('myCtrl', function($scope){
//custom data
var data = [
{x: "2016-01-10", y: "10.02"},
{x: "2016-02-10", y: "15.05"},
{x: "2016-03-10", y: "50.02"},
{x: "2016-04-10", y: "40.01"},
{x: "2016-05-10", y: "10.08"},
{x: "2016-06-10", y: "29.07"},
{x: "2016-07-10", y: "45.02"}
];
var mySVG = d3.select("svg");
var svgWidth = mySVG.attr("width");
var svgHeight = mySVG.attr("height");
var margins = {top: 20,right: 20,bottom: 20,left: 50};
var xRange = d3.scale.linear()
.range([margins.left, svgWidth - margins.right])
.domain([d3.min(data, function (d) {return d.x;}), d3.max(data, function (d) {return d.x;}) ]);
var yRange = d3.scale.linear()
.range([svgHeight - margins.top, margins.bottom])
.domain([d3.min(data, function (d) { return d.y; }), d3.max(data, function (d) { return d.y;}) ]);
var xAxis = d3.svg.axis()
.scale(xRange)
.tickSize(5)
.tickSubdivide(true);
var yAxis = d3.svg.axis()
.scale(yRange)
.tickSize(5)
.orient("left")
.tickSubdivide(true);
mySVG.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (svgHeight - margins.bottom) + ")")
.call(xAxis);
mySVG.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (margins.left) + ",0)")
.call(yAxis);
var lineFunc = d3.svg.line()
.x(function (d) {
return xRange(d.x);
})
.y(function (d) {
return yRange(d.y);
})
.interpolate('linear');
mySVG.append("svg:path")
.attr("d", lineFunc(data))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
});
</script>
</body>
</html>
** Error: **
var xRange = d3.scale.linear() <<<<< Error line
Please, help me in making the line chart along with x and y axis with date and frequency on them plotted. Kindly, help out.
Updated Snippet:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<svg width="1000" height="500"></svg>
<script>
//module declaration
var app = angular.module('myApp',[]);
//Controller declaration
app.controller('myCtrl', function($scope){
//custom data
var data = [
{x: "2016-01-10", y: "10.02"},
{x: "2016-02-10", y: "15.05"},
{x: "2016-03-10", y: "50.02"},
{x: "2016-04-10", y: "40.01"},
{x: "2016-05-10", y: "10.08"},
{x: "2016-05-10", y: "29.07"},
{x: "2016-05-10", y: "45.02"}
];
var mySVG = d3.select("svg");
var svgWidth = mySVG.attr("width");
var svgHeight = mySVG.attr("height");
var margins = {top: 20,right: 20,bottom: 20,left: 50};
var xRange = d3.scaleLinear()
.range([margins.left, svgWidth - margins.right])
.domain([d3.min(data, function (d) {return d.x;}), d3.max(data, function (d) {return d.x;}) ]);
var yRange = d3.scaleLinear()
.range([svgHeight - margins.top, margins.bottom])
.domain([d3.min(data, function (d) { return d.y; }), d3.max(data, function (d) { return d.y;}) ]);
var xAxis = d3.axisBottom(xRange)
.scale(xRange)
.tickSize(5);
var yAxis = d3.axisLeft(yRange)
.scale(yRange)
.tickSize(5)
.orient("left");
mySVG.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (svgHeight - margins.bottom) + ")")
.call(xAxis);
mySVG.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (margins.left) + ",0)")
.call(yAxis);
var lineFunc = d3.line()
.x(function (d) {
return xRange(d.x);
})
.y(function (d) {
return yRange(d.y);
})
.curve(d3.curveLinear);
mySVG.append("svg:path")
.attr("d", lineFunc(data))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
});
</script>
</body>
</html>
New Error:
You're using d3 v4.x, not the old v3. Thus, you have to modify your code.
These are the necessary changes:
var xRange = d3.scaleLinear()//keep the domain and range
var yRange = d3.scaleLinear()//keep the domain and range
var xAxis = d3.axisBottom(xRange)
.tickSize(5);
var yAxis = d3.axisLeft(yRange)
.tickSize(5);
var lineFunc = d3.line()//etc...
For the line generator, change interpolate for curve.
Also, get rid of tickSubdivide.
EDIT: you have additional problems in your fiddle: the values are strings, but they should be numbers. Besides that, if you're using dates, you'll have to parse them.
Here is your fiddle, without using the dates: https://jsfiddle.net/gerardofurtado/fawe63t8/
I have a stacked bar chart here not cooperating.
For some reason. The part where I have my code update is not working.
At this point the code seems fine but I am just not able to get the transition to occur
Anyone know how to do this?
Thanks!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>US2016</title>
<!-- d3 and plugins -->
<script src="http://d3js.org/d3.v3.js"></script>
<!-- custom css -->
<style type="text/css">
body {
font: 10px sans-serif;
}
</style>
</head>
<body>
<h2>Random</h4>
<div id="stacked-rep"></div>
<script>
var repColors = ['#403153','#9e7742','#0084ab','#e30513'];
var repColorsLight = ['#e5dae7','#deba96','#c5d7e9','#f6b89f'];
var repCandidates = ["Trump", "Cruz", "Rubio", "Kasich"];
var carnival_colors = ["blue", "lightblue"];
//Width and height
var m = {top: 10, right: 10, bottom: 10, left: 10}, // margins
h = 150 - m.left - m.right, // height
w = 960 - m.top - m.bottom; // width
//Create SVG element
var svg = d3.select("#stacked-rep")
.append("svg")
.attr("width", w)
.attr("height", h);
function cumulChart(id, dataset) {
// Set up stack method
var stack = d3.layout.stack();
//Data, stacked
stack(dataset);
// Set up scales
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset[0].length))
.rangeRoundBands([0, h], 0.2); // This is actually the Y scale (candidates)
var yScale = d3.scale.linear()
.domain([0,
d3.sum(dataset, function(d) {return d[0].y;})*1.2
])
.range([0, w]); // This is actually the X Scale (States)
// Add a group for each row of data
var groups = svg.selectAll("g")
.data(dataset)
.enter()
.append("g")
.classed("g_stacked elements", true)
// .attr("class", "g_stacked elements")
.attr("transform", "translate(" + m.left + ",0)");
// Add a rect for each data value
var rects = groups
.selectAll("rect")
.data(function(d) { return d; });
rects.enter()
.append("rect")
.attr("class", "stacked")
.attr("stacked_state", function(d) { return "st"+ d.state; })
.attr("x", function(d) {
return yScale(d.y0);
})
.attr("y", function(d, i) {
return xScale(i);
})
.attr("width", function(d) {
return yScale(d.y);
})
.attr("height", xScale.rangeBand())
.style("fill", function(d, i) {
if (d.state == 19){
return carnival_colors[1];
}
else {
return carnival_colors[0];
}
})
.style("stroke", function(d, i) {
if (d.state == 19){
return d3.rgb(carnival_colors[1]).darker() ;
}
else {
return d3.rgb(carnival_colors[0]).darker() ;
}
})
/*.on("mouseover", function(d) {
console.log(d.state);
})*/;
// transition
rects.transition() // this is to create animations
.duration(500) // 500 millisecond
.ease("bounce")
.delay(500)
// .attr("class", "stacked")
// .attr("stacked_state", function(d) { return "st"+ d.state; })
.attr("x", function(d) {
return yScale(d.y0);
})
.attr("y", function(d, i) {
return xScale(i);
})
.attr("width", function(d) {
return yScale(d.y);
})
.attr("height", xScale.rangeBand());
};
var data = [
[{
"state": 19,
"x": "Trump1",
"y": 2000
}],
[{
"state": 33,
"x": "Trump2",
"y": 3000
}]
];
cumulChart("#stacked-rep", data);
// create a function to randomize things
function rand_it(x){
return Math.floor((Math.random() * x) + 1);
};
setInterval(function(){
var object = [
[{
"state": 19,
"x": "Trump1",
"y": rand_it(20)
}],
[{
"state": 33,
"x": "Trump2",
"y": rand_it(20)
}]
];
cumulChart("#stacked-rep", object);
console.log(object[0][0].y,"---",object[1][0].y);
}, 3000);
</script>
</body>
</html>
Just figured it out.
The data part was not updating in the function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>US2016</title>
<!-- d3 and plugins -->
<script src="http://d3js.org/d3.v3.js"></script>
<!-- custom css -->
<style type="text/css">
body {
font: 10px sans-serif;
}
</style>
</head>
<body>
<h2>Random</h4>
<div id="stacked-rep"></div>
<script>
var repColors = ['#403153','#9e7742','#0084ab','#e30513'];
var repColorsLight = ['#e5dae7','#deba96','#c5d7e9','#f6b89f'];
var repCandidates = ["Trump", "Cruz", "Rubio", "Kasich"];
var carnival_colors = ["blue", "lightblue"];
//Width and height
var m = {top: 10, right: 10, bottom: 10, left: 10}, // margins
h = 150 - m.left - m.right, // height
w = 960 - m.top - m.bottom; // width
//Create SVG element
var svg = d3.select("#stacked-rep")
.append("svg")
.attr("width", w)
.attr("height", h);
// Add a group for each row of data
var data = [
[{
"state": 19,
"x": "Trump1",
"y": 2000
}],
[{
"state": 33,
"x": "Trump2",
"y": 3000
}]
];
var groups = svg.selectAll("g")
.data(data)
.enter()
.append("g")
.classed("g_stacked_elements", true)
// .attr("class", "g_stacked elements")
.attr("transform", "translate(" + m.left + ",0)");
function cumulChart(id, dataset) {
// Set up stack method
var stack = d3.layout.stack();
//Data, stacked
stack(dataset);
// console.log("the data sum is:", d3.sum(dataset, function(d) {return d[0].y;}));
// Set up scales
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset[0].length))
.rangeRoundBands([0, h], 0.2); // This is actually the Y scale (candidates)
var yScale = d3.scale.linear()
.domain([0,
d3.sum(dataset, function(d) {return d[0].y;})*1.2])
.range([0, w]); // This is actually the X Scale (States)
// console.log(xScale);
// Add a rect for each data value
groups_w_data = svg.selectAll("g")
.data(data);
var rects = groups_w_data
.selectAll("rect")
.data(function(d) { return d; });
rects.enter()
.append("rect")
.attr("class", "stacked")
.attr("stacked_state", function(d) { return "st"+ d.state; })
.attr("x", function(d) {
return yScale(d.y0);
})
.attr("y", function(d, i) {
return xScale(i);
})
.attr("width", function(d) {
return yScale(d.y);
})
.attr("height", xScale.rangeBand())
.style("fill", function(d, i) {
if (d.state == 19){
return carnival_colors[1];
}
else {
return carnival_colors[0];
}
})
.style("stroke", function(d, i) {
if (d.state == 19){
return d3.rgb(carnival_colors[1]).darker() ;
}
else {
return d3.rgb(carnival_colors[0]).darker() ;
}
})
/*.on("mouseover", function(d) {
console.log(d.state);
})*/;
// transition
rects.transition() // this is to create animations
.duration(500) // 500 millisecond
.ease("bounce")
.delay(500)
// .attr("class", "stacked")
// .attr("stacked_state", function(d) { return "st"+ d.state; })
.attr("x", function(d) {
console.log("This is the X value: ", yScale(d.y0));
return yScale(d.y0);
})
.attr("width", function(d) {
console.log("This is the width value: ", yScale(d.y));
return yScale(d.y);
})
};
cumulChart("#stacked-rep", data);
// create a function to randomize things
function rand_it(x){
return Math.floor((Math.random() * x) + 1);
};
setInterval(function(){
var object = [
[{
"state": 19,
"x": "Trump1",
"y": rand_it(20)
}],
[{
"state": 33,
"x": "Trump2",
"y": rand_it(20)
}]
];
data = object;
cumulChart("#stacked-rep", data);
console.log(object[0][0].y,"---",object[1][0].y);
}, 3000);
</script>
</body>
</html>
I'm creating a bar chart where hovering over each rectangle will generate a tooltip. So I created a "title" attribute for each rectangle and this was working
var hist = this.svg.selectAll(".hist")
.data(displayData, function(d) { return d.time; });
hist.enter().append("rect")
.attr('title', function (d) {
return tooltipDateFmt(d.time) + ": " + d.value.toFixed(1) + " gallons"; })
.attr("class", "hist");
hist.transition().duration(400)
.attr("x", function (d) { return x(d.time); })
.attr("y", function (d) { return y(d.value); })
.attr("width", function (d) { return 2.5; })
.attr("height", function (d) { return height - y(d.value); });
hist.exit().remove();
$('svg .hist').tooltip({
'container': 'body',
'placement': 'top'
});
But I then realized the titles are not updating when I updated the rects by clicking on a button and bind a new set of data into them. So I put the title in the update phase
var hist = this.svg.selectAll(".hist")
.data(displayData, function(d) { return d.time; });
hist.enter().append("rect")
.attr("class", "hist");
hist.transition().duration(400)
.attr('title', function (d) {
return tooltipDateFmt(d.time) + ": " + d.value.toFixed(1) + " gallons"; })
.attr("x", function (d) { return x(d.time); })
.attr("y", function (d) { return y(d.value); })
.attr("width", function (d) { return 2.5; })
.attr("height", function (d) { return height - y(d.value); });
hist.exit().remove();
But this is not showing any tooltips. Can anyone tell me what I have been wrong with?
bootstrap tooltip inserts a div (with the original title) into the DOM for each tooltip and then hides/shows it on mouseover. Changing the title later does not change the inserted div.
Instead of setting a title, I would use the title option and return a dynamic title.
$('svg .hist').tooltip({
'container': 'body',
'placement': 'top',
'title': function(){
var d = d3.select(this).datum(); // get data bound to rect
return tooltipDateFmt(d.time) + ": " + d.value.toFixed(1) + " gallons"; });
}
});
Here's a working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link data-require="bootstrap-css#3.3.1" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script data-require="jquery#2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script data-require="bootstrap#3.3.2" data-semver="3.3.2" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
</style>
</head>
<body>
<button id="changeTips">Change Tips</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var data = [
{
x: 1660,
y: 1
},{
x: 1670,
y: 2
},{
x: 1680,
y: 3
},{
x: 1690,
y: 4
}
];
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.range([0,width])
.domain([1650, 1700]);
var y = d3.scale.linear()
.range([height, 0])
.domain([0,5]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
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 + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var barWidth = (width / xAxis.ticks()[0]);
var bars = svg.selectAll(".bar")
.data(data)
.enter().append("rect")
/*
.attr('title', function (d) {
return d.y;
})
*/
.attr("class","bar")
.attr("width", barWidth)
.attr("x", function(d) { return x(d.x) - (barWidth / 2); })
.attr("y", function(d) { return y(d.y); })
.attr("height", function(d) { return height - y(d.y); });
var showY = true;
$('svg .bar').tooltip({
'container': 'body',
'placement': 'top',
'title': function(){
if (showY)
return (d3.select(this).datum().y);
else
return (d3.select(this).datum().x);
}
});
d3.select('#changeTips').on('click',function(){
showY = !showY;
});
</script>
</body>
</html>
Using data-original-title worked for me:
Instead of .attr('title', ...), use .attr('data-original-title', ...)
do it in both update and enter
i'm on the project for finishing my degree on computation, and i have a problem with D3, basically it works if I pass the data directly to the code, but with the data on a file, it says "n does not exist". I don't know why is this happening, here's my code:
PD: If anyone needs a sample of my data file, just ask for it.
Thanks in advance!
<code>
<!DOCTYPE html>
<meta charset="utf-8">
<title>Causa básica</title>
<style>
.axis path, .axis line
{
fill: none;
stroke: #777;
shape-rendering: crispEdges;
}
.axis text
{
font-family: 'Arial';
font-size: 13px;
}
.tick
{
stroke-dasharray: 1, 2;
}
.bar
{
fill: FireBrick;
}
</style>
<svg id="visualisation" width="1000" height="500"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
InitChart();
function InitChart() {
/*
var lineData = [{ //don't know if this is needed in source: <script src="http://d3js.org/d3.csv.js">
'x': 1, //, This is the sample data
'y': 1.0807955e-01
}, {
'x': 2,
'y': 1.2815365e-01
}, {
'x': 3,
'y': 9.3269178e-02
}, {
'x': 4,
'y': 9.3894191e-02
}];*/
var lineData;
d3.tsv("data.tsv", function(data) {
lineData=data //my data, that doesn't work
});
var vis = d3.select("#visualisation"),
WIDTH = 1000,
HEIGHT = 500,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(lineData, function (d) {
return d.x;
}),
d3.max(lineData, function (d) {
return d.x;
})
]),
yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(lineData, function (d) {
return d.y;
}),
d3.max(lineData, function (d) {
return d.y;
})
]),
xAxis = d3.svg.axis()
.scale(xRange)
.tickSize(5)
.tickSubdivide(true),
yAxis = d3.svg.axis()
.scale(yRange)
.tickSize(5)
.orient("left")
.tickSubdivide(true);
vis.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var lineFunc = d3.svg.line()
.x(function (d) {
return xRange(d.x);
})
.y(function (d) {
return yRange(d.y);
})
.interpolate('basis');
vis.append("svg:path")
.attr("d", lineFunc(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
}
</script>
</code>
Asynchronous issue.
the function
d3.tsv("data.tsv", function(data) {
lineData=data //my data, that doesn't work
});
is called after the execution of the rest of code.
You can try to move all the code inside the function and after lineData=data;. Or build a function:
var lineData;
d3.tsv("data.tsv", function(data) {
seeData(data);
});
function seeData(lineData) {
var vis = d3.select("#visualisation"),
WIDTH = 1000,
HEIGHT = 500,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
// etc etc
}
Hi I have done with chart preparation , but as per my requirement I want to add x axis value like inside the bar column. In My dummy data I have x axis as 'A', 'B','C','D'. How to move these letters inside bar column.
<script type="text/javascript">
$(document).ready(function(){
InitChart1();
});
function InitChart() {
var barData = [{
'x': 'A',
'y': 50
}, {
'x': 'B',
'y': 75
}, {
'x': 'C',
'y': 110
}, {
'x': 'D',
'y': 150
}];
var vis = d3.select('#visualisation1'),
WIDTH = 500,
HEIGHT = 500,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
xRange = d3.scale.ordinal().rangeRoundBands([MARGINS.left, WIDTH - MARGINS.right], 0.1).domain(barData.map(function (d) {
return d.x;
})),
yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0,
d3.max(barData, function (d) {
return d.y;
})
]),
xAxis = d3.svg.axis()
.scale(xRange)
.tickSize(5)
.tickSubdivide(true),
yAxis = d3.svg.axis()
.scale(yRange)
.tickSize(5)
.orient("left")
.tickSubdivide(true);
vis.append('svg:g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + (HEIGHT - MARGINS.bottom) + ')')
.call(xAxis);
vis.append('svg:g')
.attr('class', 'y axis')
.attr('transform', 'translate(' + (MARGINS.left) + ',0)')
.call(yAxis);
vis.selectAll('rect')
.data(barData)
.enter()
.append('rect')
.attr('x', function (d) {
return xRange(d.x);
})
.attr('y', function (d) {
return yRange(d.y);
})
.attr('width', 75)
.attr('height', function (d) {
return ((HEIGHT - MARGINS.bottom) - yRange(d.y));
})
.attr('fill', 'grey');
}</script>
I believe you are looking for labels rather then axis ticks. This tutorial should walk you through it.
http://alignedleft.com/tutorials/d3/making-a-bar-chart