D3 barchart with ajax data - d3.js

I am using the example chart from http://bl.ocks.org/mbostock/3885304 and rather than use the tsv example, I wish to use json from api call.
The chart does display, in the sense that it gives a large blob of what looks like a single bar.
The JSON returned from the api.php call looks like this
[{"id":"2","name":"wombat","total":"98000","record_date":"2016-01-21 00:00:00"},{"id":"5","name":"wombat","total":"96000","record_date":"2016-02-21 00:00:00"},{"id":"8","name":"wombat","total":"93000","record_date":"2016-03-21 00:00:00"},{"id":"11","name":"wombat","total":"91000","record_date":"2016-04-21 00:00:00"},{"id":"14","name":"wombat","total":"92000","record_date":"2016-05-21 00:00:00"},{"id":"17","name":"wombat","total":"83000","record_date":"2016-06-21 00:00:00"},{"id":"20","name":"wombat","total":"81000","record_date":"2016-07-21 00:00:00"}]
Plunker
Thanks
Kevin

Your json data array has the record_date property instead of event_time. But your code refers to event_time property. Try replacing them with the record_date.
I could not find no other errors in your code.
Here is the working Code Snippet:
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.ordinal()
.rangeRoundBands([0, width], .1);
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")
.ticks(10, "");
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 + ")");
var data = [{
"id": "2",
"name": "wombat",
"total": "98000",
"record_date": "2016-01-21 00:00:00"
}, {
"id": "5",
"name": "wombat",
"total": "96000",
"record_date": "2016-02-21 00:00:00"
}, {
"id": "8",
"name": "wombat",
"total": "93000",
"record_date": "2016-03-21 00:00:00"
}, {
"id": "11",
"name": "wombat",
"total": "91000",
"record_date": "2016-04-21 00:00:00"
}, {
"id": "14",
"name": "wombat",
"total": "92000",
"record_date": "2016-05-21 00:00:00"
}, {
"id": "17",
"name": "wombat",
"total": "83000",
"record_date": "2016-06-21 00:00:00"
}, {
"id": "20",
"name": "wombat",
"total": "81000",
"record_date": "2016-07-21 00:00:00"
}];
var k = [];
data.forEach(function(d) {
d.record_date = d.record_date;
d.total = +d.total;
k.push(d.record_date)
});
x.domain(data.map(function(d) {
return d.record_date;
}));
y.domain([0, d3.max(data, function(d) {
return d.total;
})]);
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("Count");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return x(d.record_date);
})
.attr("width", x.rangeBand())
.attr("y", function(d) {
return y(d.total);
})
.attr("height", function(d) {
return height - y(d.total);
});
function type(d) {
d.total = +d.total;
return d;
}
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Related

D3.js - Zoom/Transform multiple lines

I'm struggling with this problem, I'm trying to zoom my chart, specifically the lines that i draw dynamically.
Here my fiddle: https://jsfiddle.net/w3j89Lf3/
<link href="http://getbootstrap.com/examples/justified-nav/justified-nav.css" rel="stylesheet">
<style>
.axis path {
fill: none;
stroke: #777;
shape-rendering: crispEdges;
}
.axis text {
font-family: Lato;
font-size: 13px;
}
.legend {
font-size: 14px;
font-weight: bold;
}
.grid .tick {
stroke: lightgrey;
opacity: 0.7;
}
.grid path {
stroke-width: 0;
}
</style>
My code works well with x and y axes, but doesn't work for my lines as you can see in my function "zoomed".
<div class="container">
<div class="jumbotron">
<svg id="visualisation" width="1000" height="500"></svg>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
function InitChart() {
var data = [{
"Client": "ABC",
"sale": "202",
"year": "2000"
}, {
"Client": "ABC",
"sale": "215",
"year": "2002"
}, {
"Client": "ABC",
"sale": "179",
"year": "2004"
}, {
"Client": "ABC",
"sale": "199",
"year": "2006"
}, {
"Client": "ABC",
"sale": "134",
"year": "2008"
}, {
"Client": "ABC",
"sale": "176",
"year": "2010"
}, {
"Client": "XYZ",
"sale": "100",
"year": "2000"
}, {
"Client": "XYZ",
"sale": "215",
"year": "2002"
}, {
"Client": "XYZ",
"sale": "179",
"year": "2004"
}, {
"Client": "XYZ",
"sale": "199",
"year": "2006"
}, {
"Client": "XYZ",
"sale": "134",
"year": "2008"
}, {
"Client": "XYZ",
"sale": "176",
"year": "2013"
}];
var dataGroup = d3.nest()
.key(function(d) {
return d.Client;
})
.entries(data);
var vis = d3.select("#visualisation"),
WIDTH = 1000,
HEIGHT = 500,
MARGINS = {
top: 50,
right: 20,
bottom: 50,
left: 50
};
//Aggiungi ASSI con scala
xScale = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(data, function(d) {
return d.year;
}), d3.max(data, function(d) {
return d.year;
})]),
yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(data, function(d) {
return d.sale;
}), d3.max(data, function(d) {
return d.sale;
})]),
xAxis = d3.svg.axis()
.scale(xScale),
yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
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);
//Aggiungi GRID
function make_x_axis() {
return d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(10)
}
function make_y_axis() {
return d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(10)
}
vis.append("svg:g")
.attr("class", "grid")
.attr("transform", "translate(0," + HEIGHT + ")")
.call( make_x_axis()
.tickSize(-HEIGHT, 0, 0)
.tickFormat("")
)
vis.append("svg:g")
.attr("class", "grid")
.call( make_y_axis()
.tickSize(-WIDTH, 0, 0)
.tickFormat("")
)
var lineGen = d3.svg.line()
.x(function(d) {
return xScale(d.year);
})
.y(function(d) {
return yScale(d.sale);
})
.interpolate("basis"); //linear
lSpace = WIDTH/dataGroup.length;
dataGroup.forEach(function(d, i) {
color = "hsl(" + Math.random() * 360 + ",100%,50%)";
vis.append('svg:path')
.attr('d', lineGen(d.values))
.attr('stroke', color)
.attr('stroke-width', 2)
.attr('id', 'line_'+d.key)
.attr('fill', 'none');
vis.append("text")
.attr("x", (lSpace / 2) + i * lSpace)
.attr("y", HEIGHT)
//.style("stroke", "black")
.style("fill", color)
.attr("class", "legend").on('click', function() {
var active = d.active ? false : true;
var opacity = active ? 0 : 1;
d3.select("#line_" + d.key).style("opacity", opacity);
d.active = active;
})
.text(d.key);
});
function zoomed() {
vis.select(".x.axis").call(xAxis);
vis.select(".y.axis").call(yAxis);
vis.selectAll('path.line').attr("d", function(d) {return line(d.values)}); **-> HERE I WOULD ZOOM/TRANSFORM**
}
var zoom = d3.behavior.zoom()
.x(xScale)
.y(yScale)
.scaleExtent([1, 10])
.on("zoom", zoomed);
vis.call(zoom)
}
InitChart();
</script>
</div>
</div>
There are two things that should be changed to make it work.
First in zoom function you end up with an empty selection because the paths do not have line class. Add line class to paths while generating them to make the .selectAll('path.line') work.
Second, you did not bind data to the paths so you cannot use it later in the zoom function. If you pass an anonymous function as the second parameter of .attr then the first argument of this function (d, in your case) will be the data bound to the selection. To make this line work:
vis.selectAll('path.line').attr("d", function(d) {return line(d.values)});
you have to add data to the paths. One way to do it is like this:
vis.append('svg:path').datum(d)
However, there is a better way to bind data and enter new elements than the forEach loop you use. I recommend this very helpful tutorial by Scott Murray that explains d3 data bind.
Here is the updated jsfiddle.

Issue in fetching data from nested json to construct bar graph in d3

here is the json data..
[
{
"month":"2016-01",
"top_services":[
{
"domain":" EESEL-PROD-XCRM",
"service":" Subscriber-1_0",
"operation":" getSubscriberProfile",
"total_trans":333646
},
{
"domain":" EESEL-PROD-XCRM",
"service":" ProductQuery-3_0",
"operation":" listSubscriberProducts3",
"total_trans":242797
},
{
"domain":" ELYSEES-PROD",
"service":" GetCachedNetworkSettings-2_0",
"operation":" electroencephalographic",
"total_trans":242123
},
]
}
]
var data=[ { "month":"2016-01", "children": [ { "name": "Al Montoya", "saves": 15.5 }, { "name": "Alex Stalock", "saves": 14.7 }, { "name": "Anders Lindback", "saves": 12.4 }, { "name": "Anton Khudobin", "saves": 21.4 } ] } ] ;
data=data[0].children;
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.ordinal()
.rangeRoundBands([0, width], .1);
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");
//.ticks(10, "%");
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 + ")");
//d3.tsv("data.tsv", type, function(error, data) {
//if (error) throw error;
x.domain(data.map(function(d) { return d.name; }));
y.domain([0, d3.max(data, function(d) { return d.saves; })]);
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("Frequency");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.name); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.saves); })
.attr("height", function(d) { return height - y(d.saves); });
//});
function type(d) {
d.saves = +d.saves;
return d;
}
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
First of all we need to convert the data into needed format, i.e. array of objects, by
var data=[ { "month":"2016-01", "children": [ { "name": "Al Montoya", "saves": 15.5 }, { "name": "Alex Stalock", "saves": 14.7 }, { "name": "Anders Lindback", "saves": 12.4 }, { "name": "Anton Khudobin", "saves": 21.4 } ] } ] ;
data=data[0].children;
So now data is having array of objects.Hope you can understand the remaining.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
SynonymTable synTable = new SynonymTable();
synTable.registerSynonym("tv","dhoordharshan, television");
synTable.registerSynonym("radio","akashavani");
synTable.registerSynonym("house ","home");
System.out.println("tv-"+synTable.getSynonyms("tv"));
}
}
class SynonymTable {
private Map<String, Set<String>> synonymTable = new HashMap<>();
public Set<String> getSynonyms(String word) {
return synonymTable.get(word);
}
public void registerSynonym(String word, String... synonymsOfWord) {
for (String syn : synonymsOfWord) {
putSynonymTable(word, syn); // synonym(word) = syn
putSynonymTable(syn, word); // synonym(syn) = word
}
}
private void putSynonymTable(String word, String synonymOfWord) {
Set syns = synonymTable.get(word);
if (syns == null) {
syns = new TreeSet<String>();
synonymTable.put(word, syns);
}
syns.add(synonymOfWord);
}
}
Try this, It'll give you all the synonyms. If this is not you are looking for then ask for ....

Stacked Vertical Bar Chart Labeling - D3.js

I wanted to add data labels on each boxes in bars but couldn't figure out how to do it.
All examples I found on the net was getting data from simple arrays, not an external JSON file like I did.
Here is my code:
<!DOCTYPE html>
<meta charset="utf-8">
<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>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
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.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
//.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
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 + ")");
d3.json("data.json", function(error, data) {
if (error) throw error;
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "Brand"; }));
data.forEach(function(d) {
var y0 = 0;
d.stores = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.total = d.stores[d.stores.length - 1].y1;
});
data.sort(function(a, b) { return b.total - a.total; });
x.domain(data.map(function(d) { return d.Brand; }));
y.domain([0, d3.max(data, function(d) { return d.total; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var brand = svg.selectAll(".brand")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) { return "translate(" + x(d.Brand) + ",0)"; });
brand.selectAll("rect")
.data(function(d) { return d.stores; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
</script>
data.json
[
{
"Brand": "A",
"LAST 3 MONTHS": "22",
"LAST MONTH": "15",
"THIS YEAR": "36",
"ALL STORES": "72"
},
{
"Brand": "B",
"LAST 3 MONTHS": "10",
"LAST MONTH": "24",
"THIS YEAR": "15",
"ALL STORES": "61"
},
{
"Brand": "C",
"LAST 3 MONTHS": "10",
"LAST MONTH": "11",
"THIS YEAR": "23",
"ALL STORES": "67"
},
{
"Brand": "D",
"LAST 3 MONTHS": "10",
"LAST MONTH": "17",
"THIS YEAR": "21",
"ALL STORES": "81"
},
{
"Brand": "E",
"LAST 3 MONTHS": "10",
"LAST MONTH": "31",
"THIS YEAR": "51",
"ALL STORES": "92"
},
{
"Brand": "F",
"LAST 3 MONTHS": "10",
"LAST MONTH": "27",
"THIS YEAR": "35",
"ALL STORES": "76"
},
{
"Brand": "G",
"LAST 3 MONTHS": "10",
"LAST MONTH": "23",
"THIS YEAR": "19",
"ALL STORES": "59"
},
{
"Brand": "H",
"LAST 3 MONTHS": "32",
"LAST MONTH": "27",
"THIS YEAR": "15",
"ALL STORES": "45"
}
]
How can I show data labels on each boxes in the bars? (like: 22, 15, 36, 72 on the first bar etc.)
I want a final view on all bars like the first bar on this picture:
https://dl.dropboxusercontent.com/u/58490833/Yollanan%20Dosyalar/stackedbar.jpg
Do the same code as you did for all rectangle .. but you have to either pass original object with it to read value or you can get it from parent node like this
brand.selectAll("text")
.data(function(d) { return d.stores; })
.enter().append("text")
.attr("y", function(d) { return y(d.y1)+10; })
.attr("x", x.rangeBand()/2)
.attr("text-anchor","middle")
.style("fill",'#fff')
.text(function(d) { return d3.select(this)[0][0].parentNode.__data__[d.name]; });
here is fiddle with solution hope this is what you needed ..

D3 Stacked Chart with array or JSON data

I want to create a Stacked bar chart like http://bl.ocks.org/mbostock/3886208 . But I don't want to use CSV file.
How can I create Stacked chart using array or JSON data?
In csv we are using like this :
State,Post,Comment
AL,310504,552339
AK,52083,85640
How can I define data in array or json like
var data = []
do it like this
<!DOCTYPE html>
<meta charset="utf-8">
<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>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
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.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
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 + ")");
var data = [
{
"State": "AL",
"Under 5 Years": 10,
"5 to 13 Years": 20,
"14 to 17 Years": 30,
"18 to 24 Years": 40,
"25 to 44 Years": 50,
"45 to 64 Years": 60,
"65 Years and Over": 70
},{
"State": "AK",
"Under 5 Years": 15,
"5 to 13 Years": 25,
"14 to 17 Years": 35,
"18 to 24 Years": 45,
"25 to 44 Years": 55,
"45 to 64 Years": 65,
"65 Years and Over": 75
}];
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "State"; }));
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.total = d.ages[d.ages.length - 1].y1;
});
data.sort(function(a, b) { return b.total - a.total; });
x.domain(data.map(function(d) { return d.State; }));
y.domain([0, d3.max(data, function(d) { return d.total; })]);
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("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
</script>
I know late for replying to this one. I modified #heshjse's code for D3 version 4. When I tried the above code with d3 v3, it's working fine. But we had limitation to use version 4, I was getting problem bcoz of some changes in d3 v4. So adding the code which worked for me. I hope it helps.
This should work fine for Json format in d3 v4.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="Dash"></div>
</body>
</html>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
drawStackChart();
});
//Draw Stack Chart
var marginStackChart = { top: 20, right: 20, bottom: 30, left: 40 },
widthStackChart = 500 - marginStackChart.left - marginStackChart.right,
heightStackChart = 300 - marginStackChart.top - marginStackChart.bottom;
var xStackChart = d3.scaleBand()
.range([0, widthStackChart])
.padding(0.1);
var yStackChart = d3.scaleLinear()
.range([heightStackChart, 0]);
var colorStackChart = d3.scaleOrdinal(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"])
var canvasStackChart = d3.select("#Dash").append("svg")
.attr("width", widthStackChart + marginStackChart.left + marginStackChart.right)
.attr("height", heightStackChart + marginStackChart.top + marginStackChart.bottom)
.append("g")
.attr("transform", "translate(" + marginStackChart.left + "," + marginStackChart.top + ")");
function drawStackChart() {
var data = [
{
"Year": "2012",
"Category1": "20",
"Category2": "5",
"Category3": "5",
"Category4": "5",
"Category5": "5",
"Category6": "5",
"Category7": "5",
"Category8": "5",
"Category9": "5"
},
{
"Year": "2013",
"Category1": "30",
"Category2": "10",
"Category3": "10",
"Category4": "10",
"Category5": "10",
"Category6": "10",
"Category7": "10",
"Category8": "10",
"Category9": "10"
},
{
"Year": "2014",
"Category1": "35",
"Category2": "15",
"Category3": "15",
"Category4": "15",
"Category5": "15",
"Category6": "15",
"Category7": "15",
"Category8": "15",
"Category9": "15"
},
{
"Year": "2015",
"Category1": "60",
"Category2": "20",
"Category3": "20",
"Category4": "20",
"Category5": "20",
"Category6": "20",
"Category7": "20",
"Category8": "20",
"Category9": "20"
},
{
"Year": "2016",
"Category1": "70",
"Category2": "40",
"Category3": "40",
"Category4": "40",
"Category5": "40",
"Category6": "40",
"Category7": "40",
"Category8": "40",
"Category9": "40"
}
];
colorStackChart.domain(d3.keys(data[0]).filter(function (key) { return key !== "Year"; }));
data.forEach(function (d) {
var y0 = 0;
d.ages = colorStackChart.domain().map(function (name) { return { name: name, y0: y0, y1: y0 += +d[name] }; });
d.total = d.ages[d.ages.length - 1].y1;
});
data.sort(function (a, b) { return b.total - a.total; });
xStackChart.domain(data.map(function (d) { return d.Year; }));
yStackChart.domain([0, d3.max(data, function (d) { return d.total; })]);
canvasStackChart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + heightStackChart + ")")
.call(d3.axisBottom(xStackChart));
canvasStackChart.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yStackChart))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("No Of Buildings");
var state = canvasStackChart.selectAll(".Year")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function (d) { return "translate(" + xStackChart(d.Year) + ",0)"; });
state.selectAll("rect")
.data(function (d) { return d.ages; })
.enter().append("rect")
.attr("width", xStackChart.bandwidth())
.attr("y", function (d) { return yStackChart(d.y1); })
.attr("height", function (d) { return yStackChart(d.y0) - yStackChart(d.y1); })
.style("fill", function (d) { return colorStackChart(d.name); });
var legend = canvasStackChart.selectAll(".legend")
.data(colorStackChart.domain().slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", widthStackChart - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", colorStackChart);
legend.append("text")
.attr("x", widthStackChart - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function (d) { return d; });
}
</script>
If you have an array, data, you can use that just like the parameter data in the csv function in the example you linked. The code within that function will work as expected, provided that your data is in the same format.
If you can set breakpoints with your browser, you can have a look at what that format is fairly easily, set one just inside the csv function call in the js and look at the data variable.

How to render D3 js graph using json in mvc3 razor

I am new in D3 js.most of the examples in gallery load data from TSV files.
but I wanted to render line graph using json in mvc3 razor. below is code where i hard code my data.please let me know how to retrive dynamic data using json.
var data = [
{ "date": 0, "close": 0.3372 },
{ "date": 1, "close": 1.7 },
{ "date": 2, "close": 1.8 },
{ "date": 3, "close": 2.014 },
{ "date": 4, "close": 10.995 },
{ "date": 5, "close": 16.227 },
{ "date": 6, "close": 16.643 },
{ "date": 7, "close": 20.644 },
{ "date": 8, "close": 22.478 }
];
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
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 line = d3.svg.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.close); });
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 + ")");
console.log("here");
data.forEach(function (d) {
d.date = parseInt(d.date);
d.close = +d.close;
});
console.log("here2");
x.domain(d3.extent(data, function (d) { return d.date; }));
y.domain(d3.extent(data, function (d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.text("Request")
.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("Probability");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);

Resources