Quite good looking graph derived from d3.js http://c3js.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1825 lines
76 KiB

12 years ago
(function (window) {
11 years ago
window.c3 = {};
12 years ago
/*
* Generate chart according to config
*/
12 years ago
c3.generate = function (config) {
12 years ago
12 years ago
var c3 = { data : {} },
11 years ago
cache = {};
12 years ago
var EXPANDED = '_expanded_', SELECTED = '_selected_', INCLUDED = '_included_';
12 years ago
/*-- Handle Config --*/
12 years ago
function checkConfig (key, message) {
11 years ago
if ( ! (key in config)) throw Error(message);
12 years ago
}
12 years ago
12 years ago
function getConfig (keys, defaultValue) {
11 years ago
var target = config;
12 years ago
for (var i = 0; i < keys.length; i++) {
11 years ago
if ( ! (keys[i] in target)) return defaultValue;
target = target[keys[i]];
12 years ago
}
11 years ago
return target;
12 years ago
}
12 years ago
// bindto - id to bind the chart
11 years ago
checkConfig('bindto', 'bindto is required in config');
12 years ago
12 years ago
var __size_width = getConfig(['size','width'], 640),
11 years ago
__size_height = getConfig(['size','height'], 280);
12 years ago
// data - data configuration
11 years ago
checkConfig('data', 'data is required in config');
12 years ago
var __data_x = getConfig(['data','x'], 'x'),
__data_x_format = getConfig(['data','x_format'], '%Y-%m-%d'),
__data_id_converter = getConfig(['data','id_converter'], function(id){ return id; }),
__data_names = getConfig(['data','names'], {}),
__data_groups = getConfig(['data','groups'], []),
__data_axes = getConfig(['data','axes'], {}),
12 years ago
__data_types = getConfig(['data','types'], {}),
__data_regions = getConfig(['data','regions'], {}),
__data_colors = getConfig(['data','colors'], {}),
12 years ago
__data_selection_enabled = getConfig(['data','selection','enabled'], false),
__data_selection_grouped = getConfig(['data','selection','grouped'], false),
11 years ago
__data_selection_isselectable = getConfig(['data','selection','isselectable'], function(d){return true});
12 years ago
// subchart
var __subchart_show = getConfig(['subchart','show'], false),
12 years ago
__subchart_size_height = __subchart_show ? getConfig(['subchart','size','height'], 60) : 0,
11 years ago
__subchart_default = getConfig(['subchart','default'], null);
12 years ago
// color
11 years ago
var __color_pattern = getConfig(['color','pattern'], null);
12 years ago
// legend
12 years ago
var __legend_show = getConfig(['legend','show'], true),
__legend_item_width = getConfig(['legend','item','width'], 80), // TODO: auto
11 years ago
__legend_item_onclick = getConfig(['legend','item','onclick'], function(){});
12 years ago
// axis
12 years ago
var __axis_x_type = getConfig(['axis','x','type'], 'indexed'),
11 years ago
__axis_x_categories = getConfig(['axis','x','categories'], []),
12 years ago
__axis_x_tick_centered = getConfig(['axis','x','tick','centered'], false),
__axis_y_max = getConfig(['axis','y','max'], null),
__axis_y_min = getConfig(['axis','y','min'], null),
__axis_y_center = getConfig(['axis','y','center'], null),
__axis_y_text = getConfig(['axis','y','text'], null),
__axis_y_rescale = getConfig(['axis','y','rescale'], true),
__axis_y2_show = getConfig(['axis','y2','show'], false),
__axis_y2_max = getConfig(['axis','y2','max'], null),
__axis_y2_min = getConfig(['axis','y2','min'], null),
__axis_y2_center = getConfig(['axis','y2','center'], null),
__axis_y2_text = getConfig(['axis','y2','text'], null),
__axis_y2_rescale = getConfig(['axis','y2','rescale'], true),
11 years ago
__axis_rotated = getConfig(['axis','rotated'], false);
12 years ago
// grid
12 years ago
var __grid_x_show = getConfig(['grid','x','show'], false),
__grid_x_type = getConfig(['grid','x','type'], 'tick'),
__grid_x_lines = getConfig(['grid','x','lines'], null),
__grid_y_show = getConfig(['grid','y','show'], false),
__grid_y_type = getConfig(['grid','y','type'], 'tick'),
11 years ago
__grid_y_lines = getConfig(['grid','y','lines'], null);
12 years ago
// point - point of each data
12 years ago
var __point_show = getConfig(['point','show'], false),
__point_r = __point_show ? getConfig(['point','r'], 2.5) : 0,
__point_focus_line_enabled = getConfig(['point','focus','line','enabled'], true),
__point_focus_expand_enabled = getConfig(['point','focus','expand','enabled'], true),
12 years ago
__point_focus_expand_r = getConfig(['point','focus','expand','r'], __point_focus_expand_enabled ? 4 : __point_r),
__point_select_r = getConfig(['point','focus','select','r'], 8),
__point_onclick = getConfig(['point','onclick'], function(){}),
__point_onselected = getConfig(['point','onselected'], function(){}),
11 years ago
__point_onunselected = getConfig(['point','onunselected'], function(){});
12 years ago
// region - region to change style
11 years ago
var __regions = getConfig(['regions'], []);
12 years ago
// tooltip - show when mouseover on each data
12 years ago
var __tooltip_contents = getConfig(['tooltip','contents'], function(d) {
12 years ago
var date = isTimeSeries ? d[0].x.getFullYear() + '.' + (d[0].x.getMonth()+1) + '.' + d[0].x.getDate() : isCategorized ? category(d[0].x) : d[0].x,
text = "<table class='tooltip'><tr><th colspan='2'>" + date + "</th></tr>", i, value, name;
for (i = 0; i < d.length; i++){
if (isDefined(d[i])) {
value = isDefined(d[i].value) ? (Math.round(d[i].value*100)/100).toFixed(2) : '-';
name = d[i].name;
} else {
value = '-';
name = '-';
}
11 years ago
text += "<tr><td>" + name + "</td><td class='value'>" + value + "</td></tr>";
12 years ago
}
11 years ago
return text + "</table>";
});
12 years ago
12 years ago
/*-- Set Variables --*/
var clipId = config.bindto.replace('#','') + '-clip',
11 years ago
clipPath = "url(#" + clipId + ")";
12 years ago
var isTimeSeries = (__axis_x_type === 'timeseries'),
11 years ago
isCategorized = (__axis_x_type === 'categorized');
12 years ago
11 years ago
var dragStart = null, dragging = false;
12 years ago
11 years ago
var legendHeight = __legend_show ? 40 : 0;
12 years ago
var customTimeFormat = timeFormat([
12 years ago
[d3.time.format("%Y/%-m/%-d"), function() { return true }],
[d3.time.format("%-m/%-d"), function(d) { return d.getMonth() }],
[d3.time.format("%-m/%-d"), function(d) { return d.getDate() != 1 }],
[d3.time.format("%-m/%-d"), function(d) { return d.getDay() && d.getDate() != 1 }],
[d3.time.format("%I %p"), function(d) { return d.getHours() }],
[d3.time.format("%I:%M"), function(d) { return d.getMinutes() }],
[d3.time.format(":%S"), function(d) { return d.getSeconds() }],
[d3.time.format(".%L"), function(d) { return d.getMilliseconds() }]
11 years ago
]);
12 years ago
function timeFormat(formats) {
return function(date) {
11 years ago
var i = formats.length - 1, f = formats[i];
while (!f[1](date)) f = formats[--i];
return f[0](date);
};
12 years ago
}
12 years ago
/*-- Set Chart Params --*/
12 years ago
var bottom = 20 + __subchart_size_height + legendHeight,
right = __axis_y2_show && !__axis_rotated ? 50 : 1,
top2 = __size_height - __subchart_size_height - legendHeight,
bottom2 = 20 + legendHeight,
top3 = __size_height - legendHeight,
11 years ago
margin = {top: 0, right: right, bottom: bottom, left: 40},
margin2 = {top: top2, right: 20, bottom: bottom2, left: 40},
margin3 = {top: top3, right: 20, bottom: 0, left: 40},
12 years ago
width = __size_width - margin.left - margin.right,
height = __size_height - margin.top - margin.bottom,
12 years ago
height2 = __size_height - margin2.top - margin2.bottom,
11 years ago
height3 = __size_height - margin3.top - margin3.bottom;
12 years ago
11 years ago
var parseDate = d3.time.format(__data_x_format).parse;
12 years ago
var xMin = __axis_rotated ? 10 : 0,
xMax = __axis_rotated ? height : width,
yMin = __axis_rotated ? 0 : height,
11 years ago
yMax = __axis_rotated ? width : 1;
var x = ((isTimeSeries) ? d3.time.scale() : d3.scale.linear()).range([xMin, xMax]),
y = d3.scale.linear().range([yMin, yMax]),
y2 = d3.scale.linear().range([yMin, yMax]),
subX = ((isTimeSeries) ? d3.time.scale() : d3.scale.linear()).range([0, width]),
subY = d3.scale.linear().range([height2, 10]),
11 years ago
subY2 = d3.scale.linear().range([height2, 10]);
12 years ago
// TODO: Enable set position
var xAxis = isCategorized ? categoryAxis() : d3.svg.axis(),
yAxis = d3.svg.axis(),
yAxis2 = d3.svg.axis(),
11 years ago
subXAxis = isCategorized ? categoryAxis() : d3.svg.axis();
12 years ago
11 years ago
xAxis.scale(x).orient(__axis_rotated ? "left" : "bottom");
yAxis.scale(y).orient(__axis_rotated ? "bottom" : "left");
yAxis2.scale(y2).orient(__axis_rotated ? "top" : "right");
subXAxis.scale(subX).orient("bottom");
12 years ago
if (isTimeSeries) {
11 years ago
xAxis.tickFormat(customTimeFormat);
11 years ago
}
if (isCategorized) {
11 years ago
xAxis.categories(__axis_x_categories).tickCentered(__axis_x_tick_centered);
subXAxis.categories(__axis_x_categories).tickCentered(__axis_x_tick_centered);
11 years ago
} else {
// TODO: fix
xAxis.tickOffset = function () {
11 years ago
return 0;
};
// TODO: fix
subXAxis.tickOffset = function () {
11 years ago
return 0;
};
}
12 years ago
// Use custom scale if needed
if (isCategorized) {
12 years ago
// TODO: fix this
// TODO: fix x_grid
(function () {
11 years ago
var _x = x, _subX = subX;
var keys = Object.keys(x), key, i;
x = function(d){ return _x(d) + xAxis.tickOffset(); };
subX = function(d){ return _subX(d) + subXAxis.tickOffset(); };
12 years ago
for (i = 0; i < keys.length; i++) {
11 years ago
key = keys[i];
x[key] = _x[key];
subX[key] = _subX[key];
12 years ago
}
12 years ago
x.domain = function (domain) {
if (!arguments.length) {
11 years ago
var domain = _x.domain();
domain[1]++;
return domain;
12 years ago
}
11 years ago
_x.domain(domain);
return x;
};
})();
12 years ago
}
// For main region
var lineOnMain = (function () {
var line = d3.svg.line()
11 years ago
.x(__axis_rotated ? function(d){ return getYScale(d.id)(d.value); } : xx)
.y(__axis_rotated ? xx : function(d){ return getYScale(d.id)(d.value); });
return function (d) {
11 years ago
var x0, y0;
if (isLineType(d)) {
11 years ago
isSplineType(d) ? line.interpolate("cardinal") : line.interpolate("linear");
return Object.keys(__data_regions).length > 0 ? lineWithRegions(d.values, x, getYScale(d.id), __data_regions[d.id]) : line(d.values);
} else {
11 years ago
x0 = x(d.values[0].x);
y0 = getYScale(d.id)(d.values[0].value);
return __axis_rotated ? "M "+y0+" "+x0 : "M "+x0+" "+y0;
}
11 years ago
};
})();
12 years ago
// For brush region
var lineOnSub = (function () {
var line = d3.svg.line()
.x(function(d){ return subX(d.x) })
11 years ago
.y(function(d){ return getSubYScale(d.id)(d.value) });
return function (d) {
11 years ago
return isLineType(d) ? line(d.values) : "M " + subX(d.values[0].x)+ " " + getSubYScale(d.id)(d.values[0].value);
};
})();
12 years ago
// For region
var regionStart = function (d) {
11 years ago
return ('start' in d) ? x(d.start) : 0;
};
12 years ago
var regionWidth = function (d) {
var start = ('start' in d) ? x(d.start) : 0,
end = ('end' in d) ? x(d.end) : width,
11 years ago
w = end - start;
return (w < 0) ? 0 : w;
};
12 years ago
// Define color
11 years ago
var color = generateColor(__data_colors, __color_pattern);
12 years ago
12 years ago
// Define svgs
12 years ago
var svg = d3.select(config.bindto).append("svg")
.attr("width", width + margin.left + margin.right)
11 years ago
.attr("height", height + margin.top + margin.bottom);
12 years ago
11 years ago
svg.append("defs");
12 years ago
svg.select("defs").append("clipPath")
.attr("id", clipId)
.append("rect")
12 years ago
.attr("y", margin.top)
12 years ago
.attr("width", width)
11 years ago
.attr("height", height-margin.top);
12 years ago
svg.select("defs").append("clipPath")
.attr("id", "xaxis-clip")
.append("rect")
.attr("x", -1)
.attr("y", -1)
.attr("width", width + 2)
11 years ago
.attr("height", 40);
12 years ago
svg.select("defs").append("clipPath")
.attr("id", "yaxis-clip")
.append("rect")
.attr("x", -40 + 1)
12 years ago
.attr("y", margin.top - 1)
.attr("width", 40)
11 years ago
.attr("height", height - margin.top + 2);
12 years ago
// Define regions
12 years ago
var main = svg.append("g")
11 years ago
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = null;
12 years ago
if (__subchart_show) {
context = svg.append("g")
11 years ago
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
12 years ago
}
11 years ago
var legend = null;
12 years ago
if (__legend_show) {
legend = svg.append("g")
11 years ago
.attr("transform", "translate(" + margin3.left + "," + margin3.top + ")");
12 years ago
}
12 years ago
// Define tooltip
12 years ago
var tooltip = d3.select(config.bindto)
.style("position", "relative")
.append("div")
.style("position", "absolute")
.style("width", "30%") // TODO: cul actual width when show
.style("z-index", "10")
11 years ago
.style("visibility", "hidden");
12 years ago
/*-- Define Functions --*/
12 years ago
//-- Domain --//
function getYDomainMin (targets) {
11 years ago
return d3.min(targets, function(t){ return d3.min(t.values, function(v){ return v.value; }); });
12 years ago
}
12 years ago
function getYDomainMax (targets) {
11 years ago
var ys = {}, j, k;
targets.forEach(function(t){
11 years ago
ys[t.id] = [];
t.values.forEach(function(v){
11 years ago
ys[t.id].push(v.value);
});
});
for (j = 0; j < __data_groups.length; j++) {
for (k = 1; k < __data_groups[j].length; k++) {
11 years ago
if ( ! isBarType(__data_groups[j][k])) continue;
if (isUndefined(ys[__data_groups[j][k]])) continue;
ys[__data_groups[j][k]].forEach(function(v,i){
if (getAxisId(__data_groups[j][k]) === getAxisId(__data_groups[j][0])){
11 years ago
ys[__data_groups[j][0]][i] += v*1;
}
11 years ago
});
}
}
11 years ago
return d3.max(Object.keys(ys).map(function(key){ return d3.max(ys[key]); }));
12 years ago
}
function getYDomain (targets, axisId) {
11 years ago
var yTargets = getTargets(function(d){ return getAxisId(d.id) === axisId; }),
yMin = axisId === 'y2' ? __axis_y2_min : __axis_y_min,
yMax = axisId === 'y2' ? __axis_y2_max : __axis_y_max,
yDomainMin = (yMin !== null) ? yMin : getYDomainMin(yTargets),
yDomainMax = (yMax !== null) ? yMax : getYDomainMax(yTargets),
padding = Math.abs(yDomainMax - yDomainMin) * 0.1,
11 years ago
center = axisId === 'y2' ? __axis_y2_center : __axis_y_center;
if (center !== null) {
11 years ago
yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax));
yDomainMax = yDomainAbs - center;
yDomainMin = center - yDomainAbs;
12 years ago
}
11 years ago
return [hasBarType(yTargets) ? 0 : yDomainMin-padding, yDomainMax+padding];
12 years ago
}
12 years ago
function getXDomainRatio () {
11 years ago
if (brush.empty()) return 1;
var domain = subX.domain(), extent = brush.extent();
return (domain[1] - domain[0]) / (extent[1] - extent[0]);
12 years ago
}
//-- Cache --//
12 years ago
12 years ago
function hasCaches (ids) {
12 years ago
for (var i = 0; i < ids.length; i++){
11 years ago
if ( ! (ids[i] in cache)) return false;
12 years ago
}
11 years ago
return true;
12 years ago
}
12 years ago
function addCache (id, target) {
11 years ago
cache[id] = cloneTarget(target);
12 years ago
}
12 years ago
function getCaches (ids) {
11 years ago
var targets = [];
12 years ago
for (var i = 0; i < ids.length; i++){
11 years ago
if (ids[i] in cache) targets.push(cloneTarget(cache[ids[i]]));
12 years ago
}
11 years ago
return targets;
12 years ago
}
//-- Axis --//
function getAxisId (id) {
11 years ago
return id in __data_axes ? __data_axes[id] : 'y';
}
function getYScale (id) {
11 years ago
return getAxisId(id) === 'y2' ? y2 : y;
}
function getSubYScale (id) {
11 years ago
return getAxisId(id) === 'y2' ? subY2 : subY;
}
12 years ago
//-- Data --//
function convertRowsToData (rows) {
11 years ago
var keys = rows[0], new_row = {}, new_rows = [], i, j;
12 years ago
for (i = 1; i < rows.length; i++) {
11 years ago
new_row = {};
12 years ago
for (j = 0; j < rows[i].length; j++) {
11 years ago
new_row[keys[j]] = rows[i][j];
12 years ago
}
11 years ago
new_rows.push(new_row);
12 years ago
}
11 years ago
return new_rows;
12 years ago
}
12 years ago
function convertColumnsToData (columns) {
11 years ago
var new_rows = [], i, j, key;
12 years ago
for (i = 0; i < columns.length; i++) {
11 years ago
key = columns[i][0];
12 years ago
for (j = 1; j < columns[i].length; j++) {
if (isUndefined(new_rows[j-1])) {
11 years ago
new_rows[j-1] = {};
12 years ago
}
11 years ago
new_rows[j-1][key] = columns[i][j];
12 years ago
}
}
11 years ago
return new_rows;
12 years ago
}
12 years ago
function convertDataToTargets (data) {
11 years ago
var ids = d3.keys(data[0]).filter(function(key){ return key !== __data_x });
var targets, i = 0, parsedDate;
12 years ago
data.forEach(function(d) {
if (isTimeSeries) {
if (!(__data_x in d)) throw Error("'" + __data_x + "' must be included in data");
parsedDate = parseDate(d[__data_x]);
if (parsedDate === null) throw Error("Failed to parse timeseries date in data");
d.x = parsedDate;
} else {
d.x = i++;
}
11 years ago
if (firstDate === null) firstDate = new Date(d.x);
lastDate = new Date(d.x);
});
12 years ago
12 years ago
targets = ids.map(function(id,i) {
11 years ago
var convertedId = __data_id_converter(id);
12 years ago
return {
id : convertedId,
id_org : id,
values : data.map(function(d) {
11 years ago
return {x: d.x, value: +d[id], id: convertedId};
12 years ago
})
11 years ago
};
});
12 years ago
// cache as original id keyed
targets.forEach(function(d){
11 years ago
addCache(d.id_org, d);
});
12 years ago
11 years ago
return targets;
12 years ago
}
function cloneTarget (target) {
return {
id : target.id,
id_org : target.id_org,
values : target.values.map(function(d){
11 years ago
return {x: d.x, value: d.value, id: d.id};
})
11 years ago
};
}
12 years ago
function maxDataCount () {
11 years ago
return d3.max(c3.data.targets, function(t){ return t.values.length; });
12 years ago
}
function getTargetIds (targets) {
11 years ago
targets = isUndefined(targets) ? c3.data.targets : targets;
return targets.map(function(d){ return d.id; });
}
function hasTarget (id) {
11 years ago
var ids = getTargetIds(), i;
12 years ago
for (i = 0; i < ids.length; i++) {
11 years ago
if (ids[i] === id) return true;
}
11 years ago
return false;
}
function getTargets (filter) {
11 years ago
return isDefined(filter) ? c3.data.targets.filter(filter) : c3.data.targets;
}
12 years ago
function category (i) {
11 years ago
return i < __axis_x_categories.length ? __axis_x_categories[i] : i;
12 years ago
}
function classShapes (d) { return "-shapes -shapes-" + d.id; }
function classLine (d) { return classShapes(d) + " -line -line-" + d.id; }
function classCircles (d) { return classShapes(d) + " -circles -circles-" + d.id; }
function classBars (d) { return classShapes(d) + " -bars -bars-" + d.id; }
function classShape (d,i) { return "-shape -shape-" + i; }
function classCircle (d,i) { return classShape(d,i) + " -circle -circle-" + i; }
function classBar (d,i) { return classShape(d,i) + " -bar -bar-" + i; }
11 years ago
function classRegion (d,i) { return 'region region-' + i + ' ' + ('classes' in d ? [].concat(d.classes).join(' ') : ''); }
12 years ago
12 years ago
function xx (d) {
11 years ago
return x(d.x);
12 years ago
}
12 years ago
function xv (d) {
11 years ago
return x(d.value);
12 years ago
}
12 years ago
function yv (d) {
11 years ago
return y(d.value);
12 years ago
}
//-- Circle --/
function circleX (d) {
11 years ago
return x(d.x);
}
function circleY (d) {
11 years ago
return getYScale(d.id)(d.value);
}
12 years ago
//-- Bar --//
function getBarIndices () {
11 years ago
var indices = {}, i = 0, j, k;
getTargets(isBarType).forEach(function(d) {
for (j = 0; j < __data_groups.length; j++) {
11 years ago
if (__data_groups[j].indexOf(d.id) < 0) continue;
for (k = 0; k < __data_groups[j].length; k++) {
if (__data_groups[j][k] in indices) {
11 years ago
indices[d.id] = indices[__data_groups[j][k]];
break;
}
}
}
11 years ago
if (isUndefined(indices[d.id])) indices[d.id] = i++;
})
11 years ago
indices.__max__ = i-1;
return indices;
}
function getBarX (barW, barTargetsNum, barIndices, isSub) {
11 years ago
var scale = isSub ? subX : x;
return function (d) {
11 years ago
var barIndex = d.id in barIndices ? barIndices[d.id] : 0;
return scale(d.x) - barW * (barTargetsNum/2 - barIndex);
};
}
function getBarY (barH, barIndices, zeroBased, isSub) {
11 years ago
var indicesIds = Object.keys(barIndices);
return function (d,i) {
11 years ago
var offset = 0;
var scale = isSub ? getSubYScale(d.id) : getYScale(d.id);
getTargets(isBarType).forEach(function(t){
11 years ago
if (t.id === d.id || barIndices[t.id] !== barIndices[d.id]) return;
if (indicesIds.indexOf(t.id) < indicesIds.indexOf(d.id)) {
11 years ago
offset += barH(t.values[i]);
}
11 years ago
});
return zeroBased ? offset : scale(d.value) - offset;
};
}
function getBarW (axis, barTargetsNum) {
11 years ago
return (axis.tickOffset()*2*0.6) / barTargetsNum;
}
function getBarH (height, isSub) {
11 years ago
var h = height === null ? function(v){ return v; } : function(v){ return height-v; };
return function (d) {
11 years ago
var scale = isSub ? getSubYScale(d.id) : getYScale(d.id);
return h(scale(d.value));
};
}
12 years ago
//-- Type --//
function setTargetType (targets, type) {
11 years ago
var targetIds = isUndefined(targets) ? getTargetIds() : targets;
if (typeof targetIds === 'string') targetIds = [targetIds];
for (var i = 0; i < targetIds.length; i++) {
11 years ago
__data_types[targetIds[i]] = type;
}
}
function hasType (targets, type) {
11 years ago
var has = false;
targets.forEach(function(t){
11 years ago
if (__data_types[t.id] === type) has = true;
if (!(t.id in __data_types) && type === 'line') has = true;
});
return has;
}
function hasLineType (targets) {
11 years ago
return hasType(targets, 'line');
}
function hasBarType (targets) {
11 years ago
return hasType(targets, 'bar');
}
function isLineType (d) {
11 years ago
var id = (typeof d === 'string') ? d : d.id;
return !(id in __data_types) || __data_types[id] === 'line' || __data_types[id] === 'spline';
12 years ago
}
function isSplineType (d) {
11 years ago
var id = (typeof d === 'string') ? d : d.id;
return __data_types[id] === 'spline';
12 years ago
}
function isBarType (d) {
11 years ago
var id = (typeof d === 'string') ? d : d.id;
return __data_types[id] === 'bar';
12 years ago
}
function lineData (d) {
11 years ago
return isLineType(d) ? d.values : [];
}
function barData (d) {
11 years ago
return isBarType(d) ? d.values : [];
}
12 years ago
//-- Color --//
function generateColor (_colors, _pattern) {
var ids = [],
colors = _colors,
11 years ago
pattern = (_pattern !== null) ? _pattern : ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728','#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']; //same as d3.scale.category10()
12 years ago
return function (id) {
// if specified, choose that color
11 years ago
if (id in colors) return _colors[id];
12 years ago
12 years ago
// if not specified, choose from pattern
if ( ! (ids.indexOf(id) >= 0)) {
11 years ago
ids.push(id);
12 years ago
}
11 years ago
return pattern[ids.indexOf(id) % pattern.length];
};
12 years ago
}
12 years ago
//-- Util --//
12 years ago
function isWithinCircle (_this, _r) {
11 years ago
var mouse = d3.mouse(_this), d3_this = d3.select(_this);
var cx = d3_this.attr("cx")*1, cy = d3_this.attr("cy")*1;
return Math.sqrt(Math.pow(cx-mouse[0],2)+Math.pow(cy-mouse[1],2)) < _r;
12 years ago
}
function isWithinBar (_this) {
11 years ago
var mouse = d3.mouse(_this), d3_this = d3.select(_this);
var x = d3_this.attr("x")*1, y = d3_this.attr("y")*1, w = d3_this.attr("width")*1;
var sx = x - 10, ex = x + w + 10, ey = y - 10;
return sx < mouse[0] && mouse[0] < ex && ey < mouse[1];
}
12 years ago
function isWithinRegions (x, regions) {
11 years ago
var i;
12 years ago
for (i = 0; i < regions.length; i++) {
11 years ago
if (regions[i].start < x && x <= regions[i].end) return true;
12 years ago
}
11 years ago
return false;
12 years ago
}
12 years ago
12 years ago
//-- Selection --//
function selectPoint (target, d, i) {
11 years ago
__point_onselected(target, d);
12 years ago
// add selected-circle on low layer g
main.select(".selected-circles-" + d.id).selectAll('.selected-circle-' + i)
.data([d])
.enter().append('circle')
11 years ago
.attr("class", function(d){ return "selected-circle selected-circle-" + i; })
.attr("cx", __axis_rotated ? circleY : circleX)
.attr("cy", __axis_rotated ? circleX : circleY)
11 years ago
.attr("stroke", function(){ return color(d.id); })
12 years ago
.attr("r", __point_select_r * 1.4)
.transition().duration(100)
11 years ago
.attr("r", __point_select_r);
12 years ago
}
12 years ago
function unselectPoint (target, d, i) {
11 years ago
__point_onunselected(target, d);
12 years ago
// remove selected-circle from low layer g
main.select(".selected-circles-" + d.id).selectAll(".selected-circle-" + i)
.transition().duration(100).attr('r', 0)
11 years ago
.remove();
12 years ago
}
12 years ago
function togglePoint (selected, target, d, i) {
11 years ago
(selected) ? selectPoint(target, d, i) : unselectPoint(target, d, i);
12 years ago
}
12 years ago
function selectBar (target, d, i) {
}
function unselectBar (target, d, i) {
}
function toggleBar (selected, target, d, i) {
11 years ago
(selected) ? selectBar(target, d, i) : unselectBar(target, d, i);
}
12 years ago
//-- Shape --//
12 years ago
function lineWithRegions (d, x, y, regions) {
11 years ago
var prev = -1, i, j;
var s = "M";
var xp, yp, dx, dy, dd, diff, diff2;
var xValue, yValue;
12 years ago
// Check start/end of regions
if (isDefined(regions)) {
12 years ago
for (i = 0; i < regions.length; i++){
if (isUndefined(regions[i].start)) {
11 years ago
regions[i].start = d[0].x;
12 years ago
}
if (isUndefined(regions[i].end)) {
11 years ago
regions[i].end = d[d.length-1].x;
12 years ago
}
}
}
// Set scales
11 years ago
xValue = __axis_rotated ? function(d){ return y(d.value); } : function(d){ return x(d.x); };
yValue = __axis_rotated ? function(d){ return x(d.x); } : function(d){ return y(d.value); };
12 years ago
// Generate
12 years ago
for (i = 0; i < d.length; i++) {
12 years ago
// Draw as normal
if (isUndefined(regions) || ! isWithinRegions(d[i].x, regions)) {
11 years ago
s += " "+xValue(d[i])+" "+yValue(d[i]);
12 years ago
}
// Draw with region // TODO: Fix for horizotal charts
12 years ago
else {
11 years ago
xp = d3.scale.linear().range([d[i-1].x, d[i].x]);
yp = d3.scale.linear().range([d[i-1].value, d[i].value]);
dx = x(d[i].x) - x(d[i-1].x);
dy = y(d[i].value) - y(d[i-1].value);
dd = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2));
diff = 2/dd;
diffx2 = diff*2;
12 years ago
for (j = diff; j <= 1; j += diffx2) {
11 years ago
s += "M"+x(xp(j))+" "+y(yp(j))+" "+x(xp(j+diff))+" "+y(yp(j+diff));
12 years ago
}
}
11 years ago
prev = d[i].x;
12 years ago
}
11 years ago
return s;
12 years ago
}
12 years ago
12 years ago
/*-- Define brush --*/
12 years ago
var brush = d3.svg.brush().x(subX).on("brush", redrawForBrush);
12 years ago
/*-- Draw Chart --*/
// for brush area culculation
var firstDate = null,
11 years ago
lastDate = null;
12 years ago
12 years ago
function init (data) {
11 years ago
var targets = c3.data.targets = convertDataToTargets(data);
var rectX, rectW;
var grid, xgridLine;
12 years ago
// TODO: set names if names not specified
11 years ago
x.domain(d3.extent(data.map(function(d){ return d.x; })));
y.domain(getYDomain(targets, 'y'));
y2.domain(getYDomain(targets, 'y2'));
11 years ago
subX.domain(x.domain());
subY.domain(y.domain());
subY2.domain(y2.domain());
12 years ago
xAxis.ticks(data.length < 10 ? data.length : 10);
12 years ago
/*-- Main Region --*/
12 years ago
12 years ago
grid = main.append('g')
12 years ago
.attr("clip-path", clipPath)
11 years ago
.attr('class', 'grid');
12 years ago
// X-Grid
if (__grid_x_show) {
11 years ago
grid.append("g").attr("class", "xgrids");
12 years ago
}
if (__grid_x_lines) {
12 years ago
xgridLine = grid.append('g')
12 years ago
.attr("class", "xgrid-lines")
12 years ago
.selectAll('.xgrid-line')
12 years ago
.data(__grid_x_lines)
.enter().append('g')
11 years ago
.attr("class", "xgrid-line");
12 years ago
xgridLine.append('line')
11 years ago
.attr("class", function(d){ return "" + d['class']; });
12 years ago
xgridLine.append('text')
11 years ago
.attr("class", function(d){ return "" + d['class']; })
12 years ago
.attr("text-anchor", "end")
.attr("transform", __axis_rotated ? "" : "rotate(-90)")
.attr('dx', __axis_rotated ? 0 : -margin.top)
.attr('dy', -6)
11 years ago
.text(function(d){ return d.text; });
12 years ago
}
if (__point_focus_line_enabled) {
grid.append('g')
.attr("class", "xgrid-focus")
.append('line')
.attr('class', 'xgrid-focus')
.attr("x1", __axis_rotated ? 0 : -10)
.attr("x2", __axis_rotated ? width : -10)
.attr("y1", __axis_rotated ? -10 : margin.top)
11 years ago
.attr("y2", __axis_rotated ? -10 : height);
12 years ago
}
// Y-Grid
if (__grid_y_show) {
11 years ago
grid.append('g').attr('class', 'ygrids');
12 years ago
}
if (__grid_y_lines) {
grid.append('g')
.attr('class', 'ygrid-lines')
12 years ago
.selectAll('ygrid-line')
12 years ago
.data(__grid_y_lines)
.enter().append('line')
11 years ago
.attr("class", function(d){ return "ygrid-line " + d['class']; });
12 years ago
}
// Area
11 years ago
main.append('g')
.attr("clip-path", clipPath)
11 years ago
.attr("class", "regions");
12 years ago
// Define g for chart area
main.append('g')
.attr("clip-path", clipPath)
11 years ago
.attr('class', 'chart');
12 years ago
12 years ago
// Cover whole with rects for events
12 years ago
main.select('.chart').append("g")
.attr("class", "event-rects")
.style('fill-opacity', 0)
.selectAll(".event-rects")
.data(data)
.enter().append("rect")
11 years ago
.attr("class", function(d,i){ return "event-rect event-rect-" + i; })
.style("cursor", function(d){ return __data_selection_enabled && __data_selection_grouped ? "pointer" : null; })
12 years ago
.on('mouseover', function(d,i) {
11 years ago
if (dragging) return; // do nothing if dragging
12 years ago
11 years ago
var selectedData = c3.data.targets.map(function(d){ return d.values[i]; });
var j, newData, name;
12 years ago
// Add id,name to selectedData
12 years ago
for (j = 0; j < selectedData.length; j++) {
if (isUndefined(selectedData[j])) continue;
name = __data_names[selectedData[j].id];
selectedData[j].name = isDefined(name) ? name : selectedData[j].id;
12 years ago
}
// Sort selectedData as names order
if (Object.keys(__data_names).length > 0) {
11 years ago
newData = [];
12 years ago
for (var id in __data_names) {
12 years ago
for (j = 0; j < selectedData.length; j++) {
12 years ago
if (selectedData[j].id === id) {
11 years ago
newData.push(selectedData[j]);
selectedData.shift(j);
break;
12 years ago
}
}
}
11 years ago
selectedData = newData.concat(selectedData); // Add remained
12 years ago
}
// Expand circles if needed
if (__point_focus_expand_enabled) {
main.selectAll('.-circle-'+i)
.classed(EXPANDED, true)
11 years ago
.attr('r', __point_focus_expand_r);
12 years ago
}
// Expand bars
main.selectAll(".-bar-"+i)
.classed(EXPANDED, true);
12 years ago
// Show xgrid focus line
main.selectAll('line.xgrid-focus')
.style("visibility","visible")
.data([selectedData[0]])
12 years ago
.attr(__axis_rotated ? 'y1' : 'x1', xx)
11 years ago
.attr(__axis_rotated ? 'y2' : 'x2', xx);
12 years ago
// Set tooltip
tooltip.style("top", (d3.mouse(this)[1] + 30) + "px")
11 years ago
.style("left", ((__axis_rotated ? d3.mouse(this)[0] : x(selectedData[0].x)) + 60) + "px");
tooltip.html(__tooltip_contents(selectedData));
tooltip.style("visibility", "visible");
12 years ago
})
.on('mouseout', function(d,i) {
11 years ago
main.select('line.xgrid-focus').style("visibility", "hidden");
tooltip.style("visibility", "hidden");
12 years ago
// Undo expanded circles
main.selectAll('.-circle-'+i)
.filter(function(){ return d3.select(this).classed(EXPANDED); })
.classed(EXPANDED, false)
11 years ago
.attr('r', __point_r);
// Undo expanded bar
main.selectAll(".-bar-"+i)
.classed(EXPANDED, false);
12 years ago
})
.on('mousemove', function(d,i){
11 years ago
if ( ! __data_selection_enabled || dragging) return;
if ( __data_selection_grouped) return; // nothing to do when grouped
12 years ago
main.selectAll('.-shape-'+i)
11 years ago
.filter(function(d){ return __data_selection_isselectable(d); })
12 years ago
.each(function(d){
var _this = d3.select(this).classed(EXPANDED, true);
11 years ago
if (this.nodeName === 'circle') _this.attr('r', __point_focus_expand_r);
d3.select('.event-rect-'+i).style('cursor', null);
})
.filter(function(d){
11 years ago
var _this = d3.select(this);
if (this.nodeName === 'circle') {
11 years ago
return isWithinCircle(this, __point_select_r);
}
else if (this.nodeName === 'rect') {
11 years ago
return isWithinBar(this, _this.attr('x'), _this.attr('y'));
}
12 years ago
})
.each(function(d){
11 years ago
var _this = d3.select(this);
if ( ! _this.classed(EXPANDED)) {
_this.classed(EXPANDED, true);
11 years ago
if (this.nodeName === 'circle') _this.attr('r', __point_select_r);
12 years ago
}
11 years ago
d3.select('.event-rect-'+i).style('cursor', 'pointer');
});
12 years ago
})
.on('click', function(d,i) {
main.selectAll('.-shape-'+i).each(function(d){
12 years ago
var _this = d3.select(this),
isSelected = _this.classed(SELECTED);
11 years ago
var isWithin = false, toggle;
if (this.nodeName === 'circle') {
11 years ago
isWithin = isWithinCircle(this, __point_select_r*1.5);
toggle = togglePoint;
}
else if (this.nodeName === 'rect') {
11 years ago
isWithin = isWithinBar(this);
toggle = toggleBar;
}
if (__data_selection_grouped || isWithin) {
12 years ago
if (__data_selection_enabled && __data_selection_isselectable(d)) {
_this.classed(SELECTED, !isSelected);
11 years ago
toggle(!isSelected, _this, d, i);
12 years ago
}
11 years ago
__point_onclick(d, _this); // TODO: should be __data_onclick
12 years ago
}
11 years ago
});
12 years ago
})
.call(
d3.behavior.drag().origin(Object).on('drag', function(d){
11 years ago
if ( ! __data_selection_enabled) return; // do nothing if not selectable
12 years ago
var sx = dragStart[0], sy = dragStart[1],
mouse = d3.mouse(this),
mx = mouse[0],
my = mouse[1],
12 years ago
minX = Math.min(sx,mx),
maxX = Math.max(sx,mx),
minY = (__data_selection_grouped) ? margin.top : Math.min(sy,my),
11 years ago
maxY = (__data_selection_grouped) ? height : Math.max(sy,my);
12 years ago
main.select('.dragarea')
12 years ago
.attr('x', minX)
.attr('y', minY)
.attr('width', maxX-minX)
11 years ago
.attr('height', maxY-minY);
main.selectAll('.-shapes').selectAll('.-shape')
11 years ago
.filter(function(d){ return __data_selection_isselectable(d); })
12 years ago
.each(function(d,i){
var _this = d3.select(this),
isSelected = _this.classed(SELECTED),
isIncluded = _this.classed(INCLUDED),
11 years ago
_x, _y, _w, toggle, isWithin = false;
if (this.nodeName === 'circle') {
11 years ago
_x = _this.attr("cx")*1;
_y = _this.attr("cy")*1;
toggle = togglePoint;
isWithin = minX < _x && _x < maxX && minY < _y && _y < maxY;
12 years ago
}
else if (this.nodeName === 'rect') {
11 years ago
_x = _this.attr("x")*1;
_y = _this.attr("y")*1;
_w = _this.attr('width')*1;
toggle = toggleBar;
isWithin = minX < _x+_w && _x < maxX && _y < maxY;
}
12 years ago
if (isWithin ^ isIncluded) {
_this.classed(INCLUDED, !isIncluded);
// TODO: included/unincluded callback here
_this.classed(SELECTED, !isSelected);
11 years ago
toggle(!isSelected, _this, d, i);
}
11 years ago
});
12 years ago
})
.on('dragstart', function() {
11 years ago
if ( ! __data_selection_enabled) return; // do nothing if not selectable
dragStart = d3.mouse(this);
12 years ago
main.select('.chart').append('rect')
.attr('class', 'dragarea')
11 years ago
.style('opacity', 0.1);
dragging = true;
12 years ago
// TODO: add callback here
})
.on('dragend', function() {
11 years ago
if ( ! __data_selection_enabled) return; // do nothing if not selectable
12 years ago
main.select('.dragarea')
.transition().duration(100)
.style('opacity', 0)
11 years ago
.remove();
main.selectAll('.-shape')
.classed(INCLUDED, false);
11 years ago
dragging = false;
12 years ago
// TODO: add callback here
})
11 years ago
);
12 years ago
// Define g for bar chart area
main.select(".chart").append("g")
11 years ago
.attr("class", "chart-bars");
// Define g for line chart area
main.select(".chart").append("g")
11 years ago
.attr("class", "chart-lines");
12 years ago
// ATTENTION: This must be called AFTER chart added
// Add Axis
main.append("g")
.attr("class", "x axis")
.attr("clip-path", __axis_rotated ? "" : "url(#xaxis-clip)")
12 years ago
.attr("transform", "translate(0," + height + ")")
11 years ago
.call(__axis_rotated ? yAxis : xAxis);
12 years ago
main.append("g")
.attr("class", "y axis")
.attr("clip-path", __axis_rotated ? "url(#yaxis-clip)" : "")
.call(__axis_rotated ? xAxis : yAxis)
12 years ago
.append("text")
.attr("transform", "rotate(-90)")
.attr("dy", "1.4em")
.attr("dx", "-.8em")
.style("text-anchor", "end")
11 years ago
.text(__axis_y_text);
12 years ago
if (__axis_y2_show) {
main.append("g")
.attr("class", "y2 axis")
.attr("transform", "translate(" + (__axis_rotated ? 0 : width) + "," + (__axis_rotated ? 10 : 0) + ")")
11 years ago
.call(yAxis2);
}
12 years ago
/*-- Context Region --*/
if (__subchart_show) {
// Define g for chart area
context.append('g')
.attr("clip-path", clipPath)
11 years ago
.attr('class', 'chart');
12 years ago
// Define g for bar chart area
context.select(".chart").append("g")
11 years ago
.attr("class", "chart-bars");
// Define g for line chart area
context.select(".chart").append("g")
11 years ago
.attr("class", "chart-lines");
12 years ago
// ATTENTION: This must be called AFTER chart rendered and BEFORE brush called.
// Update extetn for Brush
if (__subchart_default !== null) {
11 years ago
brush.extent((isTimeSeries) ? __subchart_default(firstDate,lastDate) : __subchart_default(0,maxDataCount()-1));
12 years ago
}
// Add extent rect for Brush
context.append("g")
.attr("class", "x brush")
.call(brush)
.selectAll("rect")
11 years ago
.attr("height", height2);
12 years ago
// ATTENTION: This must be called AFTER chart added
// Add Axis
context.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height2 + ")")
11 years ago
.call(subXAxis);
12 years ago
}
/*-- Legend Region --*/
11 years ago
if (__legend_show) updateLegend(targets);
12 years ago
// Set targets
11 years ago
updateTargets(targets);
12 years ago
// Draw with targets
redraw({withTransition:false});
12 years ago
}
12 years ago
function redraw (options) {
11 years ago
var xgrid, xgridData, xgridLine;
var mainPath, mainCircle, mainBar, contextPath;
var barIndices = getBarIndices(), barTargetsNum = barIndices.__max__ + 1;
var barX, barY, barW, barH;
var rectX, rectW;
12 years ago
options = isDefined(options) ? options : {};
withY = isDefined(options.withY) ? options.withY : true;
withSubchart = isDefined(options.withSubchart) ? options.withSubchart : true;
withTransition = isDefined(options.withTransition) ? options.withTransition : true;
12 years ago
// ATTENTION: call here to update tickOffset
11 years ago
x.domain(brush.empty() ? subX.domain() : brush.extent());
y.domain(getYDomain(c3.data.targets, 'y'));
y2.domain(getYDomain(c3.data.targets, 'y2'));
11 years ago
main.selectAll(".x.axis").transition().duration(__axis_rotated ? 250 : 0).call(__axis_rotated ? yAxis : xAxis);
main.selectAll(".y.axis").transition().duration(__axis_rotated ? 0 : 250).call(__axis_rotated ? xAxis : yAxis);
main.selectAll(".y2.axis").transition().call(yAxis2);
// Update sub domain
11 years ago
subY.domain(y.domain());
subY2.domain(y2.domain());
12 years ago
// grid
if (__grid_x_show) {
if (__grid_x_type === 'year') {
11 years ago
xgridData = [];
firstYear = firstDate.getFullYear();
lastYear = lastDate.getFullYear();
12 years ago
for (var year = firstYear; year <= lastYear; year++) {
11 years ago
xgridData.push(new Date(year + '-01-01 00:00:00'));
12 years ago
}
} else {
11 years ago
xgridData = x.ticks(10);
12 years ago
}
12 years ago
12 years ago
xgrid = main.select('.xgrids').selectAll(".xgrid")
11 years ago
.data(xgridData);
xgrid.enter().append('line').attr("class", "xgrid");
xgrid.exit().remove();
12 years ago
main.selectAll(".xgrid")
12 years ago
.attr("x1", function(d){ return x(d) - xAxis.tickOffset(); })
.attr("x2", function(d){ return x(d) - xAxis.tickOffset(); })
12 years ago
.attr("y1", margin.top)
11 years ago
.attr("y2", height);
12 years ago
}
if (__grid_x_lines) {
11 years ago
xgridLine = main.selectAll(".xgrid-lines");
12 years ago
xgridLine.selectAll('line')
12 years ago
.attr("x1", __axis_rotated ? 0 : xv)
.attr("x2", __axis_rotated ? width : xv)
.attr("y1", __axis_rotated ? xv : margin.top)
11 years ago
.attr("y2", __axis_rotated ? xv : height);
12 years ago
xgridLine.selectAll('text')
12 years ago
.attr("x", __axis_rotated ? width : 0)
11 years ago
.attr("y", xv);
12 years ago
}
12 years ago
// Y-Grid
if (withY && __grid_y_show) {
12 years ago
ygrid = main.select('.ygrids').selectAll(".ygrid")
11 years ago
.data(y.ticks(10));
12 years ago
ygrid.enter().append('line')
11 years ago
.attr('class', 'ygrid');
ygrid.attr("x1", __axis_rotated ? y : 0)
.attr("x2", __axis_rotated ? y : width)
.attr("y1", __axis_rotated ? 0 : y)
.attr("y2", __axis_rotated ? height : y)
12 years ago
.attr("opacity", 0)
.transition()
11 years ago
.attr("opacity", 1);
ygrid.exit().remove();
12 years ago
}
if (withY && __grid_y_lines) {
12 years ago
main.select('.ygrid-lines').selectAll('.ygrid-line')
12 years ago
.attr("y1", yv)
11 years ago
.attr("y2", yv);
12 years ago
}
12 years ago
12 years ago
// bars
11 years ago
barW = getBarW(xAxis, barTargetsNum);
barH = getBarH(__axis_rotated ? null : height);
barX = getBarX(barW, barTargetsNum, barIndices);
barY = getBarY(barH, barIndices, __axis_rotated);
mainBar = main.selectAll('.-bars').selectAll('.-bar')
11 years ago
.data(barData);
12 years ago
mainBar.transition().duration(withTransition ? 250 : 0)
.attr("x", __axis_rotated ? barY : barX)
.attr("y", __axis_rotated ? barX : barY)
.attr("width", __axis_rotated ? barH : barW)
11 years ago
.attr("height", __axis_rotated ? barW : barH);
mainBar.enter().append('rect')
.attr("class", classBar)
.attr("x", __axis_rotated ? barY : barX)
.attr("y", __axis_rotated ? barX : barY)
.attr("width", __axis_rotated ? barH : barW)
.attr("height", __axis_rotated ? barW : barH)
.style("opacity", 0)
12 years ago
.transition().duration(withTransition ? 250 : 0)
11 years ago
.style('opacity', 1);
12 years ago
mainBar.exit().transition().duration(withTransition ? 250 : 0)
.style('opacity', 0)
11 years ago
.remove();
12 years ago
// lines and cricles
main.selectAll('.-line')
.transition().duration(withTransition ? 250 : 0)
11 years ago
.attr("d", lineOnMain);
mainCircle = main.selectAll('.-circles').selectAll('.-circle')
11 years ago
.data(lineData);
mainCircle.transition().duration(withTransition ? 250 : 0)
.attr("cx", __axis_rotated ? circleY : circleX)
11 years ago
.attr("cy", __axis_rotated ? circleX : circleY);
mainCircle.enter().append("circle")
.attr("class", classCircle)
.attr("cx", __axis_rotated ? circleY : circleX)
.attr("cy", __axis_rotated ? circleX : circleY)
11 years ago
.attr("r", __point_r);
mainCircle.exit().remove();
12 years ago
// subchart
if (withSubchart && __subchart_show) {
// bars
11 years ago
barW = getBarW(subXAxis, barTargetsNum);
barH = getBarH(height2, true);
barX = getBarX(barW, barTargetsNum, barIndices, true);
barY = getBarY(barH, barIndices, false, true);
contextBar = context.selectAll('.-bars').selectAll('.-bar')
11 years ago
.data(barData);
12 years ago
contextBar.transition().duration(withTransition ? 250 : 0)
11 years ago
.attr("x", barX).attr("y", barY).attr("width", barW).attr("height", barH);
contextBar.enter().append('rect')
.attr("class", classBar)
.attr("x", barX).attr("y", barY).attr("width", barW).attr("height", barH)
.style("opacity", 0)
.transition()
11 years ago
.style('opacity', 1);
contextBar.exit().transition()
.style('opacity', 0)
11 years ago
.remove();
// lines
context.selectAll('.-line')
.transition().duration(withTransition ? 250 : 0)
11 years ago
.attr("d", lineOnSub);
12 years ago
}
12 years ago
12 years ago
// circles for select
main.selectAll('.selected-circles')
.filter(function(d){ return isBarType(d); })
.selectAll('circle')
11 years ago
.remove();
12 years ago
main.selectAll('.selected-circle')
.transition().duration(withTransition ? 250 : 0)
.attr("cx", __axis_rotated ? circleY : circleX)
11 years ago
.attr("cy", __axis_rotated ? circleX : circleY);
12 years ago
12 years ago
// rect for mouseover
11 years ago
rectW = (((__axis_rotated ? height : width)*getXDomainRatio())/(maxDataCount()-1));
rectX = function(d){ return x(d.x)-(rectW/2); };
main.selectAll('.event-rect')
.attr("x", __axis_rotated ? 0 : rectX)
.attr("y", __axis_rotated ? rectX : 0)
.attr("width", __axis_rotated ? width : rectW)
11 years ago
.attr("height", __axis_rotated ? rectW : height);
// rect for regions
11 years ago
mainRegion = main.select('.regions').selectAll('rect.region')
11 years ago
.data(__regions);
mainRegion.enter().append('rect');
11 years ago
mainRegion
.attr('class', classRegion)
.attr("x", __axis_rotated ? 0 : regionStart)
.attr("y", __axis_rotated ? regionStart : margin.top)
.attr("width", __axis_rotated ? width : regionWidth)
.attr("height", __axis_rotated ? regionWidth : height)
11 years ago
.style("fill-opacity", function(d){ return isDefined(d.opacity) ? d.opacity : .1; });
mainRegion.exit().transition().duration(withTransition ? 250 : 0)
.style("fill-opacity", 0)
11 years ago
.remove();
12 years ago
}
function redrawForBrush() {
redraw({
withTransition: false,
withY: false,
withSubchart: false
});
}
12 years ago
function updateTargets (targets) {
11 years ago
var mainLineEnter, mainLineUpdate, mainBarEnter, mainBarUpdate;
var contextLineEnter, contextLineUpdate, contextBarEnter, contextBarUpdate;
12 years ago
/*-- Main --*/
//-- Bar --//
mainBarUpdate = main.select('.chart-bars')
.selectAll('.chart-bar')
11 years ago
.data(targets);
mainBarEnter = mainBarUpdate.enter().append('g')
11 years ago
.attr('class', function(d){ return 'chart-bar target target-' + d.id; })
12 years ago
.style("pointer-events", "none")
11 years ago
.style('opacity', 0);
// Bars for each data
mainBarEnter.append('g')
.attr("class", classBars)
11 years ago
.style("fill", function(d){ return color(d.id); })
.style("stroke", function(d){ return color(d.id); })
.style("stroke-width", 0)
11 years ago
.style("cursor", function(d){ return __data_selection_isselectable(d) ? "pointer" : null; });
12 years ago
//-- Line --//
mainLineUpdate = main.select('.chart-lines')
.selectAll('.chart-line')
11 years ago
.data(targets);
mainLineEnter = mainLineUpdate.enter().append('g')
11 years ago
.attr('class', function(d){ return 'chart-line target target-' + d.id; })
.style("pointer-events", "none")
11 years ago
.style('opacity', 0);
12 years ago
// Lines for each data
mainLineEnter.append("path")
.attr("class", classLine)
11 years ago
.style("stroke", function(d){ return color(d.id); });
12 years ago
// Circles for each data point on lines
mainLineEnter.append('g')
11 years ago
.attr("class", function(d){ return "selected-circles selected-circles-" + d.id; });
mainLineEnter.append('g')
.attr("class", classCircles)
11 years ago
.style("fill", function(d){ return color(d.id); })
.style("cursor", function(d){ return __data_selection_isselectable(d) ? "pointer" : null; });
// Update date for selected circles
targets.forEach(function(t){
main.selectAll('.selected-circles-'+t.id).selectAll('.selected-circle').each(function(d){
11 years ago
d.value = t.values[d.x].value;
});
});
12 years ago
12 years ago
/*-- Context --*/
if (__subchart_show) {
contextBarUpdate = context.select('.chart-bars')
.selectAll('.chart-bar')
11 years ago
.data(targets);
contextBarEnter = contextBarUpdate.enter().append('g')
11 years ago
.attr('class', function(d){ return 'chart-bar target target-' + d.id; })
.style('opacity', 0);
// Bars for each data
contextBarEnter.append('g')
.attr("class", classBars)
11 years ago
.style("fill", function(d){ return color(d.id); });
12 years ago
//-- Line --//
contextLineUpdate = context.select('.chart-lines')
.selectAll('.chart-line')
11 years ago
.data(targets);
contextLineEnter = contextLineUpdate.enter().append('g')
11 years ago
.attr('class', function(d){ return 'chart-line target target-' + d.id; })
.style('opacity', 0);
12 years ago
// Lines for each data
contextLineEnter.append("path")
.attr("class", classLine)
11 years ago
.style("stroke", function(d) { return color(d.id); });
12 years ago
}
/*-- Legend --*/
if (__legend_show) {
11 years ago
updateLegend(targets);
12 years ago
}
/*-- Show --*/
// Fade-in each chart
d3.selectAll('.target')
.transition()
11 years ago
.style("opacity", 1);
12 years ago
}
12 years ago
12 years ago
function load (targets, done) {
12 years ago
// Update/Add data
12 years ago
c3.data.targets.forEach(function(d){
12 years ago
for (var i = 0; i < targets.length; i++) {
if (d.id === targets[i].id) {
11 years ago
d.values = targets[i].values;
targets.splice(i,1);
break;
12 years ago
}
}
11 years ago
});
c3.data.targets = c3.data.targets.concat(targets); // add remained
12 years ago
// Set targets
11 years ago
updateTargets(c3.data.targets);
12 years ago
// Redraw with new targets
redraw();
12 years ago
11 years ago
done();
12 years ago
}
12 years ago
12 years ago
/*-- Draw Legend --*/
function updateLegend (targets) {
11 years ago
var ids = getTargetIds(targets), l;
var padding = width/2 - __legend_item_width*Object.keys(targets).length/2;
12 years ago
// Define g for legend area
12 years ago
l = legend.selectAll('.legend-item')
12 years ago
.data(ids)
.enter().append('g')
11 years ago
.attr('class', function(d){ return 'legend-item legend-item-' + d; })
12 years ago
.style('cursor', 'pointer')
.on('click', function(d){
11 years ago
__legend_item_onclick(d);
12 years ago
})
.on('mouseover', function(d){
11 years ago
d3.selectAll('.legend-item').filter(function(_d){ return _d !== d; })
12 years ago
.transition().duration(100)
11 years ago
.style('opacity', 0.3);
c3.focus(d);
12 years ago
})
.on('mouseout', function(d){
d3.selectAll('.legend-item')
.transition().duration(100)
11 years ago
.style('opacity', 1);
c3.revert();
});
12 years ago
l.append('rect')
.attr("class", "legend-item-event")
12 years ago
.style('fill-opacity', 0)
12 years ago
.attr('x', -200)
11 years ago
.attr('y', function(){ return legendHeight/2 - 16; })
12 years ago
.attr('width', __legend_item_width)
11 years ago
.attr('height', 24);
12 years ago
l.append('rect')
.attr("class", "legend-item-tile")
11 years ago
.style('fill', function(d){ return color(d); })
12 years ago
.attr('x', -200)
11 years ago
.attr('y', function(){ return legendHeight/2 - 9; })
12 years ago
.attr('width', 10)
11 years ago
.attr('height', 10);
12 years ago
l.append('text')
.text(function(d){ return isDefined(__data_names[d]) ? __data_names[d] : d; })
12 years ago
.attr('x', -200)
11 years ago
.attr('y', function(d,i){ return legendHeight/2; });
12 years ago
legend.selectAll('rect.legend-item-event')
.data(ids)
.transition()
11 years ago
.attr('x', function(d,i){ return padding + __legend_item_width*i; });
12 years ago
legend.selectAll('rect.legend-item-tile')
.data(ids)
.transition()
11 years ago
.attr('x', function(d,i){ return padding + __legend_item_width*i; });
12 years ago
legend.selectAll('text')
.data(ids)
.transition()
11 years ago
.attr('x', function(d,i){ return padding + __legend_item_width*i + 14; });
12 years ago
}
12 years ago
12 years ago
/*-- Event Handling --*/
function getTargetSelector (target) {
11 years ago
return isDefined(target) ? '.target-' + target : '.target';
12 years ago
}
12 years ago
12 years ago
c3.focus = function (target) {
11 years ago
c3.defocus();
12 years ago
d3.selectAll(getTargetSelector(target))
11 years ago
.filter(function(d){ return hasTarget(d.id); })
12 years ago
.classed('focused', true)
.transition().duration(100)
11 years ago
.style('opacity', 1);
};
12 years ago
12 years ago
c3.defocus = function (target) {
12 years ago
d3.selectAll(getTargetSelector(target))
11 years ago
.filter(function(d){ return hasTarget(d.id); })
12 years ago
.classed('focused', false)
.transition().duration(100)
11 years ago
.style('opacity', 0.3);
};
12 years ago
12 years ago
c3.revert = function (target) {
12 years ago
d3.selectAll(getTargetSelector(target))
11 years ago
.filter(function(d){ return hasTarget(d.id); })
12 years ago
.classed('focused', false)
.transition().duration(100)
11 years ago
.style('opacity', 1);
};
12 years ago
12 years ago
c3.show = function (target) {
12 years ago
d3.selectAll(getTargetSelector(target))
.transition()
11 years ago
.style('opacity', 1);
};
12 years ago
12 years ago
c3.hide = function (target) {
12 years ago
d3.selectAll(getTargetSelector(target))
.transition()
11 years ago
.style('opacity', 0);
};
12 years ago
12 years ago
c3.load = function (args) {
12 years ago
// check args
if (isUndefined(args.done)) {
11 years ago
args.done = function() {};
12 years ago
}
// use cache if exists
12 years ago
if ('cacheIds' in args && hasCaches(args.cacheIds)) {
11 years ago
load(getCaches(args.cacheIds), args.done);
return;
12 years ago
}
// load data
if ('data' in args) {
11 years ago
load(convertDataToTargets(data), args.done);
12 years ago
}
else if ('url' in args) {
d3.csv(args.url, function(error, data){
11 years ago
load(convertDataToTargets(data), args.done);
});
12 years ago
}
else if ('rows' in args) {
11 years ago
load(convertDataToTargets(convertRowsToData(args.rows)), args.done);
12 years ago
}
else if ('columns' in args) {
11 years ago
load(convertDataToTargets(convertColumnsToData(args.columns)), args.done);
12 years ago
}
else {
11 years ago
throw Error('url or rows or columns is required.');
12 years ago
}
11 years ago
};
12 years ago
12 years ago
c3.unload = function (target) {
c3.data.targets = c3.data.targets.filter(function(d){
11 years ago
return d.id != target;
});
12 years ago
d3.selectAll('.target-'+target)
.transition()
.style('opacity', 0)
11 years ago
.remove();
12 years ago
if (__legend_show) {
11 years ago
d3.selectAll('.legend-item-'+target).remove();
updateLegend(c3.data.targets);
12 years ago
}
if (c3.data.targets.length > 0) redraw();
11 years ago
};
12 years ago
12 years ago
c3.selected = function (target) {
11 years ago
var suffix = isDefined(target) ? '-' + target : '';
12 years ago
return d3.merge(
main.selectAll('.-shapes' + suffix).selectAll('.-shape')
.filter(function(){ return d3.select(this).classed(SELECTED); })
11 years ago
.map(function(d){ return d.map(function(_d){ return _d.__data__; }); })
);
};
12 years ago
c3.select = function (ids, indices, resetOther) {
11 years ago
if ( ! __data_selection_enabled) return;
main.selectAll('.-shapes').selectAll('.-shape').each(function(d,i){
var selectShape = (this.nodeName === 'circle') ? selectPoint : selectBar,
11 years ago
unselectShape = (this.nodeName === 'circle') ? unselectPoint : unselectBar;
12 years ago
if (indices.indexOf(i) >= 0) {
if (__data_selection_isselectable(d) && (__data_selection_grouped || isUndefined(ids) || ids.indexOf(d.id) >= 0)) {
selectShape(d3.select(this).classed(SELECTED,true), d, i);
12 years ago
}
} else if (isDefined(resetOther) && resetOther) {
unselectShape(d3.select(this).classed(SELECTED,false), d, i);
12 years ago
}
11 years ago
});
};
12 years ago
c3.unselect = function (ids, indices) {
11 years ago
if ( ! __data_selection_enabled) return;
main.selectAll('.-shapes').selectAll('.-shape').each(function(d,i){
11 years ago
var unselectShape = (this.nodeName === 'circle') ? unselectPoint : unselectBar;
if (isUndefined(indices) || indices.indexOf(i) >= 0) {
if (__data_selection_isselectable(d) && (__data_selection_grouped || isUndefined(ids) || ids.indexOf(d.id) >= 0)) {
unselectShape(d3.select(this).classed(SELECTED,false), d, i);
12 years ago
}
}
11 years ago
});
};
12 years ago
c3.toLine = function (targets) {
11 years ago
setTargetType(targets, 'line');
redraw();
11 years ago
};
12 years ago
c3.toSpline = function (targets) {
11 years ago
setTargetType(targets, 'spline');
redraw();
11 years ago
};
12 years ago
c3.toBar = function (targets) {
11 years ago
setTargetType(targets, 'bar');
redraw();
11 years ago
};
c3.groups = function (groups) {
11 years ago
if (isUndefined(groups)) return __data_groups;
__data_groups = groups;
redraw();
11 years ago
return __data_groups;
};
c3.regions = function (regions) {
11 years ago
if (isUndefined(regions)) return __regions;
__regions = regions;
redraw();
11 years ago
return __regions;
};
11 years ago
c3.regions.add = function (regions) {
11 years ago
if (isUndefined(regions)) return __regions;
__regions = __regions.concat(regions);
redraw();
11 years ago
return __regions;
};
11 years ago
c3.regions.remove = function (classes, options) {
var regionClasses = [].concat(classes),
11 years ago
options = isDefined(options) ? options : {};
11 years ago
regionClasses.forEach(function(cls){
11 years ago
var regions = d3.selectAll('.'+cls);
if (isDefined(options.duration)) {
11 years ago
regions = regions.transition().duration(options.duration).style('fill-opacity', 0);
}
11 years ago
regions.remove();
__regions = __regions.filter(function(region){
11 years ago
return region.classes.indexOf(cls) < 0;
});
});
return __regions;
};
c3.data.get = function (id) {
11 years ago
var target = c3.data.getAsTarget(id);
return isDefined(target) ? target.values.map(function(d){ return d.value; }) : undefined;
};
c3.data.getAsTarget = function (id) {
11 years ago
var targets = getTargets(function(d){ return d.id == id; });
return targets.length > 0 ? targets[0] : undefined;
};
12 years ago
/*-- Load data and init chart with defined functions --*/
12 years ago
if ('url' in config.data) {
11 years ago
d3.csv(config.data.url, function(error, data) { init(data) });
12 years ago
}
else if ('rows' in config.data) {
11 years ago
init(convertRowsToData(config.data.rows));
12 years ago
}
else if ('columns' in config.data) {
11 years ago
init(convertColumnsToData(config.data.columns));
12 years ago
}
else {
11 years ago
throw Error('url or rows or columns is required.');
12 years ago
}
11 years ago
return c3;
12 years ago
}
12 years ago
12 years ago
function categoryAxis () {
11 years ago
var scale = d3.scale.linear(), orient = "bottom", tickMajorSize = 6, tickMinorSize = 6, tickEndSize = 6, tickPadding = 3, tickCentered = false, tickTextNum = 10, tickOffset = 0, categories = [];
12 years ago
function axisX (selection, x) {
selection.attr("transform", function(d){
11 years ago
return "translate(" + (x(d) + tickOffset) + ",0)";
});
12 years ago
}
12 years ago
function axisY (selection, y) {
selection.attr("transform", function(d){
11 years ago
return "translate(0," + y(d) + ")";
});
12 years ago
}
12 years ago
function scaleExtent (domain) {
11 years ago
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [ start, stop ] : [ stop, start ];
12 years ago
}
12 years ago
function generateTicks (domain) {
11 years ago
var ticks = [];
12 years ago
for (var i = Math.ceil(domain[0]); i < domain[1]; i++) {
11 years ago
ticks.push(i);
12 years ago
}
if (ticks.length > 0 && ticks[0] > 0) {
11 years ago
ticks.unshift(ticks[0] - (ticks[1]-ticks[0]));
12 years ago
}
11 years ago
return ticks;
12 years ago
}
12 years ago
function shouldShowTickText (ticks, i) {
11 years ago
return ticks.length < tickTextNum || i % Math.ceil(ticks.length / tickTextNum) == 0;
12 years ago
}
12 years ago
function category (i) {
11 years ago
return i < categories.length ? categories[i] : i;
12 years ago
}
function axis(g) {
g.each(function() {
11 years ago
var g = d3.select(this);
var ticks = generateTicks(scale.domain());
var tick = g.selectAll(".tick.major").data(ticks, String), tickEnter = tick.enter().insert("g", "path").attr("class", "tick major").style("opacity", 1e-6), tickExit = d3.transition(tick.exit()).style("opacity", 1e-6).remove(), tickUpdate = d3.transition(tick).style("opacity", 1), tickTransform, tickX;
var range = scale.rangeExtent ? scale.rangeExtent() : scaleExtent(scale.range()), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), d3.transition(path));
var scale1 = scale.copy(), scale0 = this.__chart__ || scale1;
this.__chart__ = scale1;
tickEnter.append("line");
tickEnter.append("text");
var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text"), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text");
tickOffset = (scale1(1)-scale1(0))/2;
tickX = tickCentered ? 0 : tickOffset;
12 years ago
switch (orient) {
case "bottom":
{
11 years ago
tickTransform = axisX;
lineEnter.attr("y2", tickMajorSize);
textEnter.attr("y", Math.max(tickMajorSize, 0) + tickPadding);
lineUpdate.attr("x1", tickX).attr("x2", tickX).attr("y2", tickMajorSize);
textUpdate.attr("x", 0).attr("y", Math.max(tickMajorSize, 0) + tickPadding);
text.attr("dy", ".71em").style("text-anchor", "middle");
text.text(function(i){ return shouldShowTickText(ticks, i) ? category(i) : ""; });
pathUpdate.attr("d", "M" + range[0] + "," + tickEndSize + "V0H" + range[1] + "V" + tickEndSize);
break;
12 years ago
}
/* TODO: implement
case "top":
{
12 years ago
tickTransform = axisX
lineEnter.attr("y2", -tickMajorSize)
textEnter.attr("y", -(Math.max(tickMajorSize, 0) + tickPadding))
lineUpdate.attr("x2", 0).attr("y2", -tickMajorSize)
textUpdate.attr("x", 0).attr("y", -(Math.max(tickMajorSize, 0) + tickPadding))
text.attr("dy", "0em").style("text-anchor", "middle")
pathUpdate.attr("d", "M" + range[0] + "," + -tickEndSize + "V0H" + range[1] + "V" + -tickEndSize)
break
12 years ago
}
*/
12 years ago
case "left":
{
11 years ago
tickTransform = axisY;
lineEnter.attr("x2", -tickMajorSize);
textEnter.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding));
lineUpdate.attr("x2", -tickMajorSize).attr("y2", 0);
textUpdate.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding)).attr("y", tickOffset);
text.attr("dy", ".32em").style("text-anchor", "end");
text.text(function(i){ return shouldShowTickText(ticks, i) ? category(i) : ""; });
pathUpdate.attr("d", "M" + -tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + -tickEndSize);
break;
12 years ago
}
/*
12 years ago
case "right":
{
12 years ago
tickTransform = axisY
lineEnter.attr("x2", tickMajorSize)
textEnter.attr("x", Math.max(tickMajorSize, 0) + tickPadding)
lineUpdate.attr("x2", tickMajorSize).attr("y2", 0)
textUpdate.attr("x", Math.max(tickMajorSize, 0) + tickPadding).attr("y", 0)
text.attr("dy", ".32em").style("text-anchor", "start")
pathUpdate.attr("d", "M" + tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + tickEndSize)
break
12 years ago
}
*/
}
if (scale.ticks) {
11 years ago
tickEnter.call(tickTransform, scale0);
tickUpdate.call(tickTransform, scale1);
tickExit.call(tickTransform, scale1);
12 years ago
} else {
var dx = scale1.rangeBand() / 2, x = function(d) {
11 years ago
return scale1(d) + dx;
};
tickEnter.call(tickTransform, x);
tickUpdate.call(tickTransform, x);
12 years ago
}
11 years ago
});
12 years ago
}
axis.scale = function(x) {
11 years ago
if (!arguments.length) return scale;
scale = x;
return axis;
12 years ago
}
12 years ago
axis.orient = function(x) {
11 years ago
if (!arguments.length) return orient;
orient = x in {top:1,right:1,bottom:1,left:1} ? x + "" : "bottom";
return axis;
12 years ago
}
12 years ago
axis.categories = function(x) {
11 years ago
if (!arguments.length) return categories;
categories = x;
return axis;
12 years ago
}
12 years ago
axis.tickCentered = function(x) {
11 years ago
if (!arguments.length) return tickCentered;
tickCentered = x;
return axis;
12 years ago
}
axis.tickTextNum = function(x) {
11 years ago
if (!arguments.length) return tickTextNum;
tickTextNum = x;
return axis;
}
12 years ago
axis.tickOffset = function() {
11 years ago
return tickOffset;
12 years ago
}
axis.ticks = function() {
return; // TODO: implement
}
11 years ago
return axis;
12 years ago
}
12 years ago
function isUndefined(v) {
11 years ago
return typeof v === 'undefined';
}
function isDefined(v) {
11 years ago
return typeof v !== 'undefined';
}
11 years ago
})(window);