How to put the state name into the Geo chart/D3.js - javascript

I met a problem that I want to put the state name on my geo chart. I tried to use others' method, but they cannot well-matched with my chart. Could you please let me know what's wrong with my code and how to improve it.Thank you in advance!
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="stylemap.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id = "chart"></div>
<script src="https://d3js.org/d3.v5.js"></script>
<script src="mainmap.js"></script>
</body>
</html>
Mainmap.js:
//weight and height
var chart_height = 600;
var chart_width = 800;
var color = d3.scaleQuantize().range([ 'rgb(255,245,240)','rgb(254,224,210)','rgb(252,187,161)',
'rgb(252,146,114)','rgb(251,106,74)','rgb(239,59,44)',
'rgb(203,24,29)','rgb(165,15,21)','rgb(103,0,13)']);
//Projection
var projection = d3.geoAlbersUsa()
.scale([chart_width])
.translate([chart_width / 2, chart_height / 2 ]);
// .translate([0, 100]);
var path = d3.geoPath(projection);
// .projection(projection);
//create svg
var svg = d3.select('#chart')
.append("svg")
.attr('width', chart_width)
.attr('height', chart_height);
// svg.append("rect")
// .attr("class", "background")
// .attr("width", width)
// .attr("height", height);
var g = svg.append("g")
.attr("transform", "translate(" + chart_width / 2 + "," + chart_height / 2 + ")")
.append("g")
.attr("id", "states");
//Data
d3.json('zombie-attacks.json').then(function(zombie_data){
color.domain([
d3.min(zombie_data, function(d){
return d.num;
}),
d3.max(zombie_data, function(d){
return d.num;
})
]);
d3.json('us.json').then(function(us_data){
us_data.features.forEach(function(us_e, us_i){
zombie_data.forEach(function(z_e,z_i){
if(us_e.properties.name !== z_e.state){
return null;
}
us_data.features[us_i].properties.num = parseFloat(z_e.num)
});
});
// console.log(us_data)
svg.selectAll('path')
.data(us_data.features)
.enter()
.append('path')
.attr('d',path)
.attr('fill', function(d){
var num = d.properties.num;
return num ? color(num) : '#ddd';
})
.text(function(d){
return d.properties.name;
})
.attr('stroke', '#fff')
.attr('stroke-width',1)
.attr("class", "country-label")
.append("text")
// .attr("transform", function(d) { console.log("d", d); return "translate(" + path.centroid(d) + ")"; })
// .text(function(d) { return d.properties.name; })
.attr("dy", function (d) {
return "0.35em";
})
.style('fill', 'black');
g.selectAll("text")
.data(us_data.features)
.enter()
.append("text")
.text(function(d){
return d.properties.name;
})
.attr("x", function(d){
return path.centroid(d)[0];
})
.attr("y", function(d){
return path.centroid(d)[1];
})
.attr("text-anchor","middle")
.attr('font-size','6pt')
.style('fill', 'green');
})
})
// Add names of the states to a map in d3.js

You're appending text and path to different parents: svg and g. This is an issue because:
var g = svg.append("g")
.attr("transform", "translate(" + chart_width / 2 + "," + chart_height / 2 + ")")
Your g, with the text has a transform that the svg doesn't. Which is why your text is pushed width/2, height/2 further than the projected paths. Just use svg.selectAll for the text.
The projection already has a translate applied to it, you can either apply the translation to the parent or to the projection, but shouldn't use both.

Related

How to do line graph from CSV into HTML

My code now looks like this:
<!DOCTYPE html>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var parseTime = d3.timeParse("%d-%b-%y");
var x = d3.scaleTime()
.rangeRound([0, width]);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var line = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
d3.tsv("data.tsv", function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
return d;
}, function(error, data) {
if (error) throw error;
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.select(".domain")
.remove();
g.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Price ($)");
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line);
});
</script>
Now I would like to redo it to upload CSV file right there on this page and to read data from there.
The file is going to be a table with two columns: first one is going to be a column with dates, but the second one - with numbers, with which the graph will be built.
Now I also tried doing it like this:
<!DOCTYPE html>
<html lang="lv"><head>
<title>HTML formas</title>
<meta charset="UTF-8">
</head>
<body>
<p>Norādi datni</p>
<input type="file" id="datne" onchange="datnesApstrade()">
<p>Ielasītie dati</p>
<pre id="rezultats"></pre>
<script>
function datnesApstrade(){
var fr=new FileReader();
fr.onload=function(){
apstradat( fr.result );
}
f = document.getElementById("datne");
fr.readAsText(f.files[0]);
}
function apstradat( dati ) {
document.getElementById('rezultats')
.textContent=dati;
var rindas = dati.split("\n");
//document.getElementById('rezultats').textContent="Rindas:"+rindas.length;
//alert( "In file is " + rindas.length + " lines" );
var r, i, c, co2 = [];
// pirmā rindā ir tabulas galva, tāpēc to nelasām
for( r=1; r<rindas.length; r=r+1 ) {
c = rindas[r].split(",");
co2.push( Number(c[1]) );
}
var rl = rindas.length-2;
for (i=1; i<rl; i=i+1){
document.getElementById('rezultats').textContent=co2[i];
}
}
</script>
</body></html>
But I don't know how to modify it to achieve my goal. Please help!

Graph is no longer appearing when I use d3.json to access json data

I'm very new to D3.js - please can you help? I have successfully created a bar chart and used json data within the code, but when I removed it to create a separate json file and inserted d3.json("sales.json").then(function(data){ graph as before};) it no longer works. It's such a simple line of code to insert and matches the code I've found online so I can't see why it isn't working. Can anyone help please? Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="L4F - Axes and scales ">
<title>SVG</title>
<script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>
</head>
<body>
<h1> Sales data </h1>
<script>
d3.json("sales.json").then(function(data){
var w = 500;
var h = 500;
var padding = 2;
var lmargin = 50;
var bmargin = 50;
var tmargin = 50;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
.style("background", "white");
var plotArea = svg.append('g');
function colourPicker(v){
if (v<=20) {return "#666666";}
else if (v>20) {return "#ff0033";}
}
plotArea.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x",function(d, i){return i * ((w - lmargin)/dataset.length) + lmargin;})
.attr("y",function (d){ return h - (d.s*4) - bmargin;})
.attr("width", (w-lmargin)/dataset.length - padding)
.attr("height", function(d){return d.s*4;})
.attr("fill", function(d){ return colourPicker(d.s);})
plotArea.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function(d) {return (d.m+" £"+d.s);})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {return i*((w - lmargin)/dataset.length)+((w - lmargin)/dataset.length - padding)/2;})
.attr("y", function(d) { return h-(d.s*4)+14 - bmargin;})
.attr("font-family", "sans-serif")
.attr("font-size", 12)
.attr("fill", "white")
var maxY = d3.max(dataset.map(function(d){return (d.s);}))
var yScale = d3.scaleLinear()
.domain([0, maxY*4])
.range([h-maxY*4, 0]);
var yAxis = d3.axisLeft()
.scale(yScale);
var yAxisGroup = svg.append('g')
.attr('transform', 'translate('+lmargin+','+(bmargin)+')')
.call(yAxis);
yAxisGroup.append("text")
.text("Sales")
.attr("y", h/2 - bmargin)
.attr("x", lmargin/2)
.attr("transform", "translate(-230,230) rotate(270)")
.style("fill", "black")
.attr("font-size", "14")
.attr("text-anchor", "middle");
};)
</script>
</body>
</html>
And my json file looks like this..
[
{
"s":25,
"m":"Jan"
},
{
"s":10,
"m":"Feb"
},
{
"s":15,
"m":"Mar"
}
]

Not able to use symbols in d3 chart

I am using d3 chart in my project version used is version 4,
My Code sandbox - https://codesandbox.io/s/lucid-morning-bi9vc
I am trying to use the triangle symbol in place of my circle in my line chart
code -
g.selectAll(".point")
.data(data)
.enter()
.append("path")
.attr("d", d3.symbolTriangle)
.attr("transform", function(d) {
return (
"translate(" + xScale(d.startTime) + "," + yScale(d.magnitude) + ")"
);
})
.style("fill", "red")
.attr("class", "point");
Previously for circle - this was working fine for circle.
g.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d) {
return xScale(d.startTime);
})
.attr("cy", function(d) {
return yScale(d.magnitude);
})
.attr("r", function(d) {
return 6;
})
I have followed this -
https://bl.ocks.org/mbostock/3244058
to use like .attr("d", d3.svg.symbol().type("triangle-up")) but this also don’t work.
I tried to refer https://bl.ocks.org/feyderm/4d143591b66725aed0f1855444752fd9 and symbol link https://github.com/d3/d3-shape#symbols but I am not able to use it successfully, Any guidance. Thanks.
<!DOCTYPE html>
<!--TRY Triangle-->
<div id="chart"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript">
var svg_dx = 800,
svg_dy = 400,
margin_x = 100;
//Triangle shape//
var shapes = [
d3.symbolTriangle ];
var x = d3.scalePoint()
.domain(d3.range(0, shapes.length))
.range([margin_x, svg_dx - margin_x]);
var svg = d3.select("#chart")
.append("svg")
.attr("width", svg_dx)
.attr("height", svg_dy);
var symbol = d3.symbol().size([1500]),
color = d3.schemeCategory10;
var drag_behavior = d3.drag()
.on("start", dragstarted)
.on("drag", dragged);
svg.append("g")
.selectAll("path")
.data(shapes)
.enter()
.append("path")
.attr("d", symbol.type(shape => shape))
.attr("transform", (shape, i) => "translate(" + x(i) + ", -40)")
.style("fill", (shape, i) => color[i])
.call(drag_behavior)
.transition()
.duration((shape, i) => i * 800)
.attr("transform", (shape, i) => "translate(" + x(i) + "," + (svg_dy / 2) + ")");
function dragstarted() {
d3.select(this).raise();
}
function dragged(shape) {
var dx = d3.event.sourceEvent.offsetX,
dy = d3.event.sourceEvent.offsetY;
d3.select(this)
.attr("transform", shape => "translate(" + dx + "," + dy + ")");
}
</script>
D3 v4 shapes

Trying to get circles on map to transition into bars in bar chart with D3

I create a bubble map with D3, and I want the user to be able to click on a button and the circles on the map will transition into bars of a bar chart. I am using the enter, update, exit pattern, but right now what I have isn't working as the bar chart is drawn on top and all the bars and circles are translated, instead of the circles transitioning into bars and the bars being translated into place. Below is the relevant part of my code, and here is the link to the demo: https://jhjanicki.github.io/circles-to-bars/
var projection = d3.geo.mercator()
.scale(150)
.center([20, 40])
.translate([width / 2, height / 2]);
var path= d3.geo.path()
.projection(projection);
var features = countries2.features;
d3.csv("data/sum_by_country.csv", function(error, data) {
data.sort(function(a,b){
return a.value - b.value;
});
var myfeatures= joinData(features, data, ['value']);
var worldMap = svg.append('g');
var world = worldMap.selectAll(".worldcountries")
.data(myfeatures)
.enter()
.append("path")
.attr("class", function(d){
return "World " + d.properties.name+" worldcountries";
})
.attr("d", path)
.style("fill", "#ddd")
.style("stroke", "white")
.style("stroke-width", "1");
var radius = d3.scale.sqrt()
.domain([0,1097805])
.range([3, 20]);
var newFeatures = [];
myfeatures.forEach(function(d){
if(d.properties.hasOwnProperty("value")){
console.log(d.properties.name);
newFeatures.push(d);
}
});
newFeatures.sort(function(a,b){
return b.properties.value - a.properties.value;
});
var bubbles = svg.append("g").classed("bubbleG","true");
bubbles.selectAll("circle")
.data(newFeatures)
.enter().append("circle")
.attr("class", "bubble")
.attr("transform", function(d) {
return "translate(" + path.centroid(d) + ")";
})
.attr("r", function(d){
return radius(d.properties.value);
})
.attr("fill","#2166ac")
.attr("stroke","white")
.attr("id", function(d){
return "circle "+d.properties.name;
});
$('#bubblebar').click(function(){
mapBarTransition(newFeatures,bubbles)
});
});
// button onclick
function mapBarTransition(data,bubbles){
var margin = {top:20, right:20, bottom:120, left:80},
chartW = width - margin.left - margin.right,
chartH = height - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(data.map(function(d) { return d.properties.name; }))
.rangeRoundBands([0, chartW], .4);
var y = d3.scale.linear()
.domain([0,1097805])
.nice()
.range([chartH,0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.ticks(8)
.orient("left");
var barW = width / data.length;
bubbles.append("g").classed("bubblebar-chart-group", true);
bubbles.append("g").classed("bubblebar-x-axis-group axis", true);
bubbles.append("g").classed("bubblebar-y-axis-group axis", true);
bubbles.transition().duration(1000).attr({transform: "translate(" + margin.left + "," + margin.top + ")"});
bubbles.select(".bubblebar-x-axis-group.axis")
.attr({transform: "translate(0," + (chartH) + ")"})
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", function(d) {
return "rotate(-65)"
});
bubbles.select(".bubblebar-y-axis-group.axis")
.transition()
.call(yAxis);
barW = x.rangeBand();
var bars = bubbles.select(".bubblebar-chart-group")
.selectAll(".bubble")
.data(data);
bars.enter().append("rect")
.classed("bubble", true)
.attr("x", function(d) { return x(d.properties.name); })
.attr("y", function(d) { return y(d.properties.value); })
.attr("width", barW)
.attr("height", function(d) { return chartH - y(d.properties.value); })
.attr("fill","#2166ac");
bars.transition()
.attr("x", function(d) { return x(d.properties.name); })
.attr("y", function(d) { return y(d.properties.value); })
.attr("width", barW)
.attr("height", function(d) { return chartH - y(d.properties.value); });
bars.exit().transition().style({opacity: 0}).remove();
}
And here is the repo for your reference: https://github.com/jhjanicki/circles-to-bars
First, you have two very different selections with your circles and bars. They are in separate g containers and when you draw the bar chart, you aren't even selecting the circles.
Second, I'm not sure that d3 has any built-in way to know how to transition from a circle element to a rect element. There's some discussion here and here
That said, here's a quick hack with your code to demonstrate one way you could do this:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel='stylesheet'>
<link href="//rawgit.com/jhjanicki/circles-to-bars/master/css/style.css" rel='stylesheet'>
<!-- Roboto & Asar CSS -->
<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<link href="https://fonts.googleapis.com/css?family=Asar" rel="stylesheet">
</head>
<body>
<button type="button" class="btn btn-primary" id="bubblebar">Bar Chart</button>
<div id="chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<!-- D3.geo -->
<script src="https://d3js.org/d3.geo.projection.v0.min.js"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//rawgit.com/jhjanicki/circles-to-bars/master/data/countries2.js"></script>
<script>
window.onload = function() {
// set up svg and scrolling
var width = window.innerWidth / 2;
var height = window.innerHeight;
var svg = d3.select("#chart").append("svg")
.attr('width', width)
.attr('height', height);
var bubbleMapState = 'map'; // map or bar
var projection = d3.geo.mercator()
.scale(150)
.center([20, 40])
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var features = countries2.features;
d3.csv("//rawgit.com/jhjanicki/circles-to-bars/master/data/sum_by_country.csv", function(error, data) {
data.sort(function(a, b) {
return a.value - b.value;
});
var myfeatures = joinData(features, data, ['value']);
var worldMap = svg.append('g');
var world = worldMap.selectAll(".worldcountries")
.data(myfeatures)
.enter()
.append("path")
.attr("class", function(d) {
return "World " + d.properties.name + " worldcountries";
})
.attr("d", path)
.style("fill", "#ddd")
.style("stroke", "white")
.style("stroke-width", "1");
var radius = d3.scale.sqrt()
.domain([0, 1097805])
.range([3, 20]);
var newFeatures = [];
myfeatures.forEach(function(d) {
if (d.properties.hasOwnProperty("value")) {
console.log(d.properties.name);
newFeatures.push(d);
}
});
newFeatures.sort(function(a, b) {
return b.properties.value - a.properties.value;
});
var bubbles = svg.append("g").classed("bubbleG", "true");
bubbles.selectAll("rect")
.data(newFeatures)
.enter().append("rect")
.attr("class", "bubble")
.attr("transform", function(d) {
return "translate(" + path.centroid(d) + ")";
})
.attr("width", function(d) {
return radius(d.properties.value) * 2;
})
.attr("height", function(d){
return radius(d.properties.value) * 2;
})
.attr("rx", 20)
.attr("fill", "#2166ac")
.attr("stroke", "white")
.attr("id", function(d) {
return "circle " + d.properties.name;
});
$('#bubblebar').click(function() {
mapBarTransition(newFeatures, bubbles)
});
});
// button onclick
function mapBarTransition(data, bubbles) {
if (bubbleMapState == 'map') {
bubbleMapState == 'bar';
} else {
bubbleMapState == 'map';
}
var margin = {
top: 20,
right: 20,
bottom: 120,
left: 80
},
chartW = width - margin.left - margin.right,
chartH = height - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(data.map(function(d) {
return d.properties.name;
}))
.rangeRoundBands([0, chartW], .4);
var y = d3.scale.linear()
.domain([0, 1097805])
.nice()
.range([chartH, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.ticks(8)
.orient("left");
var barW = width / data.length;
bubbles.append("g").classed("bubblebar-chart-group", true);
bubbles.append("g").classed("bubblebar-x-axis-group axis", true);
bubbles.append("g").classed("bubblebar-y-axis-group axis", true);
bubbles.transition().duration(1000).attr({
transform: "translate(" + margin.left + "," + margin.top + ")"
});
bubbles.select(".bubblebar-x-axis-group.axis")
.attr({
transform: "translate(0," + (chartH) + ")"
})
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", function(d) {
return "rotate(-65)"
});
bubbles.select(".bubblebar-y-axis-group.axis")
.transition()
.call(yAxis);
barW = x.rangeBand();
var bars = d3.select(".bubbleG")
.selectAll(".bubble")
.data(data);
bars.enter().append("rect")
.classed("bubble", true)
.attr("x", function(d) {
return x(d.properties.name);
})
.attr("y", function(d) {
return y(d.properties.value);
})
.attr("width", barW)
.attr("height", function(d) {
return chartH - y(d.properties.value);
})
.attr("fill", "#2166ac");
bars.transition()
.duration(1000)
.attr("transform", function(d){
return "translate(" + x(d.properties.name) + "," + y(d.properties.value) + ")";
})
.attr("rx", 0)
.attr("width", barW)
.attr("height", function(d) {
return chartH - y(d.properties.value);
});
bars.exit().transition().style({
opacity: 0
}).remove();
}
function joinData(thisFeatures, thisData, DataArray) {
//loop through csv to assign each set of csv attribute values to geojson counties
for (var i = 0; i < thisData.length; i++) {
var csvCountry = thisData[i]; //the current county
var csvKey = csvCountry.Country; //the CSV primary key
//loop through geojson regions to find correct counties
for (var a = 0; a < thisFeatures.length; a++) {
var geojsonProps = thisFeatures[a].properties; //the current region geojson properties
var geojsonKey = geojsonProps.name; //the geojson primary key
//where primary keys match, transfer csv data to geojson properties object
if (geojsonKey == csvKey) {
//assign all attributes and values
DataArray.forEach(function(attr) {
var val = parseFloat(csvCountry[attr]); //get csv attribute value
geojsonProps[attr] = val; //assign attribute and value to geojson properties
});
};
};
};
return thisFeatures;
};
}
</script>
</body>

Aster Plot legend labels along with the arc

I am using aster plot of d3 in my project.
I want legend labels along with the arc radius outside the circle.
I could get an example of piechart showing labels along and outside the arc.
http://bl.ocks.org/Guerino1/2295263
But i am unable to implement the same in aster plot of d3.
http://bl.ocks.org/bbest/2de0e25d4840c68f2db1
Any help would be appreciated.
Thanks
Couple things to fix.
1.) You have to introduce margins into the aster plot for the labels.
2.) You then have to take the outer arcs, add a an svg g do you can group a path with a text:
var outerGroup = svg.selectAll(".solidArc")
.data(pie(data))
.enter()
.append("g")
outerGroup
.append("path")
.attr("fill", function(d) { return d.data.color; })
.attr("class", "solidArc")
.attr("stroke", "gray")
.attr("d", arc)
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
outerGroup
.append("text")
.attr("transform", function(d) {
return "translate(" + centroid(60, width, d.startAngle, d.endAngle) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) { return d.data.label });
Note I had to create my own centroid function to move the labels outside the arc. The code in the pie chart example you linked did not work for me (it's using a old d3 version).
Here's my centroid function stolen from the d3 source:
function centroid(innerR, outerR, startAngle, endAngle){
var r = (innerR + outerR) / 2, a = (startAngle + endAngle) / 2 - (Math.PI / 2);
return [ Math.cos(a) * r, Math.sin(a) * r ];
}
Here's a working example.
Full code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Testing Pie Chart</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.4.5"></script>
<style type="text/css">
.slice text {
font-size: 16pt;
font-family: Arial;
}
</style>
</head>
<body>
<script type="text/javascript">
var canvasWidth = 500, //width
canvasHeight = 500, //height
outerRadius = 150, //radius
//outerRadius = Math.min(canvasWidth, canvasHeight) / 2,
color = d3.scale.category20(); //builtin range of colors
innerRadius =0
var colorsArray = ['#0099ff','#cc00ff','#ff3366','#cc3300','#ff6600','#ffff33','#cccc00','#0066ff'];
var dataSet = [
{"legendLabel":"Testing Text Is", "magnitude":30,'score':4.8,width:20,color:colorsArray[0] },
{"legendLabel":"Two", "magnitude":8,'score':3.2,width:20,color:colorsArray[1] },
{"legendLabel":"Three", "magnitude":40,'score':3.9,width:20,color:colorsArray[2] },
{"legendLabel":"Four", "magnitude":50,'score':3.1,width:20,color:colorsArray[3] },
{"legendLabel":"Five", "magnitude":16,'score':4.2,width:20,color:colorsArray[4] },
{"legendLabel":"Six", "magnitude":50,'score':3.1,width:20,color:colorsArray[5] },
{"legendLabel":"Seven", "magnitude":30,'score':4.3,width:20,color:colorsArray[6] },
{"legendLabel":"Eight", "magnitude":20,'score':2.3,width:20,color:colorsArray[7] }
];
var vis = d3.select("body")
.append("svg:svg")
.data([dataSet])
.attr("width", canvasWidth)
.attr("height", canvasHeight)
.append("svg:g")
.attr("transform", "translate(" + 1.5*outerRadius + "," + 1.5*outerRadius + ")") // relocate center of pie to 'outerRadius,outerRadius'
var arc = d3.svg.arc()
.outerRadius(outerRadius);
var arc1 = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(function (d) {
return (outerRadius - innerRadius) * (d.data.score / 5.0) + innerRadius;
});
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.width; });
// Select all <g> elements with class slice (there aren't any yet)
var arcs = vis.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
arcs.append("svg:path")
//set the color for each slice to be chosen from the color function defined above
.attr("fill", function(d, i) { return d.data.color; } )
//this creates the actual SVG path using the associated data (pie) with the arc drawing function
.attr("d", arc1);
var text = arcs.append("svg:text")
.attr("transform", function(d) {
d.outerRadius = outerRadius + 75;
d.innerRadius = outerRadius + 70;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle") //center the text on it's origin
.style("fill", "black")
.style("font", "bold 12px Arial")
.each(function (d) {
var arr = d.data.legendLabel.split(" ");
if (arr != undefined) {
for (i = 0; i < arr.length; i++) {
d3.select(this).append("tspan")
.text(arr[i])
.attr("dy", i ? "1.2em" : 0)
.attr("x", 0)
.attr("text-anchor", "middle")
.attr("class", "tspan" + i);
}
}
});
//.text(function(d, i) { return dataSet[i].legendLabel; })
// .html(function(d, i) { return '<tspan>'+dataSet[i].legendLabel+'</tspan></n><tspan>'+dataSet[i].score+'</tspan>'})
/* arcs.append("foreignObject")
.attr("transform", function(d) {
d.outerRadius = outerRadius + 75;
d.innerRadius = outerRadius + 70;
return "translate(" + arc.centroid(d) + ")";
})
.attr("width", 50)
.attr("height", 50)
.append("xhtml:body")
.style("font", "14px 'Helvetica Neue'")
.html(function(d, i) { return dataSet[i].legendLabel+'<br>'+dataSet[i].score; });*/
</script>
</body>
</html>

Categories