d3.csv linked GitHub - javascript

I'm trying to link my .csv stored in github to the my d3 code.
Does anybody know if there is anything that I'm missing? I was able to do it with LeafLet not with D3. Any help would be highly appreciated. Thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3!!</title>
</head>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.js">
</script>
<script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>
<script>
var outerWidth=500;
var outerheight=250;
var margin={left:-50, top:0, right:-50, bottom:0};
var xColumn="longitude";
var yColumn="latitude";
var rColumn="population";
var peoplePerPixel=1000000;
var innerWidth=outerWidth - margin.left - margin.right;
var innerHeight=outerheight - margin.top - margin.bottom;
var svg=d3.select("body").append("svg")
.attr("width", outerWidth)
.attr("height", outerheight);
var g= svg.append("g")
.attr("transform", "translate (" + margin.left + "," +margin.top +")");
var xScale= d3.scaleLog()
.range([0,innerWidth]);
var yScale= d3.scaleLog()
.range([innerHeight,0]);
var rScale= d3.scaleSqrt();
function render (data){
xScale.domain(d3.extent(data, function (d){return d[xColumn]; }));
yScale.domain(d3.extent(data, function (d){return d[yColumn]; }));
rScale.domain([0, d3.max(data, function (d){return d[xColumn]; })]);
var circles= svg.selectAll("circle").data(data);
circles.enter().append("circle");
circles
.attr("cx", function(d){ return xScale(d[xColumn]);})
.attr("cy", function(d){ return yScale(d[yColumn]);})
.attr("r", function(d){ return rScale(d[rColumn]);});
circles.exit().remove();
}
function type(d) {
d.latitude=+d.latitude;
d.longitude=+d.longitude;
d.population=+d.population;
return d;
}
var data =
d3.csv(
"https://raw.githubusercontent.com/Pre60/myTest/master/map_cities.csv",
type, render)
</script>
</body>
</html>

You have some problems here:
You're setting the attributes to an "update" selection. This will not work (unless you call the function twice). It has to be:
circles.enter()
.append("circle")
.attr("cx", function(d) {
//etc...
because of that, there were no circles in your SVG. However, changing that point #1 shows you two additional problems:
You're using a scaleLog with a domain that crosses zero. There is no log of zero (actually, it is minus infinity). As the API clearly says:
As log(0) = -∞, a log scale domain must be strictly-positive or strictly-negative; the domain must not include or cross zero.
So, use a linear scale instead.
You are using the wrong property for the radii. It should be rColumn.
You forgot to set the range of the rScale.
All together, this is your (almost) working code:
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.js">
</script>
<script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>
<script>
var outerWidth = 500;
var outerheight = 250;
var margin = {
left: -50,
top: 0,
right: -50,
bottom: 0
};
var xColumn = "longitude";
var yColumn = "latitude";
var rColumn = "population";
var peoplePerPixel = 1000000;
var innerWidth = outerWidth - margin.left - margin.right;
var innerHeight = outerheight - margin.top - margin.bottom;
var svg = d3.select("body").append("svg")
.attr("width", outerWidth)
.attr("height", outerheight);
var g = svg.append("g")
.attr("transform", "translate (" + margin.left + "," + margin.top + ")");
var xScale = d3.scaleLinear()
.range([0, innerWidth]);
var yScale = d3.scaleLinear()
.range([innerHeight, 0]);
var rScale = d3.scaleSqrt().range([1, 5]);
function render(data) {
xScale.domain(d3.extent(data, function(d) {
return d[xColumn];
}));
yScale.domain(d3.extent(data, function(d) {
return d[yColumn];
}));
rScale.domain([0, d3.max(data, function(d) {
return d[rColumn];
})]);
var circles = svg.selectAll("circle").data(data);
circles.enter().append("circle").attr("cx", function(d) {
return xScale(d[xColumn]);
})
.attr("cy", function(d) {
return yScale(d[yColumn]);
})
.attr("r", function(d) {
return rScale(d[rColumn]);
});
circles.exit().remove();
}
function type(d) {
d.latitude = +d.latitude;
d.longitude = +d.longitude;
d.population = +d.population;
return d;
}
var data = d3.csv(
"https://raw.githubusercontent.com/Pre60/myTest/master/map_cities.csv",
type, render)
</script>
PS: There is no difference in writing var data = d3.csv(url, callback), since d3.csv doesn't return anything (actually, it returns an object related to the request). So, just drop that var data.

Related

How to use rangeRound in scaleTime in d3 v4?

I am trying to create a divergent bar chart which uses time scale(date) as x-axis. I am having trouble using ScaleBands with date, the date labels are overlapping.
This is what I got so far. https://jsfiddle.net/14ch7yeo/ when I use scaleTime, Unfortunately, the graph does not load.
I need to use zoom and brush on this graph.
<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = [{"Date":"2015-01-02T00:00:00.000Z","Buy":554646.5,"Sell":-406301.3547},{"Date":"2015-02-02T00:00:00.000Z","Buy":565499.5,"Sell":-673692.5697},{"Date":"2015-03-02T00:00:00.000Z","Buy":421954.5,"Sell":-571685.4629},{"Date":"2015-04-02T00:00:00.000Z","Buy":466242.0,"Sell":-457477.7121},{"Date":"2015-05-02T00:00:00.000Z","Buy":350199.7,"Sell":-579682.8772},{"Date":"2015-06-02T00:00:00.000Z","Buy":391035.1,"Sell":-338816.6205},{"Date":"2015-07-02T00:00:00.000Z","Buy":437644.6,"Sell":-502329.557},{"Date":"2015-08-02T00:00:00.000Z","Buy":291978.9,"Sell":-504067.0329},{"Date":"2015-09-02T00:00:00.000Z","Buy":360913.8,"Sell":-489519.6652},{"Date":"2015-10-02T00:00:00.000Z","Buy":505799.1,"Sell":-723353.7089},{"Date":"2015-11-02T00:00:00.000Z","Buy":510691.0,"Sell":-374061.8139},{"Date":"2015-12-02T00:00:00.000Z","Buy":527757.1,"Sell":-597800.0116},{"Date":"2016-01-02T00:00:00.000Z","Buy":564799.1,"Sell":-451779.1593},{"Date":"2016-02-02T00:00:00.000Z","Buy":336533.7,"Sell":-522601.1707},{"Date":"2016-03-02T00:00:00.000Z","Buy":460684.6,"Sell":-643556.0079999999},{"Date":"2016-04-02T00:00:00.000Z","Buy":428388.1,"Sell":-349216.2376},{"Date":"2016-05-02T00:00:00.000Z","Buy":525459.5,"Sell":-597258.4075},{"Date":"2016-06-02T00:00:00.000Z","Buy":677659.1,"Sell":-513192.107},{"Date":"2016-07-02T00:00:00.000Z","Buy":365612.8,"Sell":-287845.8089},{"Date":"2016-07-03T00:00:00.000Z","Buy":358775.2,"Sell":-414573.209}]
var parseTime = d3.utcParse("%Y-%m-%dT%H:%M:%S.%LZ");
data.forEach(d => {
d["Date"] = parseTime(d["Date"]);
})
var series = d3.stack()
.keys(["Buy", "Sell"])
.offset(d3.stackOffsetDiverging)
(data);
var svg = d3.select("svg"),
margin = {top: 20, right: 30, bottom: 30, left: 60},
width = +svg.attr("width"),
height = +svg.attr("height");
var x = d3.scaleBand()
.domain(data.map(function(d) { return d['Date']; }))
.rangeRound([margin.left, width - margin.right])
.padding(0.1);
var y = d3.scaleLinear()
.domain([d3.min(series, stackMin), d3.max(series, stackMax)])
.rangeRound([height - margin.bottom, margin.top]);
var z = d3.scaleOrdinal()
.range(["green","red"]);
svg.append("g")
.selectAll("g")
.data(series)
.enter().append("g")
.attr("fill", function(d) { return z(d.key); })
.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("width", x.bandwidth)
.attr("x", function(d) { return x(d.data["Date"]); })
.attr("y", function(d) { return y(d[1]); })
.attr("height", function(d) { return y(d[0]) - y(d[1]); })
svg.append("g")
.attr("transform", "translate(0,"+ (height-margin.top) + ")")
.call(d3.axisBottom(x));
svg.append("g")
.attr("transform", "translate(" + margin.left + ",0)")
.call(d3.axisLeft(y));
function stackMin(serie) {
return d3.min(serie, function(d) { return d[0]; });
}
function stackMax(serie) {
return d3.max(serie, function(d) { return d[1]; });
}
</script>
d3.scaleTime has to be treated differently on a number of fronts.
The scale doesn't take padding as an argument:
var x = d3.scaleTime()
.domain(d3.extent(data, function(d) { return d.Date; }))
.rangeRound([margin.left, width - margin.right]);
Time is continuous rather than discrete, so the widths of the bars need to be calculated manually, as a ratio of rect and series.length. I got this to work, but maybe you want something more elegant:
.attr("width", width/series.length - 450)

How to get the index of the data element in a histogram on mouseover?

I have a d3.v3.min.js histogram created using this as reference Histogram chart using d3 and I'd like to highlight in a separate plot (scatter plot) all the points that fall within one bar of this histogram. To this end I hook on the mouseover event of the rectangle to get the values within one bin. This works fine but I can't get their indices from the original input array:
var data = d3.layout.histogram().bins(xTicks)(values);
bar.append("rect")
.attr("x", 1)
.attr("width", (x(data[0].dx) - x(0)) - 1)
.attr("height", function(d) { return height - y(d.y); })
.attr("fill", function(d) { return colorScale(d.y) })
.on("mouseover", function (d, i) { console.log(d); });
d is an array containing all the values within the bin, and i is the bin index. I need the indices of the original data values I passed to the histogram function so that I can look them up in the other plot by index (as opposed to a binary search needed on the value).
Instead of just passing number values to the histogram generator you could create an array of objects carrying additional information:
// Generate a 1000 data points using normal distribution with mean=20, deviation=5
var f = d3.random.normal(20, 5);
// Create full-fledged objects instead of mere numbers.
var values = d3.range(1000).map(id => ({
id: id,
value: f()
}));
// Accessor function for the objects' value property.
var valFn = d => d.value;
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
.value(valFn) // Provide accessor function for histogram generation
(values);
By providing an accessor function to the histogram generator you are then able to create the bins from this array of objects. Calling the histogram generator will consequently result in bins filled with objects instead of just raw numbers. In an event handler you are then able to access your data objects by reference. The objects will carry all the initial information, be it the id property as in my example, an index or anything else you put in them in the first place.
Have a look at the following snippet for a working demo:
var color = "steelblue";
var f = d3.random.normal(20, 5);
// Generate a 1000 data points using normal distribution with mean=20, deviation=5
var values = d3.range(1000).map(id => ({
id: id,
value: f()
}));
var valFn = d => d.value;
// A formatter for counts.
var formatCount = d3.format(",.0f");
var margin = {top: 20, right: 30, bottom: 30, left: 30},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var max = d3.max(values, valFn);
var min = d3.min(values, valFn);
var x = d3.scale.linear()
.domain([min, max])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
.value(valFn)
(values);
var yMax = d3.max(data, function(d){return d.length});
var yMin = d3.min(data, function(d){return d.length});
var colorScale = d3.scale.linear()
.domain([yMin, yMax])
.range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);
var y = d3.scale.linear()
.domain([0, yMax])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
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 bar = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; })
.on("mouseover", d => { console.log(d)});
bar.append("rect")
.attr("x", 1)
.attr("width", (x(data[0].dx) - x(0)) - 1)
.attr("height", function(d) { return height - y(d.y); })
.attr("fill", function(d) { return colorScale(d.y) });
bar.append("text")
.attr("dy", ".75em")
.attr("y", -12)
.attr("x", (x(data[0].dx) - x(0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.y); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
/*
* Adding refresh method to reload new data
*/
function refresh(values){
// var values = d3.range(1000).map(d3.random.normal(20, 5));
var data = d3.layout.histogram()
.value(valFn)
.bins(x.ticks(20))
(values);
// Reset y domain using new data
var yMax = d3.max(data, function(d){return d.length});
var yMin = d3.min(data, function(d){return d.length});
y.domain([0, yMax]);
var colorScale = d3.scale.linear()
.domain([yMin, yMax])
.range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);
var bar = svg.selectAll(".bar").data(data);
// Remove object with data
bar.exit().remove();
bar.transition()
.duration(1000)
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
bar.select("rect")
.transition()
.duration(1000)
.attr("height", function(d) { return height - y(d.y); })
.attr("fill", function(d) { return colorScale(d.y) });
bar.select("text")
.transition()
.duration(1000)
.text(function(d) { return formatCount(d.y); });
}
// Calling refresh repeatedly.
setInterval(function() {
var values = d3.range(1000).map(id => ({
id: id,
value: f()
}));
refresh(values);
}, 2000);
body {
font: 10px sans-serif;
}
.bar rect {
shape-rendering: crispEdges;
}
.bar text {
fill: #999999;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.as-console-wrapper {
height: 20%;
}
<script src="https://d3js.org/d3.v3.min.js"></script>

Display multiple d3.js charts in a single html page

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>

Use External Json Data from a File to show a d3.js Pie chart

I have to design a Pie chart, which dynamically updates when changes are made in an external JSON file. I have written a fairly simple code, but somehow I am not getting the chart rendered on the chrome page. There seems to be some Uncaught errors and definition of "data" missing. I am fairly new to d3 and Javascript, and I need your assistance in debugging/fixing this code for me.
My Json file is called by the d3.json method call.
x in the json file is Name and y is Value. x,y becomes my name:Value pair.
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="../lib/d3.v3.min.js"></script>
<script type="text/javascript">
var width = 960;
var height = 500;
var radius = 400;
var outerRadius = radius;
var innerRadius = 0;
var pie = d3.layout.pie().sort(null).y(function(d) {
return d.y;
});
var color = d3.scale.category10();
var svg = d3.select("body").append("svg").attr("width", width).attr(
"height", height).append("g").attr("transform",
"translate(" + width / 2 + "," + height / 2 + ")");
var g = svg.selectAll(".arc").data(pie(data)).enter().append("g").attr(
"class", "arc");
var arc = d3.svg.arc().outerRadius(outerRadius)
.innerRadius(innerRadius);
var labelArc = d3.svg.arc().outerRadius(radius - 40).innerRadius(
radius - 40);
d3.json("data.json", function(error, data ) {
data.forEach(function(d) {
d.x = d.x;
d.y = d.y+d.y;
x.domain(data.map(function(d) {
return d.x;
}));
y.domain([ 0, d3.max(data, function(d) {
return d.y;
}) ]);
g.append("path")
.attr("fill", function(d, i) {
return color(i);
}).attr("d", arc);
g.append("text").attr("transform", function(d) {
return "translate(" + labelArc.centroid(d) + ")";
}).attr("text-anchor", "middle").text(function(d) {
return d.data.x;
});
})
});
</script>
There is some logical issues with code structure... like the data variable is used outside d3.json where it isnt accessible. See the approach below... it should work, I havent tested it. Let me know if u face any issues running this code
var width = 960;
var height = 500;
var radius = 400;
var outerRadius = radius;
var innerRadius = 0;
var pie = d3.layout.pie().sort(null).y(function(d) {
return d.y;
});
var g, arc, labelArc;
var color = d3.scale.category10();
var svg = d3.select("body").append("svg").attr("width", width).attr(
"height", height).append("g").attr("transform",
"translate(" + width / 2 + "," + height / 2 + ")");
d3.json("data.json", function(error, data ) {
x.domain(data.map(function(d) { return d.x; }));
y.domain([ 0, d3.max(data, function(d) { return d.y; }) ]);
g = svg.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc");
arc = d3.svg.arc()
.outerRadius(outerRadius)
.innerRadius(innerRadius);
labelArc = d3.svg.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
g.append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
g.append("text")
.attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")";})
.attr("text-anchor", "middle").text(function(d) { return d.data.x; });
});

D3 Stacked bar graph works in Tributary but nowhere else

This has the expected results I want but when I import the code into my HTML file as a script it doesn't show anything at all.
var PUBLIC = [50,40,10];
var NONPROFIT = [30,40,30];
var FOR_PROFIT = [70,15,15];
var data = [
{"key":"PUBLIC", "pop1":PUBLIC[0], "pop2":PUBLIC[1], "pop3":PUBLIC[2]},
{"key":"NONPROFIT", "pop1":NONPROFIT[0], "pop2":NONPROFIT[1], "pop3":NONPROFIT[2]},
{"key":"FORPROFIT", "pop1":FOR_PROFIT[0], "pop2":FOR_PROFIT[1], "pop3":FOR_PROFIT[2]}
];
var n = 3, // Number of layers
m = data.length, // Number of samples per layer
stack = d3.layout.stack(),
labels = data.map(function(d) { return d.key; }),
// Go through each layer (pop1, pop2 etc, that's the range(n) part)
// then go through each object in data and pull out that objects's population data
// and put it into an array where x is the index and y is the number
layers = stack(d3.range(n).map(function(d)
{
var a = [];
for (var i = 0; i < m; ++i)
{
a[i] = { x: i, y: data[i]['pop' + (d+1)] };
}
return a;
})),
// The largest single layer
yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
// The largest stack
yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });
var margin = {top: 40, right: 10, bottom: 20, left: 50},
width = 677 - margin.left - margin.right,
height = 533 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.domain(d3.range(m))
.rangeRoundBands([2, height], .08);
var x = d3.scale.linear()
.domain([0, yStackMax])
.range([0, width]);
var color = d3.scale.linear()
.domain([0, n - 1])
.range(["#aad", "#556"]);
var svg = d3.select("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 layer = svg.selectAll(".layer")
.data(layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) { return color(i); });
layer.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("y", function(d) { return y(d.x); })
.attr("x", function(d) { return x(d.y0); })
.attr("height", y.rangeBand())
.attr("width", function(d) { return x(d.y); });
var yAxis = d3.svg.axis()
.scale(y)
.tickSize(1)
.tickPadding(6)
.tickValues(labels)
.orient("left");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
I believe I have all the required libraries imported and then some:
<!-- D3 Library -->
<script src='https://d3js.org/d3.v3.min.js' charset='utf-8'></script>
<!-- jQuery Mobile -->
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- jQuery Main -->
<script src='https://code.jquery.com/jquery-2.2.3.min.js' charset='utf-8'></script>
While the code to get my variables are a bit simplified (i.e. plainly setting my arrays) they are the same format as what is put within the data array.
Furthermore, this example does not work within CodePen either when I import everything that Tributary uses for its base libraries. While, again, this isn't 100% of the code I have going into the creation a much simpler working example on Tributary does not work on CodePen.
D3 has done nothing but kick my butt these past few weeks and I'm in need of some guidance. Thanks.
You need to wait for the page to be fully loaded or your can put the code before the closing </body> tag.
Solution1:
$(function() {
//Put your code here;
});
Solution2:
<body>
<svg></svg>
<script>
//your code here
</script>
</body>
Demo: https://jsfiddle.net/iRbouh/ag6p4kkg/

Categories