Related
Need help in showing attendence value in each cell of D3 Calender visualization. I am new to D3 and kind of stuck in this step. Appreciate as much help on this.
Sample Date used for visualization
Date Station Group Attendance Absent PTO
2010-07-19 C GH 57 10 0
2010-07-20 C EF 58 10 1
2010-09-21 A GH 6 1 1
2010-09-20 A IJ 6 1 2
2010-09-17 A AB 6 1 3
HTML page
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
shape-rendering: crispEdges;
}
.day {
fill: #fff;
stroke: #ccc;
}
.month {
fill: none;
stroke: #000;
stroke-width: 2px;
}
.RdYlGn .q10-11{fill:rgb(165,0,38)}
.RdYlGn .q9-11{fill:rgb(215,48,39)}
.RdYlGn .q8-11{fill:rgb(244,109,67)}
.RdYlGn .q7-11{fill:rgb(253,174,97)}
.RdYlGn .q6-11{fill:rgb(254,224,139)}
.RdYlGn .q5-11{fill:rgb(255,255,191)}
.RdYlGn .q4-11{fill:rgb(217,239,139)}
.RdYlGn .q3-11{fill:rgb(166,217,106)}
.RdYlGn .q2-11{fill:rgb(102,189,99)}
.RdYlGn .q1-11{fill:rgb(26,152,80)}
.RdYlGn .q0-11{fill:rgb(0,104,55)}
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="https://d3js.org/d3-time-format.v2.min.js"></script>
<script>
//For Selecting Distinct Year from Date field for drop down
d3.csv("station.csv", function(error, csv) {
if (error) throw error;
var data = d3.nest()
.key(function(d) { return d.Date.split("-")[0]; })
.sortKeys(d3.descending)
.rollup(function(v) { return {
total: d3.sum(v, function(d) { return d.Attendance; })
}; })
.entries(csv);
var dropdown = d3.select('body')
.append('select')
.attr('class','select')
.attr('id','year_dropdown')
.on('change', Year_change_Del);
var options = dropdown.selectAll('option')
.data(data)
.enter()
.append('option')
.text(function (d) { return d.key; });
});
//For Selecting Distinct Year from Date field for drop down
d3.csv("station.csv", function(error, csv) {
if (error) throw error;
var data = d3.nest()
.key(function(d) { return d.Station; })
.sortKeys(d3.ascending)
.rollup(function(v) { return {
total: d3.sum(v, function(d) { return d.Attendance; })
}; })
.entries(csv);
var dropdown = d3.select('body')
.append('select')
.attr('class','select')
.attr('id','station_dropdown')
.on('change', Year_change_Del);
var options = dropdown.selectAll('option')
.data(data)
.enter()
.append('option')
.text(function (d) { return d.key; });
});
var width = 1450,
height = 190,
cellSize = 25; // cell size
var percent = d3.format(".1%"),
format = d3.time.format("%Y-%m-%d");
var color = d3.scale.quantize()
.domain([-.05, .50])
.range(d3.range(11).map(function(d) { return "q" + d + "-11"; }));
var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var week_days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
function Year_change_Del(){
d3.selectAll('svg').remove();
d3.select(".day").remove();
Year_Change_Create();
};
function Year_Change_Create() {
var station_selection = d3.select('#station_dropdown').property('value');
var year_selection = eval(d3.select('#year_dropdown').property('value')),
year_start = eval(d3.select('#year_dropdown').property('value')) -2 ,
year_end = eval(d3.select('#year_dropdown').property('value')) +1 ;
//alert(year_end);
var svg = d3.select("body").selectAll("svg")
.data(d3.range(year_start, year_end).reverse())
.enter().append("svg")
.attr("width", width)
.attr("height", height)
.attr("class", "RdYlGn")
.append("g")
.attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");
svg.append("text")
.attr("transform", "translate(-45," + cellSize * 3.5 + ")rotate(-90)")
.style("text-anchor", "middle")
.text(function(d) { return d; });
for (var i=0; i<7; i++)
{
svg.append("text")
.attr("transform", "translate(-15," + cellSize*(i+1) + ")")
.style("text-anchor", "end")
.attr("dy", "-.25em")
.text(function(d) { return week_days[i]; });
}
var rect = svg.selectAll(".day")
.data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("g");
var newrect = rect.append("rect")
.attr("id",function(d) { return d.getFullYear(d) + "," + d3.time.weekOfYear(d) * cellSize + "," + d.getDay() * cellSize; })
.attr("class", "day")
.attr("width", cellSize)
.attr("height", cellSize)
.attr("x", function(d) { return d3.time.weekOfYear(d) * cellSize; })
.attr("y", function(d) { return d.getDay() * cellSize; })
.datum(format);
newrect.append("title")
.text(function(d) { return d ; });
var newrect1 = rect.append("text")
.attr("class", "day")
.attr("x", function(d) { return d3.time.weekOfYear(d) * cellSize ; })
.attr("y", function(d) { return d.getDay() * cellSize; })
.attr("dy", "15px")
.attr("dx", "5px")
.style({"font-size":"8px","z-index":"999999999"})
.style("text-anchor", "left")
.text(function(d) { return d ; });
// to add month name on top of graph - month name not getting aligned properly
var legend = svg.selectAll(".legend")
.data(month)
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(" + (((i+1) * ((width -50)/12))) + ",0)"; });
legend.append("text")
.attr("class", function(d,i){ return month[i] })
.style("text-anchor", "end")
.attr("dy", "-.45em")
.text(function(d,i){ return month[i] });
svg.selectAll(".month")
.data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("path")
.attr("class", "month")
.attr("d", monthPath);
d3.csv("station.csv", function(csv) {
data = csv;
dataset = datafilter(data);
data=d3.nest()
.key(function(d) { return d.Date; })
.rollup(function(d) { return (d[0].Absent * 100) / d[0].Attendance / 100; })
.map(dataset);//console.log(JSON.stringify(data));
newrect.filter(function(d) { return d in data; })
.attr("class", function(d) { return "day " + color(data[d]); })
.select("title")
.text(function(d) { return d + ": " + percent(data[d]); });
function datafilter(d){
data = data.filter(function(d) { return d.Station == station_selection;});
return data;};
});
d3.csv("station.csv", function(csv) {
data = csv;
dataset = datafilter(data);
d3.csv("station.csv", function(csv) {
data = csv;
dataset = datafilter(data);
data=d3.nest()
.key(function(d) { return d.Date; })
.rollup(function(d) { return (d[0].Absent * 100) / d[0].Attendance / 100; })
.entries(dataset);//console.log(JSON.stringify(data));
rect.filter(function(d) { return d in data; })
.select("text")
.text(function(d) { return d + ": " + percent(data[d]); });
function datafilter(d){
data = data.filter(function(d) { return d.Station == station_selection;});
return data;};
});
function monthPath(t0) {
var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
d0 = t0.getDay(), w0 = d3.time.weekOfYear(t0),
d1 = t1.getDay(), w1 = d3.time.weekOfYear(t1);
return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
+ "H" + w0 * cellSize + "V" + 7 * cellSize
+ "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
+ "H" + (w1 + 1) * cellSize + "V" + 0
+ "H" + (w0 + 1) * cellSize + "Z";
}
};
var formatTime = function(input){
var dateParse = d3.time.format("%Y-%m-%d").parse;
var dateFormat = d3.time.format("%Y");
return dateFormat(dateParse(input));
};
var formatTime = function(input){
var dateParse = d3.time.format("%Y-%m-%d").parse;
var dateFormat = d3.time.format("%u");
return dateFormat(dateParse(input));
};
</Script>
The first D3.csv creates the chart and does the coloring and even the tooltip is working. I am trying to get the data to be inserted into each cell from the second D3.csv. But this is not working. Can someone guide me on this.
d3.csv("station.csv", function(csv) {
data = csv;
dataset = datafilter(data);
data=d3.nest()
.key(function(d) { return d.Date; })
.rollup(function(d) { return (d[0].Absent * 100) / d[0].Attendance / 100; })
.map(dataset);//console.log(JSON.stringify(data));
newrect.filter(function(d) { return d in data; })
.attr("class", function(d) { return "day " + color(data[d]); })
.select("title")
.text(function(d) { return d + ": " + percent(data[d]); });
function datafilter(d){
data = data.filter(function(d) { return d.Station == station_selection;});
return data;};
});
d3.csv("station.csv", function(csv) {
data = csv;
dataset = datafilter(data);
d3.csv("station.csv", function(csv) {
data = csv;
dataset = datafilter(data);
data=d3.nest()
.key(function(d) { return d.Date; })
.rollup(function(d) { return (d[0].Absent * 100) / d[0].Attendance / 100; })
.entries(dataset);//console.log(JSON.stringify(data));
rect.filter(function(d) { return d in data; })
.select("text")
.text(function(d) { return d + ": " + percent(data[d]); });
function datafilter(d){
data = data.filter(function(d) { return d.Station == station_selection;});
return data;};
});
Who wants the d3 calendar with dates?
Here is an example fiddle created by me.
var cellSize = 17, // cell size
width = cellSize * 8,
height = cellSize * 9,
firstDayOfEachMonth = getFirstDayOfEachMonth(2013);
var day = d3.time.format("%w"),
myday = d3.time.format("%d"),
week = d3.time.format("%U"),
monthName = d3.time.format("%B");
percent = d3.format(".1%"),
format = d3.time.format("%Y-%m-%d");
var svg = d3.select("#calendars").selectAll("svg")
.data(firstDayOfEachMonth)
.enter().append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
// Just centering the month here
.attr("transform", "translate(" + (width - cellSize * 7 - 1) + "," + ((height - cellSize * 6) / 2) + ")");
svg.append("text")
.attr("transform", "translate(" + cellSize * 3.5 + ", -6)")
.style("text-anchor", "middle")
.text(function(d) { return monthName(d); });
var rect = svg.selectAll("g")
.data(function(d) { return getDaysInMonth(d); })
.enter().append("g")
.attr("class", "mygroup")
//.attr("width", cellSize)
//.attr("height", cellSize)
//.attr("x", function(d) { return day(d) * cellSize; })
//.attr("y", function(d) { return (week(d) - getFirstWeekOfMonth(d)) * cellSize; })
//.on("mouseover", function(){d3.select(this).attr("class", "hovered")})
//.on("mouseout", function(){d3.select(this).style("background-color", "white")})
//.on("mouseout", function(){d3.select(this).attr("class", "")})
// format is a function - a formatter configured to use the format specified above (format = d3.time.format("%Y-%m-%d");)
// datum will execute the function to set the data for each item in the dataset - in this case, every day in the year.
//.datum(format);
rect.append("rect")
.data(function(d) { return getDaysInMonth(d); })
//.enter().append("rect")
.attr("class", "day")
.attr("width", cellSize)
.attr("height", cellSize)
.attr("x", function(d) { return day(d) * cellSize; })
.attr("y", function(d) { return (week(d) - getFirstWeekOfMonth(d)) * cellSize; })
.on("mouseover", function(){d3.select(this).attr("class", "hovered")})
//.on("mouseout", function(){d3.select(this).style("background-color", "white")})
.on("mouseout", function(){d3.select(this).attr("class", "")})
// format is a function - a formatter configured to use the format specified above (format = d3.time.format("%Y-%m-%d");)
// datum will execute the function to set the data for each item in the dataset - in this case, every day in the year.
.datum(format);
rect.append("text")
//.text(function(d) { return d; })
.text(function(d) { return myday(d)})
.attr("x", function(d) { return day(d) * cellSize + 4; })
.attr("y", function(d) { return (week(d) - getFirstWeekOfMonth(d)) * cellSize + 12; })
rect.append("title")
// This will display the formatted date for each day in the year when hovered (title attribute)
.text(function(d) { return d; });
d3.select(self.frameElement).style("height", "2910px");
function getDaysInYear(year) {
return d3.time.days(new Date(year, 0, 1), new Date(year + 1, 0, 1));
}
function getFirstDayOfEachMonth(year) {
return d3.time.months(new Date(year, 0, 1), new Date(year + 1, 0, 1));
}
function getDaysInMonth(firstDayOfMonth) {
return d3.time.days(firstDayOfMonth, new Date(firstDayOfMonth.getFullYear(), firstDayOfMonth.getMonth() + 1, 1));
}
function getFirstWeekOfMonth(day) {
// TODO: stop using this. It's wasteful because it gets executed for every day of every month.
// We should only do this once per month. The problem is with referencing data throughout a month.
// Perhaps use a closure - http://stackoverflow.com/questions/13076553/combining-parent-and-nested-data-with-d3-js
// also, the "each" reference in - http://nelsonslog.wordpress.com/2011/04/03/d3-selections/
return week(new Date(day.getFullYear(), day.getMonth(), 1));
}
body {
font: 10px sans-serif;
shape-rendering: crispEdges;
}
.day {
fill: #fff;
stroke: #ccc;
}
.month {
fill: none;
stroke: #000;
stroke-width: 2px;
}
#calendars rect {
fill: #ffffff;
stroke: #bbbbbb;
}
#calendars rect.hovered {
fill: #f0f8ff;
}
<div id="calendars"></div>
I'm trying to build a legend to a calendar view graph using d3 js like this one
but i'm trying to build a legend to it like the kind of shown in the pic
but i'm not able to generate this
here's my code to generated calender view map
var Comparison_Type_Max = d3.max(inputData, function(d) { return d.value; });
var data = d3.nest()
.key(function(d) { return d.Date; })
.rollup(function(d) { return (d[0].value ); })
.map(inputData);
var margin = { top: 20, right: 50, bottom: 10, left: 60 },
width = $(dom_element_to_append_to).parent().width() - margin.left - margin.right,
cellSize = Math.floor(width/52),
height = cellSize * 7 + margin.top + margin.bottom ,
week_days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
$rootScope.defaultWidth = width;
$rootScope.cellSize = cellSize;
var day = d3.time.format("%w"),
week = d3.time.format("%U"),
percent = d3.format(".1%"),
format = d3.time.format("%Y%m%d"),
legendElementWidth = cellSize * 2,
buckets = 9,
parseDate = d3.time.format("%Y%m%d").parse;
var color = d3.scale.linear().range(colorRange)
.domain([0, 1]);
var colorScale = d3.scale.quantile()
.domain([0, buckets - 1, d3.max(data, function (d) { return d.value; })])
.range(colorRange);
var svg = d3.select(dom_element_to_append_to).selectAll("svg")
.data(d3.range(year, year+1))
.enter().append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("data-height", '0.5678')
.attr("class", "RdYlGn")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//.attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");
console.log("1");
svg.append("text")
.attr("transform", "translate(-38," + cellSize * 3.5 + ")rotate(-90)")
.style("text-anchor", "middle")
.text(function(d) { return d; });
for (var i=0; i<7; i++)
{
svg.append("text")
.attr("transform", "translate(-5," + cellSize*(i+1) + ")")
.style("text-anchor", "end")
.attr("dy", "-.25em")
.text(function(d) { return week_days[i]; });
}
var rect = svg.selectAll(".day")
.data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter()
.append("rect")
.attr("class", "day")
.attr("width", cellSize)
.attr("height", cellSize)
.attr("x", function(d) { return week(d) * cellSize; })
.attr("y", function(d) { return day(d) * cellSize; })
.attr("fill",'#fff')
.datum(format);
console.log("2");
/* var legend = svg.selectAll(".legend")
.data(data)
.enter().append("g")
.attr("class", "legend");
//.attr("transform", function(d, i) { return "translate(" + (((i+1) * cellSize*4.33)) + ",0)"; });
legend.append("rect")
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height)
.attr("width", legendElementWidth)
.attr("height", cellSize / 2)
.style("fill", function(d, i) { return color(Math.sqrt(data[d] / Comparison_Type_Max )); });
legend.append("text")
.attr("class", "mono")
.text(function(d) { return "≥ " + Math.round(d); })
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height + cellSize);
*/
var legend = svg.selectAll(".legend")
.data([0].concat(colorScale.quantiles()), function(d) { return d; });
legend.enter().append("g")
.attr("class", "legend");
legend.append("rect")
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height)
.attr("width", legendElementWidth)
.attr("height", cellSize / 2)
.style("fill", function(d, i) { return color(Math.sqrt(data[i] / Comparison_Type_Max )); });
legend.append("text")
.attr("class", "mono")
.text(function(d) { return "≥ " + Math.round(d); })
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height + cellSize);
legend.exit().remove();
svg.selectAll(".month")
.data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("path")
.attr("class", "month")
.attr("id", function(d,i){ return month[i] + "" + varID })
.attr("d", monthPath);
console.log("4");
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
var year = d/10000;
year = Math.floor(year);
var month = d/100;
month = Math.floor(month % 100);
var day = d % 100;
if(day<10) day = "0" + day;
if(month < 10) month = "0" + month;
if(isCurrency)
return "<div><span>Date:</span> <span style='color:white'>" + day + "/" + month + "/" + year + "</span></div>" +
"<div><span>Value:</span> <span style='color:white'><span>₹</span>" + d3.format(",")(data[d]) + "</span></div>";
else
return "<div><span>Date:</span> <span style='color:white'>" + day + "/" + month + "/" + year + "</span></div>" +
"<div><span>Value:</span> <span style='color:white'>" + d3.format(",")(data[d]) + "</span></div>";
});
console.log("5");
svg.call(tip);
console.log("6");
rect.filter(function(d) { return d in data; })
.on("click", function(d){
console.log(d);
var year = d/10000;
year = Math.floor(year);
var monthInt = d/100;
console.log(dom_element_to_append_to);
var val,id;
if(dom_element_to_append_to=='.sms-yearheatmap-container-negative')
val = 0;
else if (dom_element_to_append_to=='.sms-yearheatmap-container-positive')
val = 1;
else val = 2;
monthInt = Math.floor(monthInt % 100);
for (var itr = 0; itr<12; ++itr) {
id = month[itr] + "" + varID;
$('#' + id).css("z-index",0);
$('#' + id).css("stroke","#000");
$('#' + id).css("stroke-width", "2.5px");
}
id = month[monthInt-1] + "" + varID;
$('#' + id).css("stroke","blue");
$('#' + id).css("position","relative");
$('#' + id).css("z-index",1000);
$('#' + id).css("stroke-width", "4.5px");
console.log("year " + year + " month" + monthInt);
$rootScope.loadDayHourHeatGraph(year, monthInt , val, isCurrency);
})
.attr("fill", function(d) { return color(Math.sqrt(data[d] / Comparison_Type_Max )); })
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
/*.attr("data-title", function(d) { return "value : "+Math.round(data[d])});
$("rect").tooltip({container: 'body', html: true, placement:'top'}); */
/* $("rect").on("click", function(d) {
console.log(d);
});*/
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
it is generting the graph correctly but my legend is not generating with it
here's the code of legend which i wrote above
var legend = svg.selectAll(".legend")
.data([0].concat(colorScale.quantiles()), function(d) { return d; });
legend.enter().append("g")
.attr("class", "legend");
legend.append("rect")
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height)
.attr("width", legendElementWidth)
.attr("height", cellSize / 2)
.style("fill", function(d, i) { return color(Math.sqrt(data[i] / Comparison_Type_Max )); });
legend.append("text")
.attr("class", "mono")
.text(function(d) { return "≥ " + Math.round(d); })
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height + cellSize);
legend.exit().remove();
i don't want to use the colorscale variable instead i want to generate the legend according to the color variable defined in the main code, the colorscale variable is not used anywhere in the code but only in the legend just for a start, the whole calender view graph is generated using the the colorscheme provided by the color variable
I have a sunburst which has following layers of data
world=>continents=>countries=>fuels
NOw I want to include names of elements only until countries and not names of fuels. With my code I can add names of all elements in the dropdown but not sure how to remove names of fuels from the dropdown.
Fiddle: http://jsfiddle.net/8wd2xt9n/14/
Full code:
var width = 960,
height = 700,
radius = Math.min(width, height) / 2;
var b = {
w: 130,
h: 30,
s: 3,
t: 10
};
var x = d3.scale.linear()
.range([0, 2 * Math.PI]);
var y = d3.scale.sqrt()
.range([0, radius]);
var changeArray = [100, 80, 60, 0, -60, -80, -100];
var colorArray = ["#67000d", "#b73e43", "#d5464a", "#f26256", "#fb876e", "#fca78e", "#fcbba1", "#fee0d2", "#fff5f0"];
var svg = d3.select("#diagram").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + (height / 2 + 10) + ")");
var partition = d3.layout.partition()
.value(function (d) {
return d.Total;
});
var arc = d3.svg.arc()
.startAngle(function (d) {
return Math.max(0, Math.min(2 * Math.PI, x(d.x)));
})
.endAngle(function (d) {
return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx)));
})
.innerRadius(function (d) {
return Math.max(0, y(d.y));
})
.outerRadius(function (d) {
return Math.max(0, y(d.y + d.dy));
});
console.log(arc)
function checkIt(error, root) {
initializeBreadcrumbTrail();
//intilaize dropdown
if (error) throw error;
var g = svg.selectAll("g")
.data(partition.nodes(root))
.enter().append("g");
var path = g.append("path")
.attr("d", arc)
.style("fill", function (d) {
var color;
if (d.Total_Change > 100) {
color = colorArray[0]
} else if (d.Total_Change > 0 && d.Total_Change < 100) {
color = colorArray[1]
} else {
color = colorArray[2]
}
d.color = color;
return color
})
.on("click", click)
.on("mouseover", mouseover);
var tooltip = d3.select("body")
.append("div")
.attr("id", "tooltips")
.style("position", "absolute")
.style("background-color", "#fff")
.style("z-index", "10")
.style("visibility", "hidden");
g.on("mouseover", function (d) {
return tooltip.style("visibility", "visible")
.html("<div class=" + "tooltip_container>" + "<h4 class=" + "tooltip_heading>" + d.name.replace(/[_-]/g, " ") + "</h4>" + "<br>" + "<p> Emissions 2013:" + " " + "<br>" + d.Total + " " + "<span>in Million Tons</span></p>" + "<br>" + "<p> Change in Emissions: <span>" + (d.Total_Change / d.Total * 100).toPrecision(3) + "%" + "</span></p>" + "</div>");
})
.on("mousemove", function () {
return tooltip.style("top", (d3.event.pageY - 10) + "px").style("left", (d3.event.pageX + 10) + "px");
})
.on("mouseout", function () {
return tooltip.style("visibility", "hidden");
});
//creating a dropdown
var dropDown = d3.select("#dropdown_container")
.append("select")
.attr("class", "selection")
.attr("name", "country-list");
var nodeArr = partition.nodes(root);
var options = dropDown.selectAll("option")
.data(nodeArr)
.enter()
.append("option");
options.text(function (d) {
var prefix = new Array(d.depth + 1);
var dropdownValues = d.name.replace(/[_-]/g, " ");
return dropdownValues;
}).attr("value", function (d) {
var dropdownValues = d.name;
return dropdownValues;
});
// transition on click
function click(d) {
// fade out all text elements
console.log(d)
path.transition()
.duration(750)
.attrTween("d", arcTween(d))
.each("end", function (e, i) {
// check if the animated element's data e lies within the visible angle span given in d
if (e.x >= d.x && e.x < (d.x + d.dx)) {
// get a selection of the associated text element
var arcText = d3.select(this.parentNode).select("text");
// fade in the text element and recalculate positions
arcText.transition().duration(750)
.attr("opacity", 1)
.attr("transform", function () {
return "rotate(" + computeTextRotation(e) + ")"
})
.attr("x", function (d) {
return y(d.y);
});
}
});
};
d3.select(".selection").on("change", function changePie() {
var value = this.value;
var index = this.selectedIndex;
var dataObj = nodeArr[index];
path[0].forEach(function (p) {
var data = d3.select(p).data(); //get the data from the path
if (data[0].name === value) {
console.log(data)
click(data[0]);//call the click function
}
});
console.log(this.value + " :c " + dataObj["Iron and steel"] + " in " + (dataObj.parent && dataObj.parent.name));
});
};
d3.json("https://gist.githubusercontent.com/heenaI/cbbc5c5f49994f174376/raw/743b3964d1dcc0b005ec2b024414877a36b0bd33/data.json", checkIt);
d3.select(self.frameElement).style("height", height + "px");
// Interpolate the scales!
function arcTween(d) {
var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
yd = d3.interpolate(y.domain(), [d.y, 1]),
yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]);
return function (d, i) {
return i ? function (t) {
return arc(d);
} : function (t) {
x.domain(xd(t));
y.domain(yd(t)).range(yr(t));
return arc(d);
};
};
}
function initializeBreadcrumbTrail() {
// Add the svg area.
var trail = d3.select("#sequence").append("svg:svg")
.attr("width", width)
.attr("height", 50)
.attr("id", "trail");
// Add the label at the end, for the percentage.
trail.append("svg:text")
.attr("id", "endlabel")
.style("fill", "#000");
}
function breadcrumbPoints(d, i) {
var points = [];
points.push("0,0");
points.push(b.w + ",0");
points.push(b.w + b.t + "," + (b.h / 2));
points.push(b.w + "," + b.h);
points.push("0," + b.h);
if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
points.push(b.t + "," + (b.h / 2));
}
return points.join(" ");
}
// Update the breadcrumb trail to show the current sequence and percentage.
function updateBreadcrumbs(nodeArray) {
// Data join; key function combines name and depth (= position in sequence).
var g = d3.select("#trail")
.selectAll("g")
.data(nodeArray, function (d) {
return d.name.replace(/[_-]/g, " ") + d.Total;
});
// Add breadcrumb and label for entering nodes.
var entering = g.enter().append("svg:g");
entering.append("svg:polygon")
.attr("points", breadcrumbPoints)
.style("fill", "#d3d3d3");
entering.append("svg:text")
.attr("x", (b.w + b.t) / 2)
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function (d) {
return d.name.replace(/[_-]/g, " ");
});
// Set position for entering and updating nodes.
g.attr("transform", function (d, i) {
return "translate(" + i * (b.w + b.s) + ", 0)";
});
// Remove exiting nodes.
g.exit().remove();
// Now move and update the percentage at the end.
d3.select("#trail").select("#endlabel")
.attr("x", (nodeArray.length + 0.5) * (b.w + b.s))
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle");
// Make the breadcrumb trail visible, if it's hidden.
d3.select("#trail")
.style("visibility", "");
}
function getAncestors(node) {
var path = [];
var current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
function mouseover(d) {
var sequenceArray = getAncestors(d);
updateBreadcrumbs(sequenceArray);
}
Code that creates dropdown
/creating a dropdown
var dropDown = d3.select("#dropdown_container")
.append("select")
.attr("class", "selection")
.attr("name", "country-list");
var nodeArr = partition.nodes(root);
var options = dropDown.selectAll("option")
.data(nodeArr)
.enter()
.append("option");
options.text(function (d) {
var prefix = new Array(d.depth + 1);
var dropdownValues = d.name.replace(/[_-]/g, " ");
return dropdownValues;
}).attr("value", function (d) {
var dropdownValues = d.name;
return dropdownValues;
});
Data structure can be viewed here
As you are grabbing the values of the dropdown menu from the nodes of the partition, you have the depth of the nodes at hand when setting up the dropdown, thus you can filter:
var nodeArr = partition.nodes(root);
var options = dropDown.selectAll("option")
.data(nodeArr.filter(function(d){return d.depth < 3;}))
.enter()
.append("option");
I hope that helps!
(see fiddle)
I would just pre-process the data. In the original root structure you know the countries are 2 levels down so:
var countries = [];
root.children.forEach(function (c){
c.children.forEach(function (d){
countries.push(d.name.replace(/[_-]/g, " "));
});
});
And the dropdown becomes:
var options = dropDown.selectAll("option")
.data(countries)
.enter()
.append("option");
options.text(function (d) {
return d;
}).attr("value", function (d) {
return d;
});
Updated fiddle.
I am have created chart using d3.js, when I zoom in or zoom out on web browser this charts do not re-size according to window.
Following is what I have done:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<style type="text/css">
svg {
font-family: "Helvetica Neue", Helvetica;
}
.line {
fill: none;
stroke: #000;
stroke-width: 2px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var m = [20, 20, 30, 20],
w = 960 - m[1] - m[3],
h = 500 - m[0] - m[2];
var x,
y,
duration = 1500,
delay = 500;
var color = d3.scale.category10();
var svg = d3.select("body").append("svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
var stocks,
symbols;
// A line generator, for the dark stroke.
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.price); });
// A line generator, for the dark stroke.
var axis = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(h);
// A area generator, for the dark stroke.
var area = d3.svg.area()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y1(function(d) { return y(d.price); });
d3.csv("stocks.csv", function(data) {
var parse = d3.time.format("%b %Y").parse;
// Nest stock values by symbol.
symbols = d3.nest()
.key(function(d) { return d.symbol; })
.entries(stocks = data);
// Parse dates and numbers. We assume values are sorted by date.
// Also compute the maximum price per symbol, needed for the y-domain.
symbols.forEach(function(s) {
s.values.forEach(function(d) { d.date = parse(d.date); d.price = +d.price; });
s.maxPrice = d3.max(s.values, function(d) { return d.price; });
s.sumPrice = d3.sum(s.values, function(d) { return d.price; });
});
// Sort by maximum price, descending.
symbols.sort(function(a, b) { return b.maxPrice - a.maxPrice; });
var g = svg.selectAll("g")
.data(symbols)
.enter().append("g")
.attr("class", "symbol");
setTimeout(lines, duration);
});
function lines() {
x = d3.time.scale().range([0, w - 60]);
y = d3.scale.linear().range([h / 4 - 20, 0]);
// Compute the minimum and maximum date across symbols.
x.domain([
d3.min(symbols, function(d) { return d.values[0].date; }),
d3.max(symbols, function(d) { return d.values[d.values.length - 1].date; })
]);
var g = svg.selectAll(".symbol")
.attr("transform", function(d, i) { return "translate(0," + (i * h / 4 + 10) + ")"; });
g.each(function(d) {
var e = d3.select(this);
e.append("path")
.attr("class", "line");
e.append("circle")
.attr("r", 5)
.style("fill", function(d) { return color(d.key); })
.style("stroke", "#000")
.style("stroke-width", "2px");
e.append("text")
.attr("x", 12)
.attr("dy", ".31em")
.text(d.key);
});
function draw(k) {
g.each(function(d) {
var e = d3.select(this);
y.domain([0, d.maxPrice]);
e.select("path")
.attr("d", function(d) { return line(d.values.slice(0, k + 1)); });
e.selectAll("circle, text")
.data(function(d) { return [d.values[k], d.values[k]]; })
.attr("transform", function(d) { return "translate(" + x(d.date) + "," + y(d.price) + ")"; });
});
}
var k = 1, n = symbols[0].values.length;
d3.timer(function() {
draw(k);
if ((k += 2) >= n - 1) {
draw(n - 1);
setTimeout(horizons, 500);
return true;
}
});
}
function horizons() {
svg.insert("defs", ".symbol")
.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", w)
.attr("height", h / 4 - 20);
var color = d3.scale.ordinal()
.range(["#c6dbef", "#9ecae1", "#6baed6"]);
var g = svg.selectAll(".symbol")
.attr("clip-path", "url(#clip)");
area
.y0(h / 4 - 20);
g.select("circle").transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + (w - 60) + "," + (-h / 4) + ")"; })
.remove();
g.select("text").transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + (w - 60) + "," + (h / 4 - 20) + ")"; })
.attr("dy", "0em");
g.each(function(d) {
y.domain([0, d.maxPrice]);
d3.select(this).selectAll(".area")
.data(d3.range(3))
.enter().insert("path", ".line")
.attr("class", "area")
.attr("transform", function(d) { return "translate(0," + (d * (h / 4 - 20)) + ")"; })
.attr("d", area(d.values))
.style("fill", function(d, i) { return color(i); })
.style("fill-opacity", 1e-6);
y.domain([0, d.maxPrice / 3]);
d3.select(this).selectAll(".line").transition()
.duration(duration)
.attr("d", line(d.values))
.style("stroke-opacity", 1e-6);
d3.select(this).selectAll(".area").transition()
.duration(duration)
.style("fill-opacity", 1)
.attr("d", area(d.values))
.each("end", function() { d3.select(this).style("fill-opacity", null); });
});
setTimeout(areas, duration + delay);
}
function areas() {
var g = svg.selectAll(".symbol");
axis
.y(h / 4 - 21);
g.select(".line")
.attr("d", function(d) { return axis(d.values); });
g.each(function(d) {
y.domain([0, d.maxPrice]);
d3.select(this).select(".line").transition()
.duration(duration)
.style("stroke-opacity", 1)
.each("end", function() { d3.select(this).style("stroke-opacity", null); });
d3.select(this).selectAll(".area")
.filter(function(d, i) { return i; })
.transition()
.duration(duration)
.style("fill-opacity", 1e-6)
.attr("d", area(d.values))
.remove();
d3.select(this).selectAll(".area")
.filter(function(d, i) { return !i; })
.transition()
.duration(duration)
.style("fill", color(d.key))
.attr("d", area(d.values));
});
svg.select("defs").transition()
.duration(duration)
.remove();
g.transition()
.duration(duration)
.each("end", function() { d3.select(this).attr("clip-path", null); });
setTimeout(stackedArea, duration + delay);
}
function stackedArea() {
var stack = d3.layout.stack()
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.price; })
.out(function(d, y0, y) { d.price0 = y0; })
.order("reverse");
stack(symbols);
y
.domain([0, d3.max(symbols[0].values.map(function(d) { return d.price + d.price0; }))])
.range([h, 0]);
line
.y(function(d) { return y(d.price0); });
area
.y0(function(d) { return y(d.price0); })
.y1(function(d) { return y(d.price0 + d.price); });
var t = svg.selectAll(".symbol").transition()
.duration(duration)
.attr("transform", "translate(0,0)")
.each("end", function() { d3.select(this).attr("transform", null); });
t.select("path.area")
.attr("d", function(d) { return area(d.values); });
t.select("path.line")
.style("stroke-opacity", function(d, i) { return i < 3 ? 1e-6 : 1; })
.attr("d", function(d) { return line(d.values); });
t.select("text")
.attr("transform", function(d) { d = d.values[d.values.length - 1]; return "translate(" + (w - 60) + "," + y(d.price / 2 + d.price0) + ")"; });
setTimeout(streamgraph, duration + delay);
}
function streamgraph() {
var stack = d3.layout.stack()
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.price; })
.out(function(d, y0, y) { d.price0 = y0; })
.order("reverse")
.offset("wiggle");
stack(symbols);
line
.y(function(d) { return y(d.price0); });
var t = svg.selectAll(".symbol").transition()
.duration(duration);
t.select("path.area")
.attr("d", function(d) { return area(d.values); });
t.select("path.line")
.style("stroke-opacity", 1e-6)
.attr("d", function(d) { return line(d.values); });
t.select("text")
.attr("transform", function(d) { d = d.values[d.values.length - 1]; return "translate(" + (w - 60) + "," + y(d.price / 2 + d.price0) + ")"; });
setTimeout(overlappingArea, duration + delay);
}
function overlappingArea() {
var g = svg.selectAll(".symbol");
line
.y(function(d) { return y(d.price0 + d.price); });
g.select(".line")
.attr("d", function(d) { return line(d.values); });
y
.domain([0, d3.max(symbols.map(function(d) { return d.maxPrice; }))])
.range([h, 0]);
area
.y0(h)
.y1(function(d) { return y(d.price); });
line
.y(function(d) { return y(d.price); });
var t = g.transition()
.duration(duration);
t.select(".line")
.style("stroke-opacity", 1)
.attr("d", function(d) { return line(d.values); });
t.select(".area")
.style("fill-opacity", .5)
.attr("d", function(d) { return area(d.values); });
t.select("text")
.attr("dy", ".31em")
.attr("transform", function(d) { d = d.values[d.values.length - 1]; return "translate(" + (w - 60) + "," + y(d.price) + ")"; });
svg.append("line")
.attr("class", "line")
.attr("x1", 0)
.attr("x2", w - 60)
.attr("y1", h)
.attr("y2", h)
.style("stroke-opacity", 1e-6)
.transition()
.duration(duration)
.style("stroke-opacity", 1);
setTimeout(groupedBar, duration + delay);
}
function groupedBar() {
x = d3.scale.ordinal()
.domain(symbols[0].values.map(function(d) { return d.date; }))
.rangeBands([0, w - 60], .1);
var x1 = d3.scale.ordinal()
.domain(symbols.map(function(d) { return d.key; }))
.rangeBands([0, x.rangeBand()]);
var g = svg.selectAll(".symbol");
var t = g.transition()
.duration(duration);
t.select(".line")
.style("stroke-opacity", 1e-6)
.remove();
t.select(".area")
.style("fill-opacity", 1e-6)
.remove();
g.each(function(p, j) {
d3.select(this).selectAll("rect")
.data(function(d) { return d.values; })
.enter().append("rect")
.attr("x", function(d) { return x(d.date) + x1(p.key); })
.attr("y", function(d) { return y(d.price); })
.attr("width", x1.rangeBand())
.attr("height", function(d) { return h - y(d.price); })
.style("fill", color(p.key))
.style("fill-opacity", 1e-6)
.transition()
.duration(duration)
.style("fill-opacity", 1);
});
setTimeout(stackedBar, duration + delay);
}
function stackedBar() {
x.rangeRoundBands([0, w - 60], .1);
var stack = d3.layout.stack()
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.price; })
.out(function(d, y0, y) { d.price0 = y0; })
.order("reverse");
var g = svg.selectAll(".symbol");
stack(symbols);
y
.domain([0, d3.max(symbols[0].values.map(function(d) { return d.price + d.price0; }))])
.range([h, 0]);
var t = g.transition()
.duration(duration / 2);
t.select("text")
.delay(symbols[0].values.length * 10)
.attr("transform", function(d) { d = d.values[d.values.length - 1]; return "translate(" + (w - 60) + "," + y(d.price / 2 + d.price0) + ")"; });
t.selectAll("rect")
.delay(function(d, i) { return i * 10; })
.attr("y", function(d) { return y(d.price0 + d.price); })
.attr("height", function(d) { return h - y(d.price); })
.each("end", function() {
d3.select(this)
.style("stroke", "#fff")
.style("stroke-opacity", 1e-6)
.transition()
.duration(duration / 2)
.attr("x", function(d) { return x(d.date); })
.attr("width", x.rangeBand())
.style("stroke-opacity", 1);
});
setTimeout(transposeBar, duration + symbols[0].values.length * 10 + delay);
}
function transposeBar() {
x
.domain(symbols.map(function(d) { return d.key; }))
.rangeRoundBands([0, w], .2);
y
.domain([0, d3.max(symbols.map(function(d) { return d3.sum(d.values.map(function(d) { return d.price; })); }))]);
var stack = d3.layout.stack()
.x(function(d, i) { return i; })
.y(function(d) { return d.price; })
.out(function(d, y0, y) { d.price0 = y0; });
stack(d3.zip.apply(null, symbols.map(function(d) { return d.values; }))); // transpose!
var g = svg.selectAll(".symbol");
var t = g.transition()
.duration(duration / 2);
t.selectAll("rect")
.delay(function(d, i) { return i * 10; })
.attr("y", function(d) { return y(d.price0 + d.price) - 1; })
.attr("height", function(d) { return h - y(d.price) + 1; })
.attr("x", function(d) { return x(d.symbol); })
.attr("width", x.rangeBand())
.style("stroke-opacity", 1e-6);
t.select("text")
.attr("x", 0)
.attr("transform", function(d) { return "translate(" + (x(d.key) + x.rangeBand() / 2) + "," + h + ")"; })
.attr("dy", "1.31em")
.each("end", function() { d3.select(this).attr("x", null).attr("text-anchor", "middle"); });
svg.select("line").transition()
.duration(duration)
.attr("x2", w);
setTimeout(donut, duration / 2 + symbols[0].values.length * 10 + delay);
}
function donut() {
var g = svg.selectAll(".symbol");
g.selectAll("rect").remove();
var pie = d3.layout.pie()
.value(function(d) { return d.sumPrice; });
var arc = d3.svg.arc();
g.append("path")
.style("fill", function(d) { return color(d.key); })
.data(function() { return pie(symbols); })
.transition()
.duration(duration)
.tween("arc", arcTween);
g.select("text").transition()
.duration(duration)
.attr("dy", ".31em");
svg.select("line").transition()
.duration(duration)
.attr("y1", 2 * h)
.attr("y2", 2 * h)
.remove();
function arcTween(d) {
var path = d3.select(this),
text = d3.select(this.parentNode.appendChild(this.previousSibling)),
x0 = x(d.data.key),
y0 = h - y(d.data.sumPrice);
return function(t) {
var r = h / 2 / Math.min(1, t + 1e-3),
a = Math.cos(t * Math.PI / 2),
xx = (-r + (a) * (x0 + x.rangeBand()) + (1 - a) * (w + h) / 2),
yy = ((a) * h + (1 - a) * h / 2),
f = {
innerRadius: r - x.rangeBand() / (2 - a),
outerRadius: r,
startAngle: a * (Math.PI / 2 - y0 / r) + (1 - a) * d.startAngle,
endAngle: a * (Math.PI / 2) + (1 - a) * d.endAngle
};
path.attr("transform", "translate(" + xx + "," + yy + ")");
path.attr("d", arc(f));
text.attr("transform", "translate(" + arc.centroid(f) + ")translate(" + xx + "," + yy + ")rotate(" + ((f.startAngle + f.endAngle) / 2 + 3 * Math.PI / 2) * 180 / Math.PI + ")");
};
}
setTimeout(donutExplode, duration + delay);
}
function donutExplode() {
var r0a = h / 2 - x.rangeBand() / 2,
r1a = h / 2,
r0b = 2 * h - x.rangeBand() / 2,
r1b = 2 * h,
arc = d3.svg.arc();
svg.selectAll(".symbol path")
.each(transitionExplode);
function transitionExplode(d, i) {
d.innerRadius = r0a;
d.outerRadius = r1a;
d3.select(this).transition()
.duration(duration / 2)
.tween("arc", tweenArc({
innerRadius: r0b,
outerRadius: r1b
}));
}
function tweenArc(b) {
return function(a) {
var path = d3.select(this),
text = d3.select(this.nextSibling),
i = d3.interpolate(a, b);
for (var key in b) a[key] = b[key]; // update data
return function(t) {
var a = i(t);
path.attr("d", arc(a));
text.attr("transform", "translate(" + arc.centroid(a) + ")translate(" + w / 2 + "," + h / 2 +")rotate(" + ((a.startAngle + a.endAngle) / 2 + 3 * Math.PI / 2) * 180 / Math.PI + ")");
};
}
}
setTimeout(function() {
svg.selectAll("*").remove();
svg.selectAll("g").data(symbols).enter().append("g").attr("class", "symbol");
lines();
}, duration);
}
</script>
</body>
</html>
I am learning d3.js, so I don't know how to do it. Please help me.
Doing this ends up being a bit code heavy, but for my graphs I tend to have 3 different parts: setup, draw and redraw. In setup I set up all the SVG containers and bind the data. In draw, I do the initial data draw (this tends to have different animations, fade-ins, etc). Then I bind window.onresize to the redraw all of the SVG data based on window/container dimensions.
I can provide you with an example of my code if you would like.
Can anybody help me convert the d3.js Calendar View implementation which looks like the one depicted here (weeks as columns): D3 Calendar View using Associative Array
to something more like this (weeks as rows): http://kamisama.github.io/cal-heatmap/v2/ (See Months > days (horizontally) section)
I've had a go at playing around with the axes, but to no avail.
Any help would be greatly appreciated.
My current code looks like this:
raApp.directive('heatMapYear', function () {
var width = 1200,
height = 150,
cellSize = 17; // cell size
var day = d3.time.format("%w"),
week = d3.time.format("%U"),
month = d3.time.format("%m"),
monthName = d3.time.format("%b"),
format = d3.time.format("%Y-%m-%d");
var color = d3.scale.quantize()
.domain([1, 5])
.range(d3.range(5).map(function(d) { return "rank" + d; }));
return {
restrict: 'A'
, replace: false
, scope: {
chartData: '='
, dateField: '='
}
, link: function (scope, element, attrs) {
scope.$watch('chartData', function(newData, oldData) {
d3.select(element[0]).selectAll('*').remove();
if (newData != undefined) {
var svg = d3.select(element[0]).selectAll("svg")
.data(function() {
var years = [];
for (var i = 0; i < newData.length; i++) {
var date = newData[i][scope.dateField];
var year = parseInt(date.substring(0, 4));
if (years.indexOf(year) == -1) {
years.push(year);
}
}
return years;
})
.enter().append("svg")
.attr("width", width)
.attr("height", height)
.attr("class", "heatClass")
.append("g")
.attr("transform", "translate(" + 50 + "," + (height - cellSize * 7 - 1) + ")");
svg.append("text")
.attr("transform", "translate(-30," + cellSize * 3.5 + ")rotate(-90)")
.style("text-anchor", "middle")
.style("font-weight", "bold")
.text(function(d) { return d; });
svg.selectAll(".monthName")
.data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("text")
.attr("x", function(d) {return (week(d) * cellSize + 50); })
.attr("y", -5)
.style("text-anchor", "middle")
.text(function(d) { return monthName(d); });
svg.selectAll(".dayName")
.data(function(d) { return ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] })
.enter().append("text")
.attr("x", -10)
.attr("y", function(d, i) {return (i * cellSize) + 12; })
.style("text-anchor", "middle")
.text(function(d) { return d; });
var svg1 = d3.select(element[0]).select("svg")
var legend = svg1.selectAll(".legend")
.data([0])
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(130," + (i * (cellSize) + 30) + ")";
});
legend.append("svg:image")
.attr("xlink:href", "img/RA-scale-small.png")
.attr("x", width - 350)
.attr("y", 0)
.attr("width",200)
.attr("height", 47);
var rect = svg.selectAll(".day")
.data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("rect")
.attr("class", "day")
.attr("width", cellSize)
.attr("height", cellSize)
.attr("x", function(d) { return week(d) * cellSize; })
.attr("y", function(d) { return day(d) * cellSize; })
.datum(format);
rect.append("title")
.text(function(d) { return d; });
svg.selectAll(".month")
.data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("path")
.attr("class", "month")
.attr("d", monthPath);
var data = d3.nest()
.key(function(d) { return d[scope.dateField]; })
.rollup(function(d) {return {rank:d[0]["rank"],revenue:d[0]["abbrRevenue"],volume:d[0]["abbrVolume"]}})
.map(newData);
rect.filter(function(d) { return d in data; })
.attr("class", function(d) {return "day " + color(data[d].rank); })
.select("title")
.text(function(d) { return d + "\nRevenue: " + data[d].revenue + "\nVolume: " + data[d].volume });
}
});
function monthPath(t0) {
var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
d0 = +day(t0), w0 = +week(t0),
d1 = +day(t1), w1 = +week(t1);
return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
+ "H" + w0 * cellSize + "V" + 7 * cellSize
+ "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
+ "H" + (w1 + 1) * cellSize + "V" + 0
+ "H" + (w0 + 1) * cellSize + "Z";
}
}
}
});
After much digging around and trial and error, I figured out a solution to this. Therefore I wanted to share the code in case it helps anyone else out there looking to achieve similar results.
The code is as follows:
raApp.directive('heatMapYearWeekRows', function () {
var width = 1490,
height = 200,
cellSize = 17; // cell size
var day = d3.time.format("%w"),
week = d3.time.format("%U"),
month = d3.time.format("%m"),
monthName = d3.time.format("%b"),
format = d3.time.format("%Y-%m-%d"),
displayFormat = d3.time.format("%a, %d %b %Y");
var color = d3.scale.quantize()
.domain([1, 5])
.range(d3.range(5).map(function(d) { return "rank" + d; }));
return {
restrict: 'A'
, replace: false
, scope: {
chartData: '='
, dateField: '='
}
, link: function (scope, element, attrs) {
scope.$watch('chartData', function(newData, oldData) {
d3.select(element[0]).selectAll('*').remove();
if (newData != undefined) {
var svg = d3.select(element[0]).selectAll("svg")
.data(function() {
var years = [];
for (var i = 0; i < newData.length; i++) {
var date = newData[i][scope.dateField];
var year = parseInt(date.substring(0, 4));
if (years.indexOf(year) == -1) {
years.push(year);
}
}
return years;
})
.enter().append("svg")
.attr("width", width)
.attr("height", height)
.attr("class", "heatClass")
.append("g")
.attr("transform", "translate(" + 50 + "," + (height - cellSize * 7 - 1) + ")");
svg.append("text")
.attr("transform", "translate(-30," + cellSize * 3.5 + ")rotate(-90)")
.style("text-anchor", "middle")
.style("font-weight", "bold")
.text(function(d) { return d; });
svg.selectAll(".monthName")
.data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("text")
.attr("x", function(d) {
return ((month(d) - 1) * (7 * cellSize) + 50);
})
.attr("y", 115)
.style("text-anchor", "middle")
.style("font-weight", "bold")
.text(function(d) { return monthName(d); });
var svg1 = d3.select(element[0]).select("svg")
var legend = svg1.selectAll(".legend")
.data([0])
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(130," + (i * (cellSize) + 30) + ")";
});
legend.append("svg:image")
.attr("xlink:href", "img/RA-scale-small.png")
.attr("x", -80)
.attr("y", -30)
.attr("width",200)
.attr("height", 47);
var rect = svg.selectAll(".day")
.data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("rect")
.attr("class", "day")
.attr("width", cellSize)
.attr("height", cellSize)
.attr("x", function(d) {
var prevDay = new Date(d -1);
var monthOffset = (month(d) - 1) * (7 * cellSize);
var result = (day(d) * cellSize) + +monthOffset;
return result; })
.attr("y", function(d) {
var result = ((getMonthWeek(d) - 1) * cellSize);
return result; })
.datum(format);
rect.append("title")
.text(function(d) {
return d;
});
svg.selectAll(".month")
.data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("path")
.attr("class", "month")
.attr("d", monthPath);
var data = d3.nest()
.key(function(d) { return d[scope.dateField]; })
.rollup(function(d) {return {rank:d[0]["rank"],revenue:d[0]["abbrRevenue"],volume:d[0]["abbrVolume"]}})
.map(newData);
rect.filter(function(d) { return d in data; })
.attr("class", function(d) {return "day " + color(data[d].rank); })
.select("title")
.text(function(d) { return displayFormat(new Date(d)) + "\nRevenue: " + data[d].revenue + "\nVolume: " + data[d].volume });
}
});
function getMonthWeek(date){
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1).getDay();
return Math.ceil((date.getDate() + firstDay)/7);
}
function monthPath(t0) {
var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
d0 = +day(t0), w0 = +getMonthWeek(t0) -1, m0 = +month(t0),
d1 = +day(t1), w1 = +getMonthWeek(t1) -1;
var monthOffsetX = (+m0 - 1) * (7 * cellSize);
return "M" + ((d0 * cellSize) + +monthOffsetX) + "," + ((w0 + 1) * cellSize)
+ "V" + w0 * cellSize + "H" + ((7 * cellSize) + +monthOffsetX)
+ "V" + w1 * cellSize + "H" + (((d1 + 1) * cellSize) + +monthOffsetX)
+ "V" + ((w1 + 1) * cellSize) + "H" + +monthOffsetX
+ "V" + ((w0 + 1) * cellSize) + "Z";
}
}
}
});
Hope that helps.