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.

1521 lines
63 KiB

12 years ago
(function (window) {
12 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 : {} },
12 years ago
cache = {}
12 years ago
/*-- Handle Config --*/
12 years ago
function checkConfig (key, message) {
12 years ago
if ( ! (key in config)) throw Error(message)
}
12 years ago
12 years ago
function getConfig (keys, defaultValue) {
12 years ago
var target = config
12 years ago
for (var i = 0; i < keys.length; i++) {
12 years ago
if ( ! (keys[i] in target)) return defaultValue
target = target[keys[i]]
12 years ago
}
12 years ago
return target
}
12 years ago
// bindto - id to bind the chart
12 years ago
checkConfig('bindto', 'bindto is required in config')
12 years ago
12 years ago
var __size_width = getConfig(['size','width'], 640),
12 years ago
__size_height = getConfig(['size','height'], 480)
12 years ago
// data - data configuration
12 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_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),
__data_selection_isselectable = getConfig(['data','selection','isselectable'], function(d){return true})
12 years ago
// subchart
12 years ago
var __subchart_show = getConfig(['subchart','show'], true),
__subchart_size_height = __subchart_show ? getConfig(['subchart','size','height'], 60) : 0,
12 years ago
__subchart_default = getConfig(['subchart','default'], null)
12 years ago
// color
12 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
12 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'),
__axis_x_categories = getConfig(['axis','x','categories'], ['hoge']),
__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),
12 years ago
__axis_y_rescale = getConfig(['axis','y','rescale'], true)
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'),
12 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'], false),
__point_focus_expand_enabled = getConfig(['point','focus','expand','enabled'], __point_show),
__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(){}),
12 years ago
__point_onunselected = getConfig(['point','onunselected'], function(){})
12 years ago
// region - region to change style
12 years ago
var __regions = getConfig(['regions'], null)
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,
12 years ago
text = "<table class='tooltip'><tr><th colspan='2'>" + date + "</th></tr>"
12 years ago
for (var i = 0; i < d.length; i++){
12 years ago
var value = (typeof d[i].value !== 'undefined') ? (Math.round(d[i].value*100)/100).toFixed(2) : '-'
text += "<tr><td>" + d[i].name + "</td><td class='value'>" + value + "</td></tr>"
12 years ago
}
12 years ago
return text + "</table>"
})
12 years ago
12 years ago
/*-- Set Variables --*/
var clipId = config.bindto.replace('#','') + '-clip',
12 years ago
clipPath = "url(#" + clipId + ")"
12 years ago
var isTimeSeries = (__axis_x_type === 'timeseries'),
12 years ago
isCategorized = (__axis_x_type === 'categorized')
12 years ago
12 years ago
var dragStart = null, dragging = false
12 years ago
12 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() }]
])
12 years ago
function timeFormat(formats) {
return function(date) {
12 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 margin_bottom = 20 + __subchart_size_height + legendHeight,
margin2_top = __size_height - __subchart_size_height - legendHeight,
margin2_bottom = 20 + legendHeight,
margin3_top = __size_height - legendHeight,
margin = {top: 10, right: 20, bottom: margin_bottom, left: 40},
margin2 = {top: margin2_top, right: 20, bottom: margin2_bottom, left: 40},
margin3 = {top: margin3_top, right: 20, bottom: 0, left: 40},
width = __size_width - margin.left - margin.right,
height = __size_height - margin.top - margin.bottom,
12 years ago
height2 = __size_height - margin2.top - margin2.bottom,
height3 = __size_height - margin3.top - margin3.bottom
12 years ago
12 years ago
var parseDate = d3.time.format(__data_x_format).parse
12 years ago
var x = ((isTimeSeries) ? d3.time.scale() : d3.scale.linear()).range([0, width]),
x2 = ((isTimeSeries) ? d3.time.scale() : d3.scale.linear()).range([0, width]),
y = d3.scale.linear().range([height, 10]),
12 years ago
y2 = d3.scale.linear().range([height2, 10])
12 years ago
// TODO: Enable set position
var xAxis = isCategorized ? categoryAxis() : d3.svg.axis(),
xAxis2 = isCategorized ? categoryAxis() : d3.svg.axis(),
12 years ago
yAxis = d3.svg.axis()
12 years ago
12 years ago
xAxis.scale(x).orient("bottom")
xAxis2.scale(x2).orient("bottom")
yAxis.scale(y).orient("left")
12 years ago
if (isTimeSeries) {
12 years ago
xAxis.tickFormat(customTimeFormat)
// TODO: fix
xAxis.tickOffset = function () {
12 years ago
return 0
};
// TODO: fix
xAxis2.tickOffset = function () {
12 years ago
return 0
}
}
12 years ago
if (isCategorized) {
12 years ago
xAxis.categories(__axis_x_categories).tickCentered(__axis_x_tick_centered)
xAxis2.categories(__axis_x_categories).tickCentered(__axis_x_tick_centered)
12 years ago
}
// Use custom scale if needed
if (isCategorized) {
12 years ago
// TODO: fix this
// TODO: fix x_grid
(function () {
12 years ago
var _x = x, _x2 = x2
var keys = Object.keys(x), key, i
x = function(d){ return _x(d) + xAxis.tickOffset() }
x2 = function(d){ return _x2(d) + xAxis2.tickOffset() }
12 years ago
for (i = 0; i < keys.length; i++) {
12 years ago
key = keys[i]
x[key] = _x[key]
x2[key] = _x2[key]
12 years ago
}
12 years ago
x.domain = function (domain) {
if (!arguments.length) {
12 years ago
var domain = _x.domain()
domain[1]++
return domain
12 years ago
}
12 years ago
_x.domain(domain)
return x
}
})()
12 years ago
}
// For brush region
var line2 = d3.svg.line()
12 years ago
.x(function(d){ return x2(d.x) })
.y(function(d){ return y2(d.value) })
12 years ago
// For region
var regionStart = function (d) {
12 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,
12 years ago
w = end - start
return (w < 0) ? 0 : w
12 years ago
}
// Define color
12 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)
12 years ago
.attr("height", height + margin.top + margin.bottom)
12 years ago
12 years ago
svg.append("defs")
12 years ago
svg.select("defs").append("clipPath")
.attr("id", clipId)
.append("rect")
.attr("width", width)
12 years ago
.attr("height", height)
12 years ago
svg.select("defs").append("clipPath")
.attr("id", "xaxis-clip")
.append("rect")
.attr("x", -1)
.attr("y", -1)
.attr("width", width + 2)
12 years ago
.attr("height", 40)
12 years ago
12 years ago
// Define regions
12 years ago
var main = svg.append("g")
12 years ago
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
var context = null
12 years ago
if (__subchart_show) {
context = svg.append("g")
12 years ago
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")")
12 years ago
}
12 years ago
var legend = null
12 years ago
if (__legend_show) {
legend = svg.append("g")
12 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")
12 years ago
.style("visibility", "hidden")
12 years ago
/*-- Define Functions --*/
12 years ago
//-- Domain --//
function getYDomainMin (targets) {
12 years ago
return (__axis_y_min !== null) ? __axis_y_min : d3.min(targets, function(t) { return d3.min(t.values, function(v) { return v.value }) })
}
12 years ago
function getYDomainMax (targets) {
12 years ago
return (__axis_y_max !== null) ? __axis_y_max : d3.max(targets, function(t) { return d3.max(t.values, function(v) { return v.value }) })
}
12 years ago
function getYDomain (targets) {
var yDomainMin = getYDomainMin(targets),
yDomainMax = getYDomainMax(targets),
12 years ago
padding = Math.abs(yDomainMax - yDomainMin) * 0.1
12 years ago
if (__axis_y_center !== null) {
12 years ago
yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax))
yDomainMax = yDomainAbs - __axis_y_center
yDomainMin = __axis_y_center - yDomainAbs
12 years ago
}
12 years ago
return [yDomainMin-padding, yDomainMax+padding]
}
12 years ago
function getXDomainRatio () {
12 years ago
if (brush.empty()) return 1
var domain = x2.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++){
12 years ago
if ( ! (ids[i] in cache)) return false
12 years ago
}
12 years ago
return true
12 years ago
}
12 years ago
function addCache (id, target) {
12 years ago
cache[id] = target
12 years ago
}
12 years ago
function getCaches (ids) {
12 years ago
var targets = []
12 years ago
for (var i = 0; i < ids.length; i++){
12 years ago
if (ids[i] in cache) targets.push(cache[ids[i]])
12 years ago
}
12 years ago
return targets
12 years ago
}
12 years ago
//-- Data --//
function convertRowsToData (rows) {
12 years ago
var keys = rows[0], new_row = {}, new_rows = [], i, j
for (i = 1; i < rows.length; i++) {
12 years ago
new_row = {}
12 years ago
for (j = 0; j < rows[i].length; j++) {
12 years ago
new_row[keys[j]] = rows[i][j]
}
12 years ago
new_rows.push(new_row)
12 years ago
}
12 years ago
return new_rows
}
12 years ago
function convertColumnsToData (columns) {
12 years ago
var new_rows = [], i, j, key
12 years ago
for (i = 0; i < columns.length; i++) {
12 years ago
key = columns[i][0]
12 years ago
for (j = 1; j < columns[i].length; j++) {
12 years ago
if (typeof new_rows[j-1] === 'undefined') {
new_rows[j-1] = {}
}
12 years ago
new_rows[j-1][key] = columns[i][j]
12 years ago
}
}
12 years ago
return new_rows
}
12 years ago
function convertDataToTargets (data) {
12 years ago
var ids = d3.keys(data[0]).filter(function(key){ return key !== __data_x })
12 years ago
var targets, currentTargetsNum = getTargetsNum(), i = 0
12 years ago
data.forEach(function(d) {
12 years ago
d.x = (isTimeSeries) ? parseDate(d[__data_x]) : i++
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) {
12 years ago
var convertedId = __data_id_converter(id)
12 years ago
return {
id : convertedId,
id_org : id,
values : data.map(function(d) {
12 years ago
return {x: d.x, value: +d[id], id: convertedId, i: currentTargetsNum + i}
12 years ago
})
12 years ago
}
})
12 years ago
// cache as original id keyed
targets.forEach(function(d){
12 years ago
addCache(d.id_org, d)
})
12 years ago
12 years ago
return targets
12 years ago
}
12 years ago
function maxDataCount () {
12 years ago
return d3.max(c3.data.targets, function(t){ return t.values.length })
12 years ago
}
function hasTarget (id) {
12 years ago
var ids = c3.data.targets.map(function(d){ return d.id }), i
12 years ago
for (i = 0; i < ids.length; i++) {
12 years ago
if (ids[i] === id) return true
}
12 years ago
return false
}
function getTargetsNum (filter) {
12 years ago
if (typeof c3.data.targets === 'undefined') return 0
return typeof filter !== 'undefined' ? c3.data.targets.filter(filter).length : c3.data.targets.length;
}
function getBarTargetIndices () {
var indices = []
c3.data.targets.forEach(function(d,i) {
if (isBarType(d)) {
indices.push(i)
}
})
return indices
}
function getBarX (barWidth, barTargetsNum, barIndices) {
return function (d) {
return x(d.x) - barWidth * (barTargetsNum/2 - barIndices.indexOf(d.i))
}
}
function isLineType (d) {
12 years ago
var id = (typeof d === 'string') ? d : d.id
return !(id in __data_types) || __data_types[id] === 'line'
12 years ago
}
function isBarType (d) {
12 years ago
var id = (typeof d === 'string') ? d : d.id
return __data_types[id] === 'bar'
12 years ago
}
function category (i) {
12 years ago
return i < __axis_x_categories.length ? __axis_x_categories[i] : i
12 years ago
}
12 years ago
//-- Color --//
function generateColor (_colors, _pattern) {
var ids = [],
colors = _colors,
12 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
12 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)) {
12 years ago
ids.push(id)
12 years ago
}
12 years ago
return pattern[ids.indexOf(id) % pattern.length]
12 years ago
}
12 years ago
}
12 years ago
//-- Util --//
12 years ago
function isWithinCircle (_this, _r) {
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
}
function isWithinBar (_this) {
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) {
12 years ago
var i
12 years ago
for (i = 0; i < regions.length; i++) {
12 years ago
if (regions[i].start < x && x <= regions[i].end) return true
12 years ago
}
12 years ago
return false
12 years ago
}
12 years ago
12 years ago
//-- Selection --//
function selectPoint (target, d, i) {
12 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')
12 years ago
.attr("class", function(d){ return "selected-circle selected-circle-" + i })
.attr("cx", function(d){ return x(d.x) })
.attr("cy", function(d){ return y(d.value) })
.attr("stroke", function(){ return color(d.id) })
12 years ago
.attr("r", __point_select_r * 1.4)
.transition().duration(100)
12 years ago
.attr("r", __point_select_r)
}
12 years ago
function unselectPoint (target, d, i) {
12 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)
12 years ago
.remove()
}
12 years ago
function togglePoint (selected, target, d, i) {
12 years ago
(selected) ? selectPoint(target, d, i) : unselectPoint(target, d, i)
}
12 years ago
function selectBar (target, d, i) {
target.transition().duration(100)
.style("fill-opacity", 0.4)
.style("stroke-width", "1px")
}
function unselectBar (target, d, i) {
target.transition().duration(100)
.style("fill-opacity", 1)
.style("stroke-width", target.classed("_e_") ? "4px" : null)
.each('end', function(){ target.transition().style("stroke-width", null) })
}
function toggleBar (selected, target, d, i) {
(selected) ? selectBar(target, d, i) : unselectBar(target, d, i)
}
12 years ago
//-- Shape --//
12 years ago
12 years ago
function lineWithRegions (d, regions) {
12 years ago
var prev = -1, i, j
var s = "M"
var xp, yp, dx, dy, dd, diff, diff2
12 years ago
// Check start/end of regions
if (typeof regions !== 'undefined') {
12 years ago
for (i = 0; i < regions.length; i++){
12 years ago
if (typeof regions[i].start === 'undefined') {
12 years ago
regions[i].start = d[0].x
12 years ago
}
if (typeof regions[i].end === 'undefined') {
12 years ago
regions[i].end = d[d.length-1].x
12 years ago
}
}
}
// Generate
12 years ago
for (i = 0; i < d.length; i++) {
12 years ago
// Draw as normal
12 years ago
if (typeof regions === 'undefined' || ! isWithinRegions(d[i].x, regions)) {
12 years ago
s += " "+x(d[i].x)+" "+y(d[i].value)
12 years ago
}
// Draw with region
else {
12 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) {
12 years ago
s += "M"+x(xp(j))+" "+y(yp(j))+" "+x(xp(j+diff))+" "+y(yp(j+diff))
12 years ago
}
}
12 years ago
prev = d[i].x
12 years ago
}
12 years ago
return s
}
12 years ago
12 years ago
/*-- Define brush --*/
12 years ago
12 years ago
var brush = d3.svg.brush().x(x2).on("brush", update)
12 years ago
/*-- Draw Chart --*/
// for brush area culculation
var firstDate = null,
12 years ago
lastDate = null
12 years ago
12 years ago
function init (data) {
12 years ago
var targets = c3.data.targets = convertDataToTargets(data)
var rectWidth
var grid, xgridLine, yGridData
12 years ago
// TODO: set names if names not specified
12 years ago
x.domain(d3.extent(data.map(function(d){ return d.x })))
y.domain(getYDomain(targets))
x2.domain(x.domain())
y2.domain(y.domain())
12 years ago
12 years ago
/*-- Main Region --*/
12 years ago
12 years ago
grid = main.append('g')
12 years ago
.attr("clip-path", clipPath)
12 years ago
.attr('class', 'grid')
12 years ago
// X-Grid
if (__grid_x_show) {
12 years ago
grid.append("g").attr("class", "xgrid")
12 years ago
}
if (__grid_x_lines) {
12 years ago
xgridLine = grid.append('g')
12 years ago
.attr("class", "xgrid-lines")
.selectAll('g.xgrid-line')
.data(__grid_x_lines)
.enter().append('g')
12 years ago
.attr("class", "xgrid-line")
12 years ago
xgridLine.append('line')
12 years ago
.attr("class", function(d){ return "" + d['class'] })
.attr("x1", function(d){ return x(d.value) })
.attr("x2", function(d){ return x(d.value) })
12 years ago
.attr("y1", margin.top)
12 years ago
.attr("y2", height)
12 years ago
xgridLine.append('text')
12 years ago
.attr("class", function(d){ return "" + d['class'] })
.attr('x', function(d){ return x(d.value) })
12 years ago
.attr('y', height-8)
.attr('dx', 6)
12 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", -10)
.attr("x2", -10)
.attr("y1", margin.top)
12 years ago
.attr("y2", height)
12 years ago
}
// Y-Grid
if (__grid_y_show) {
12 years ago
yGridData = y.ticks(10)
12 years ago
grid.append('g')
.attr('class', 'ygrid')
.selectAll("line.ygrid")
.data(yGridData)
.enter().append("line")
.attr("class", "ygrid")
.attr("x1", 0)
.attr("x2", width)
12 years ago
.attr("y1", y)
12 years ago
.attr("y2", y)
12 years ago
}
if (__grid_y_lines) {
grid.append('g')
.attr('class', 'ygrid-lines')
.selectAll('line.y')
.data(__grid_y_lines)
.enter().append('line')
12 years ago
.attr("class", function(d){ return "y " + d['class'] })
12 years ago
.attr("x1", 0)
.attr("x2", width)
12 years ago
.attr("y1", function(d){ return y(d.value) })
.attr("y2", function(d){ return y(d.value) })
12 years ago
}
// Area
if (__regions !== null) {
grid.append('g')
.attr("class", "regions")
.selectAll('rect.region')
.data(__regions)
.enter().append('rect')
12 years ago
.attr('class', function(d,i){ return 'region region-' + i })
12 years ago
.attr("x", regionStart)
.attr("y", margin.top)
.attr("width", regionWidth)
12 years ago
.attr("height", height)
12 years ago
}
// Define g for chart area
main.append('g')
.attr("clip-path", clipPath)
12 years ago
.attr('class', 'chart')
12 years ago
12 years ago
// Cover whole with rects for events
12 years ago
rectWidth = ((width*getXDomainRatio())/(maxDataCount()-1))
12 years ago
main.select('.chart').append("g")
.attr("class", "event-rects")
.style('fill-opacity', 0)
.selectAll(".event-rects")
.data(data)
.enter().append("rect")
12 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 })
.attr("x", function(d){ return x(d.x) - (rectWidth/2) })
.attr("y", function(d){ return 0 })
12 years ago
.attr("width", rectWidth)
12 years ago
.attr("height", height)
.on('mouseover', function(d,i) {
12 years ago
if (dragging) return // do nothing if dragging
12 years ago
var selectedData = c3.data.targets.map(function(d){ return d.values[i] });
12 years ago
var j, newData
12 years ago
// Add id,name to selectedData
12 years ago
for (j = 0; j < selectedData.length; j++) {
12 years ago
selectedData[j].name = __data_names[selectedData[j].id]
12 years ago
}
// Sort selectedData as names order
if (Object.keys(__data_names).length > 0) {
12 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) {
12 years ago
newData.push(selectedData[j])
selectedData.shift(j)
12 years ago
break
12 years ago
}
}
}
selectedData = newData.concat(selectedData) // Add remained
12 years ago
}
// Expand circles if needed
if (__point_focus_expand_enabled) {
main.selectAll('.target-circle-'+i)
.classed("_e_", true)
12 years ago
.attr('r', __point_focus_expand_r)
12 years ago
}
// Expand bars
main.selectAll(".target-bar-"+i)
.classed("_e_", true)
12 years ago
// Show xgrid focus line
main.selectAll('line.xgrid-focus')
.style("visibility","visible")
.data([selectedData[0]])
12 years ago
.attr('x1', function(d){ return x(d.x) })
.attr('x2', function(d){ return x(d.x) })
12 years ago
// Set tooltip
tooltip.style("top", (d3.mouse(this)[1] + 30) + "px")
12 years ago
.style("left", (x(selectedData[0].x) + 60) + "px")
tooltip.html(__tooltip_contents(selectedData))
tooltip.style("visibility", "visible")
12 years ago
})
.on('mouseout', function(d,i) {
main.select('line.xgrid-focus').style("visibility", "hidden")
12 years ago
tooltip.style("visibility", "hidden")
12 years ago
// Undo expanded circles
main.selectAll('.target-circle-'+i)
12 years ago
.filter(function(){ return d3.select(this).classed('_e_') })
12 years ago
.classed("_e_", false)
12 years ago
.attr('r', __point_r)
// Undo expanded bar
main.selectAll(".target-bar-"+i)
.classed("_e_", false)
12 years ago
})
.on('mousemove', function(d,i){
12 years ago
if ( ! __data_selection_enabled || dragging) return
if ( __data_selection_grouped) return // nothing to do when grouped
12 years ago
main.selectAll('.target-circle-'+i+', .target-bar-'+i)
12 years ago
.filter(function(d){ return __data_selection_isselectable(d) })
12 years ago
.each(function(d){
var _this = d3.select(this).classed('_e_', true)
if (this.nodeName === 'circle') _this.attr('r', __point_focus_expand_r)
d3.select('.event-rect-'+i).style('cursor', null)
})
.filter(function(d){
12 years ago
var _this = d3.select(this)
if (this.nodeName === 'circle') {
12 years ago
return isWithinCircle(this, __point_select_r)
}
else if (this.nodeName === 'rect') {
12 years ago
return isWithinBar(this, _this.attr('x'), _this.attr('y'))
}
12 years ago
})
.each(function(d){
12 years ago
var _this = d3.select(this)
12 years ago
if ( ! _this.classed('_e_')) {
_this.classed('_e_', true)
if (this.nodeName === 'circle') _this.attr('r', __point_select_r)
12 years ago
}
12 years ago
d3.select('.event-rect-'+i).style('cursor', 'pointer')
})
12 years ago
})
.on('click', function(d,i) {
main.selectAll('.target-circle-'+i+', .target-bar-'+i).each(function(d){
12 years ago
var _this = d3.select(this),
12 years ago
_selected = _this.classed('_s_')
var isWithin = false, toggle
if (this.nodeName === 'circle') {
12 years ago
isWithin = isWithinCircle(this, __point_select_r*1.5)
toggle = togglePoint
}
else if (this.nodeName === 'rect') {
12 years ago
isWithin = isWithinBar(this)
toggle = toggleBar
}
if (__data_selection_grouped || isWithin) {
12 years ago
if (__data_selection_enabled && __data_selection_isselectable(d)) {
12 years ago
_this.classed('_s_', !_selected)
toggle(!_selected, _this, d, i)
12 years ago
}
__point_onclick(d, _this) // TODO: should be __data_onclick
12 years ago
}
12 years ago
})
12 years ago
})
.call(
d3.behavior.drag().origin(Object).on('drag', function(d){
12 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],
min_x = Math.min(sx,mx),
max_x = Math.max(sx,mx),
min_y = (__data_selection_grouped) ? margin.top : Math.min(sy,my),
12 years ago
max_y = (__data_selection_grouped) ? height : Math.max(sy,my)
12 years ago
main.select('.dragarea')
.attr('x', min_x)
.attr('y', min_y)
.attr('width', max_x-min_x)
12 years ago
.attr('height', max_y-min_y)
12 years ago
main.selectAll('.target-circles').selectAll('.target-circle')
.filter(function(d){ return __data_selection_isselectable(d) })
.each(function(d,i){
var _this = d3.select(this),
_selected = _this.classed('_s_'),
_included = _this.classed('_i_'),
_x = x(d.x), _y = y(d.value),
12 years ago
_within = min_x < _x && _x < max_x && min_y < _y && _y < max_y
12 years ago
if (_within ^ _included) {
12 years ago
_this.classed('_i_', !_included)
12 years ago
// TODO: included/unincluded callback here
12 years ago
_this.classed('_s_', !_selected)
togglePoint(!_selected, _this, d, i)
12 years ago
}
12 years ago
})
main.selectAll('.target-bars').selectAll('.target-bar')
.filter(function(d){ return __data_selection_isselectable(d) })
.each(function(d,i){
var _this = d3.select(this),
_selected = _this.classed('_s_'),
_included = _this.classed('_i_'),
12 years ago
_x = _this.attr("x")*1, _y = _this.attr("y")*1
_w = _this.attr('width')*1,
_within = min_x < _x+_w && _x < max_x && _y < max_y
if (_within ^ _included) {
_this.classed('_i_', !_included)
// TODO: included/unincluded callback here
_this.classed('_s_', !_selected)
toggleBar(!_selected, _this, d, i)
}
})
12 years ago
})
.on('dragstart', function() {
12 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')
12 years ago
.style('opacity', 0.1)
dragging = true
12 years ago
// TODO: add callback here
})
.on('dragend', function() {
12 years ago
if ( ! __data_selection_enabled) return // do nothing if not selectable
12 years ago
main.select('.dragarea')
.transition().duration(100)
.style('opacity', 0)
12 years ago
.remove()
12 years ago
main.selectAll('.target-circle')
12 years ago
.classed('_i_', false)
dragging = false
12 years ago
// TODO: add callback here
})
12 years ago
)
12 years ago
// ATTENTION: This must be called AFTER chart added
// Add Axis
main.append("g")
.attr("class", "x axis")
.attr("clip-path", "url(#xaxis-clip)")
.attr("transform", "translate(0," + height + ")")
12 years ago
.call(xAxis)
12 years ago
main.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("dy", "1.4em")
.attr("dx", "-.8em")
.style("text-anchor", "end")
12 years ago
.text(__axis_y_text)
12 years ago
/*-- Context Region --*/
if (__subchart_show) {
// Define g for chart area
context.append('g')
.attr("clip-path", clipPath)
12 years ago
.attr('class', 'chart')
12 years ago
// ATTENTION: This must be called AFTER chart rendered and BEFORE brush called.
// Update extetn for Brush
if (__subchart_default !== null) {
12 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")
12 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 + ")")
12 years ago
.call(xAxis2)
12 years ago
}
/*-- Legend Region --*/
12 years ago
if (__legend_show) drawLegend(targets)
12 years ago
// Update main chart with settings
12 years ago
update()
12 years ago
12 years ago
// Draw chart for each data
12 years ago
draw(targets)
}
12 years ago
12 years ago
function update (withTransition) {
12 years ago
var xgrid, xgridData, xgridLine
var mainPath, mainCircle, mainBar, contextPath
var barTargetsNum = getTargetsNum(isBarType), barWidth, barIndices, barX
var rectWidth
12 years ago
12 years ago
x.domain(brush.empty() ? x2.domain() : brush.extent())
12 years ago
12 years ago
// ticks for x-axis
// ATTENTION: call here to update tickOffset
12 years ago
main.selectAll(".x.axis").call(xAxis)
12 years ago
12 years ago
// grid
if (__grid_x_show) {
if (__grid_x_type === 'year') {
12 years ago
xgridData = []
firstYear = firstDate.getFullYear()
lastYear = lastDate.getFullYear()
12 years ago
for (var year = firstYear; year <= lastYear; year++) {
12 years ago
xgridData.push(new Date(year + '-01-01 00:00:00'))
12 years ago
}
} else {
12 years ago
xgridData = x.ticks(10)
12 years ago
}
12 years ago
12 years ago
xgrid = main.select('g.xgrid').selectAll("line.xgrid")
12 years ago
.data(xgridData)
12 years ago
// Enter
12 years ago
xgrid.enter().append('line').attr("class", "xgrid")
12 years ago
// Exit
12 years ago
xgrid.exit().remove()
12 years ago
// Update
main.selectAll("line.xgrid")
.attr("class", "xgrid")
.attr("x1", x)
.attr("x2", x)
.attr("y1", margin.top)
12 years ago
.attr("y2", height)
12 years ago
}
if (__grid_x_lines) {
12 years ago
xgridLine = main.selectAll("g.xgrid-line")
12 years ago
xgridLine.selectAll('line')
12 years ago
.attr("x1", function(d){ return x(d.value) })
.attr("x2", function(d){ return x(d.value) })
12 years ago
xgridLine.selectAll('text')
12 years ago
.attr("x", function(d){ return x(d.value) })
12 years ago
}
12 years ago
12 years ago
// lines and cricles
12 years ago
mainPath = main.selectAll('.target').selectAll('.target-line').filter(isLineType)
if (withTransition) mainPath = mainPath.transition()
mainPath.attr("d", function(d){ return lineWithRegions(d.values, __data_regions[d.id]) })
mainCircle = main.selectAll('.target').selectAll('.target-circle').filter(isLineType)
if (withTransition) mainCircle = mainCircle.transition()
mainCircle.attr("cx", function(d) { return x(d.x) })
.attr("cy", function(d) { return y(d.value) })
12 years ago
12 years ago
// bars
barWidth = (xAxis.tickOffset()*2*0.6) / barTargetsNum
barIndices = getBarTargetIndices()
barX = getBarX(barWidth, barTargetsNum, barIndices)
12 years ago
mainBar = main.selectAll('.target').selectAll('.target-bar').filter(isBarType)
if (withTransition) mainBar = mainBar.transition()
12 years ago
mainBar.attr("width", barWidth)
.attr("x", barX)
12 years ago
12 years ago
// subchart
12 years ago
if (__subchart_show) {
12 years ago
contextPath = context.selectAll('.target').selectAll('path').filter(isLineType)
if (withTransition) contextPath = contextPath.transition()
contextPath.attr("d", function(d){ return line2(d.values) })
12 years ago
}
12 years ago
12 years ago
// circles for select
main.selectAll('.selected-circle')
12 years ago
.attr("cx", function(d) { return x(d.x) })
.attr("cy", function(d) { return y(d.value) })
12 years ago
12 years ago
// rect for mouseover
12 years ago
rectWidth = ((width*getXDomainRatio())/(maxDataCount()-1))
12 years ago
main.selectAll('rect.event-rect')
12 years ago
.attr("width", rectWidth)
12 years ago
.attr("x", function(d) { return x(d.x) - (rectWidth/2) })
12 years ago
main.selectAll('rect.region')
.attr("x", regionStart)
12 years ago
.attr("width", regionWidth)
12 years ago
}
12 years ago
12 years ago
function draw (targets) {
var barTargetsNum = getTargetsNum(isBarType), barWidth = 0, bar2Width = 0, barIndices, barX
12 years ago
var f, c
12 years ago
/*-- Main --*/
12 years ago
f = main.select('.chart')
12 years ago
.selectAll('.target')
.data(targets)
.enter().append('g')
12 years ago
.attr('class', function(d){ return 'target target-' + d.id })
12 years ago
.style("pointer-events", "none")
12 years ago
.style('opacity', 0)
12 years ago
// Lines for each data
f.append("path")
12 years ago
.attr("class", function(d){ return "target-line target-line-" + d.id })
.style("stroke", function(d) { return color(d.id) })
.filter(isLineType)
12 years ago
.attr("d", function(d){ return lineWithRegions(d.values, __data_regions[d.id]) })
12 years ago
// Circles for each data point on lines
f.append('g')
12 years ago
.attr("class", function(d){ return "selected-circles selected-circles-" + d.id })
12 years ago
f.append('g')
12 years ago
.attr("class", function(d){ return "target-circles target-circles-" + d.id })
.style("fill", function(d) { return color(d.id) })
.style("cursor", function(d){ return __data_selection_isselectable(d) ? "pointer" : null })
.filter(isLineType)
12 years ago
.selectAll("circle")
12 years ago
.data(function(d){ return d.values })
12 years ago
.enter().append("circle")
12 years ago
.attr("class", function(d,i){ return "target-circle target-circle-" + i })
.attr("cx", function(d) { return x(d.x) })
.attr("cy", function(d) { return y(d.value) })
12 years ago
.attr("r", __point_r)
// Rects for each data
barWidth = (xAxis.tickOffset()*2*0.6) / barTargetsNum
barIndices = getBarTargetIndices()
barX = getBarX(barWidth, barTargetsNum, barIndices)
12 years ago
f.append('g')
12 years ago
.attr("class", function(d){ return "target-bars target-bars-" + d.id })
.style("fill", function(d){ return color(d.id) })
.style("stroke", function(d){ return color(d.id) })
.style("cursor", function(d){ return __data_selection_isselectable(d) ? "pointer" : null })
.filter(isBarType)
12 years ago
.selectAll("bar")
12 years ago
.data(function(d){ return d.values })
12 years ago
.enter().append("rect")
12 years ago
.attr("class", function(d,i){ return "target-bar target-bar-" + i })
.attr("x", barX)
12 years ago
.attr("y", function(d){ return y(d.value) })
12 years ago
.attr("width", barWidth)
12 years ago
.attr("height", function(d){ return height-y(d.value) })
//-- Main Update Section --//
12 years ago
main.selectAll('.target-line')
.data(targets)
.filter(isLineType)
12 years ago
.transition()
12 years ago
.attr("d", function(d){ return lineWithRegions(d.values, __data_regions[d.id]) })
12 years ago
main.selectAll('.target-circles')
.data(targets)
.filter(isLineType)
12 years ago
.selectAll('circle')
12 years ago
.data(function(d) { return d.values })
12 years ago
.transition()
12 years ago
.attr("cx", function(d) { return x(d.x) })
.attr("cy", function(d) { return y(d.value) })
12 years ago
12 years ago
main.selectAll(".target-bars")
.data(targets)
.filter(isBarType)
.selectAll('rect')
.data(function(d) { return d.values })
.transition()
.attr("x", barX)
.attr("y", function(d){ return y(d.value) })
.attr("width", barWidth)
.attr("height", function(d){ return height-y(d.value) })
12 years ago
/*-- Context --*/
if (__subchart_show) {
12 years ago
c = context.select('.chart')
12 years ago
.selectAll('.target')
.data(targets)
.enter().append('g')
12 years ago
.attr('class', function(d){ return 'target target-' + d.id })
.style('opacity', 0)
12 years ago
// Lines for each data
c.append("path")
12 years ago
.attr("class", function(d){ return "target-line target-line-" + d.id })
.style("stroke", function(d) { return color(d.id) })
.filter(isLineType)
12 years ago
.attr("d", function (d) { return line2(d.values) })
12 years ago
// Rects for each data
bar2Width = (xAxis2.tickOffset()*2*0.6) / barTargetsNum
barX = getBarX(bar2Width, barTargetsNum, barIndices)
12 years ago
c.append('g')
12 years ago
.attr("class", function(d){ return "target-bars target-bars-" + d.id })
.style("fill", function(d){ return color(d.id) })
.filter(isBarType)
12 years ago
.selectAll("bar")
12 years ago
.data(function(d){ return d.values })
12 years ago
.enter().append("rect")
12 years ago
.attr("class", function(d,i){ return "target-bar target-bar-" + i })
.attr("x", barX)
12 years ago
.attr("y", function(d){ return y2(d.value) })
12 years ago
.attr("width", bar2Width)
12 years ago
.attr("height", function(d){ return height2-y2(d.value) })
//-- Context Update Section --//
12 years ago
context.selectAll('.target-line')
.data(targets)
.filter(isLineType)
12 years ago
.transition()
12 years ago
.attr("d", function (d) { return line2(d.values) })
12 years ago
context.selectAll(".target-bars")
.data(targets)
.filter(isBarType)
.selectAll('rect')
.data(function(d) { return d.values })
.transition()
.attr("x", barX)
.attr("y", function(d){ return y2(d.value) })
.attr("width", bar2Width)
.attr("height", function(d){ return height2-y2(d.value) })
12 years ago
}
/*-- Legend --*/
if (__legend_show) {
12 years ago
drawLegend(targets)
12 years ago
}
/*-- Show --*/
// Fade-in each chart
d3.selectAll('.target')
.transition()
12 years ago
.style("opacity", 1)
}
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) {
12 years ago
d.values = targets[i].values
12 years ago
targets.splice(i,1)
12 years ago
break
12 years ago
}
}
12 years ago
})
c3.data.targets = c3.data.targets.concat(targets) // add remained
12 years ago
if (__axis_y_rescale) {
12 years ago
y.domain(getYDomain(c3.data.targets))
y2.domain(y.domain())
main.select('.y.axis').transition().call(yAxis)
12 years ago
}
12 years ago
draw(c3.data.targets)
12 years ago
12 years ago
done()
}
12 years ago
12 years ago
/*-- Draw Legend --*/
function drawLegend (targets) {
12 years ago
var ids = targets.map(function(d){ return d.id })
var l
12 years ago
// Define g for legend area
12 years ago
l = legend.selectAll('.legend-item')
12 years ago
.data(ids)
.enter().append('g')
12 years ago
.attr('class', function(d){ return 'legend-item legend-item-' + d })
12 years ago
.style('cursor', 'pointer')
.on('click', function(d){
12 years ago
__legend_item_onclick(d)
12 years ago
})
.on('mouseover', function(d){
12 years ago
d3.selectAll('.legend-item').filter(function(_d){ return _d !== d })
12 years ago
.transition().duration(100)
12 years ago
.style('opacity', 0.3)
c3.defocus()
c3.focus(d)
12 years ago
})
.on('mouseout', function(d){
d3.selectAll('.legend-item')
.transition().duration(100)
12 years ago
.style('opacity', 1)
c3.revert()
})
12 years ago
12 years ago
l.append('rect').classed("legend-item-event",true).attr('x', -200)
l.append('rect').classed("legend-item-tile",true).attr('x', -200)
l.append('text').attr('x', -200)
12 years ago
legend.selectAll('rect.legend-item-event')
.data(ids)
.style('fill-opacity', 0)
.attr('width', __legend_item_width)
.attr('height', 24)
12 years ago
.attr('y', function(d,i){ return legendHeight/2 - 16 })
12 years ago
legend.selectAll('rect.legend-item-tile')
.data(ids)
12 years ago
.style('fill', function(d){ return color(d) })
12 years ago
.attr('width', 10)
.attr('height', 10)
12 years ago
.attr('y', function(d,i){ return legendHeight/2 - 9 })
12 years ago
legend.selectAll('text')
.data(ids)
12 years ago
.text(function(d){ return __data_names[d] })
.attr('y', function(d,i){ return legendHeight/2 })
12 years ago
12 years ago
updateLegend(targets)
}
12 years ago
function updateLegend (targets) {
12 years ago
var ids = targets.map(function(d){ return d.id }),
padding = width/2 - __legend_item_width*Object.keys(targets).length/2
12 years ago
legend.selectAll('rect.legend-item-event')
.data(ids)
.transition()
12 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()
12 years ago
.attr('x', function(d,i){ return padding + __legend_item_width*i })
12 years ago
legend.selectAll('text')
.data(ids)
.transition()
12 years ago
.attr('x', function(d,i){ return padding + __legend_item_width*i + 14 })
}
12 years ago
12 years ago
/*-- Event Handling --*/
function getTargetSelector (target) {
12 years ago
return (typeof target === 'undefined') ? '.target' : '.target-' + target
}
12 years ago
12 years ago
c3.focus = function (target) {
12 years ago
d3.selectAll(getTargetSelector(target))
12 years ago
.filter(function(d){ return hasTarget(d.id) })
12 years ago
.classed('focused', true)
.transition().duration(100)
12 years ago
.style('opacity', 1)
}
12 years ago
12 years ago
c3.defocus = function (target) {
12 years ago
d3.selectAll(getTargetSelector(target))
12 years ago
.filter(function(d){ return hasTarget(d.id) })
12 years ago
.classed('focused', false)
.transition().duration(100)
.style('opacity', 0.3)
12 years ago
}
12 years ago
12 years ago
c3.revert = function (target) {
12 years ago
d3.selectAll(getTargetSelector(target))
12 years ago
.filter(function(d){ return hasTarget(d.id) })
12 years ago
.classed('focused', false)
.transition().duration(100)
12 years ago
.style('opacity', 1)
}
12 years ago
12 years ago
c3.show = function (target) {
12 years ago
d3.selectAll(getTargetSelector(target))
.transition()
12 years ago
.style('opacity', 1)
}
12 years ago
12 years ago
c3.hide = function (target) {
12 years ago
d3.selectAll(getTargetSelector(target))
.transition()
12 years ago
.style('opacity', 0)
}
12 years ago
12 years ago
c3.load = function (args) {
12 years ago
// check args
if (typeof args.done === 'undefined') {
12 years ago
args.done = function() {}
12 years ago
}
// use cache if exists
12 years ago
if ('cacheIds' in args && hasCaches(args.cacheIds)) {
12 years ago
load(getCaches(args.cacheIds), args.done)
return
12 years ago
}
// load data
if ('data' in args) {
12 years ago
load(convertDataToTargets(data), args.done)
12 years ago
}
else if ('url' in args) {
d3.csv(args.url, function(error, data){
12 years ago
load(convertDataToTargets(data), args.done)
})
12 years ago
}
else if ('rows' in args) {
12 years ago
load(convertDataToTargets(convertRowsToData(args.rows)), args.done)
12 years ago
}
else if ('columns' in args) {
12 years ago
load(convertDataToTargets(convertColumnsToData(args.columns)), args.done)
12 years ago
}
else {
12 years ago
throw Error('url or rows or columns is required.')
12 years ago
}
12 years ago
}
12 years ago
12 years ago
c3.unload = function (target) {
c3.data.targets = c3.data.targets.filter(function(d){
12 years ago
return d.id != target
})
12 years ago
d3.selectAll('.target-'+target)
.transition()
.style('opacity', 0)
12 years ago
.remove()
12 years ago
if (__legend_show) {
12 years ago
d3.selectAll('.legend-item-'+target).remove()
updateLegend(c3.data.targets)
12 years ago
}
if (__axis_y_rescale){
12 years ago
y.domain(getYDomain(c3.data.targets))
y2.domain(y.domain())
main.select('.y.axis').transition().call(yAxis)
12 years ago
}
12 years ago
if (c3.data.targets.length > 0) update(true)
}
12 years ago
12 years ago
c3.selected = function (target) {
12 years ago
var suffix = (typeof target !== 'undefined') ? '-' + target : ''
12 years ago
return d3.merge(
main.selectAll('.target-circles' + suffix)
.selectAll('circle')
12 years ago
.filter(function(){ return d3.select(this).classed('_s_') })
.map(function(d){ return d.map(function(_d){ return _d.__data__ }) })
)
12 years ago
}
12 years ago
c3.select = function (indices, resetOther) {
12 years ago
if ( ! __data_selection_enabled) return
12 years ago
main.selectAll('.target-circles').selectAll('.target-circle').each(function(d,i){
if (indices.indexOf(i) >= 0) {
if (__data_selection_grouped || __data_selection_isselectable(d)) {
12 years ago
selectPoint(d3.select(this).classed('_s_',true), d, i)
12 years ago
}
} else if (typeof resetOther !== 'undefined' && resetOther) {
12 years ago
unselectPoint(d3.select(this).classed('_s_',false), d, i)
12 years ago
}
12 years ago
})
12 years ago
}
12 years ago
c3.unselect = function (indices) {
12 years ago
if ( ! __data_selection_enabled) return
12 years ago
main.selectAll('.target-circles').selectAll('.target-circle').each(function(d,i){
if (typeof indices === 'undefined' || indices.indexOf(i) >= 0) {
if (__data_selection_grouped || __data_selection_isselectable(d)) {
12 years ago
unselectPoint(d3.select(this).classed('_s_',false), d, i)
12 years ago
}
}
12 years ago
})
12 years ago
}
12 years ago
/*-- Load data and init chart with defined functions --*/
12 years ago
if ('url' in config.data) {
12 years ago
d3.csv(config.data.url, function(error, data) { init(data) })
12 years ago
}
else if ('rows' in config.data) {
12 years ago
init(convertRowsToData(config.data.rows))
12 years ago
}
else if ('columns' in config.data) {
12 years ago
init(convertColumnsToData(config.data.columns))
12 years ago
}
else {
12 years ago
throw Error('url or rows or columns is required.')
12 years ago
}
12 years ago
return c3
}
12 years ago
12 years ago
function categoryAxis () {
12 years ago
var scale = d3.scale.linear(), orient = "bottom", tickMajorSize = 6, tickMinorSize = 6, tickEndSize = 6, tickPadding = 3, tickCentered = false, tickTextNum = 30, tickOffset = 0, categories = []
12 years ago
function axisX (selection, x) {
selection.attr("transform", function(d){
12 years ago
return "translate(" + (x(d) + tickOffset) + ",0)"
})
}
12 years ago
function axisY (selection, y) {
selection.attr("transform", function(d){
12 years ago
return "translate(" + y(d) + ",0)"
})
}
12 years ago
function scaleExtent (domain) {
12 years ago
var start = domain[0], stop = domain[domain.length - 1]
return start < stop ? [ start, stop ] : [ stop, start ]
}
12 years ago
function generateTicks (domain) {
12 years ago
var ticks = []
12 years ago
for (var i = Math.ceil(domain[0]); i < domain[1]; i++) {
12 years ago
ticks.push(i)
12 years ago
}
if (ticks.length > 0 && ticks[0] > 0) {
12 years ago
ticks.unshift(ticks[0] - (ticks[1]-ticks[0]))
12 years ago
}
12 years ago
return ticks
}
12 years ago
function shouldShowTickText (ticks, i) {
12 years ago
return ticks.length < tickTextNum || i % Math.ceil(ticks.length / tickTextNum) == 0
}
12 years ago
function category (i) {
12 years ago
return i < categories.length ? categories[i] : i
12 years ago
}
function axis(g) {
g.each(function() {
12 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":
{
12 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
}
case "left":
{
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", "end")
pathUpdate.attr("d", "M" + -tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + -tickEndSize)
break
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) {
12 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) {
12 years ago
return scale1(d) + dx
}
tickEnter.call(tickTransform, x)
tickUpdate.call(tickTransform, x)
12 years ago
}
12 years ago
})
12 years ago
}
axis.scale = function(x) {
12 years ago
if (!arguments.length) return scale
scale = x
return axis
}
12 years ago
axis.orient = function(x) {
12 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
axis.categories = function(x) {
12 years ago
if (!arguments.length) return categories
categories = x
return axis
}
12 years ago
axis.tickCentered = function(x) {
12 years ago
if (!arguments.length) return tickCentered
tickCentered = x
return axis
}
12 years ago
axis.tickOffset = function() {
12 years ago
return tickOffset
12 years ago
}
12 years ago
return axis
}
12 years ago
12 years ago
})(window)