first commit

This commit is contained in:
dev-chiefworks
2022-05-31 16:21:53 -04:00
commit f76abffdcd
5978 changed files with 1078901 additions and 0 deletions
+104
View File
@@ -0,0 +1,104 @@
$(document).ready(function(){
const API = function() {
const api = {};
api.remove = function (url, itemId) {
// alert('This function will be implemented with AJAX.' + itemId.toString());
window.location.href = url;
}
return api;
}
window.__api__ = new API();
});
// predefine date ranges ex. YYYY-MM-DD - YYYY-MM-DD => YYYY-MM-DD to YYYY-MM-DD
const customDateRange = function (datepicker) {
let start = moment();
let end = moment();
function cb(start, end) {
datepicker.val(start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
}
cb(start, end);
datepicker.daterangepicker({
locale: {
format: 'YYYY-MM-DD'
}
}, cb);
cb(start, end);
datepicker.on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' to ' + picker.endDate.format('YYYY-MM-DD'));
});
datepicker.on('cancel.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' to ' + picker.endDate.format('YYYY-MM-DD'));
});
}
window.getURLParameter = function (url, name) {
return (RegExp(name + '=' + '(.+?)(&|$)').exec(url) || [, null])[1];
}
window.loadingButton = function(btn) {
if (btn !== null) btn.button('loading');
}
window.stopLoadingButton = function(btn) {
if (btn !== null) btn.button('reset');
}
window.setDefaultDate = function(form) {
form = (form === null || form === 'undefined')
? $('body')
: form;
let start_date = form.find('#start_date');
let end_date = form.find('#end_date');
if ( ! start_date.val() && ! end_date.val()) {
start_date
.datepicker('setDate', moment(moment.now())
.subtract(1, 'months').format("YYYY/MM/DD"));
end_date
.datepicker('setDate', moment(moment.now())
.format("YYYY/MM/DD"));
}
}
window.setDefaultDateWithMonths = function(form, month) {
form = (form === null || form === 'undefined')
? $('body')
: $(form);
let start_date = form.find('#start_date').length !== 0
? form.find('#start_date')
: form.find('#from_date');
let end_date = form.find('#end_date').length !== 0
? form.find('#end_date')
: form.find('#to_date');
start_date.datepicker('setDate', moment(moment.now())
.subtract(month, 'months').format("YYYY/MM/DD"));
end_date.datepicker('setDate', moment(moment.now())
.format("YYYY/MM/DD"));
}
window.addDatePicker = function(item) {
$(item).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
clearBtn: true,
format: "yyyy-mm-dd",
onClose: function(selectedDate) {
$(item).datepicker("option", "minDate", selectedDate);
}
});
}
+201
View File
@@ -0,0 +1,201 @@
/* ------------------------------------------------------------------------------
*
* # C3.js - advanced examples
*
* Demo setup of chart transformations, zoom, pan and brushing features
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Chart transforms
// ------------------------------
// Generate chart
var transform = c3.generate({
bindto: '#c3-transform',
size: { height: 400 },
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 130, 100, 140, 200, 150, 50]
]
},
grid: {
y: {
show: true
}
}
});
// Update data
function update() {
transform.transform('donut');
setTimeout(function () {
transform.transform('area');
}, 1500);
setTimeout(function () {
transform.transform('bar', 'data1');
}, 3000);
setTimeout(function () {
transform.transform('scatter');
}, 4500);
setTimeout(function () {
transform.transform('bar');
}, 6000);
setTimeout(function () {
transform.transform('step');
}, 7500);
setTimeout(function () {
transform.transform('line');
$('#btn-transform').removeClass('disabled');
}, 11500);
}
// Run update on click
$('#btn-transform').click(function () {
$(this).addClass('disabled');
update();
});
// Zoomable chart
// ------------------------------
// Generate chart
var zoomable_chart = c3.generate({
bindto: '#c3-chart-zoomable',
size: { height: 400 },
data: {
columns: [
['sample', 30, 120, 320, 180, 50, 250, 167, 279, 290, 400, 214, 190, 40, 400, 162, 289, 300, 200, 120, 320, 390, 110, 130, 400, 240, 189, 250, 30, 100, 200, 300, 250, 50, 100, 50, 300, 250, 20, 90, 150, 400, 320, 220, 150, 190, 270, 190, 350, 90, 300, 150, 220, 170, 40]
]
},
color: {
pattern: ['#1E88E5']
},
zoom: {
enabled: true
},
grid: {
x: {
show: true
},
y: {
show: true
}
}
});
// Subchart (brushing)
// ------------------------------
// Generate chart
var subchart = c3.generate({
bindto: '#c3-subchart',
size: { height: 400 },
data: {
columns: [
['sample', 30, 200, 100, 400, 150, 250, 150, 200, 170, 240, 350, 150, 100, 400, 150, 250, 150, 200, 170, 240, 100, 150, 250, 150, 200, 170, 240, 30, 200, 100, 400, 150, 250, 150, 200, 170, 240, 350, 150, 100, 400, 350, 220, 250, 300, 270, 140, 150, 90, 150, 50, 120, 70, 40]
]
},
color: {
pattern: ['#00ACC1']
},
subchart: {
show: true
},
grid: {
y: {
show: true
}
}
});
// Label format
// ------------------------------
// Generate chart
var label_format = c3.generate({
bindto: '#c3-label-format',
size: { height: 400 },
data: {
columns: [
['data1', 30, -200, -100, 400, 150, 250, 100, 120, 150],
['data2', -50, 150, 150, -150, -50, -150, -120, -100, -120],
['data3', -100, 100, -40, 100, -150, -50, 90, -40, 100]
],
groups: [
['data1', 'data2']
],
type: 'bar',
labels: {
format: {
y: d3.format('$')
}
}
},
color: {
pattern: ['#4CAF50', '#F4511E', '#1E88E5']
},
bar: {
width: {
ratio: 1
}
},
grid: {
y: {
lines: [{value: 0}]
}
}
});
// Data colors
// ------------------------------
// Generate chart
var data_color = c3.generate({
bindto: '#c3-data-color',
size: { height: 400 },
data: {
columns: [
['data1', 30, 20, 50, 40, 60, 50],
['data2', 200, 130, 90, 240, 130, 220],
['data3', 300, 200, 160, 400, 250, 250]
],
type: 'bar',
colors: {
data1: '#4DB6AC',
data2: '#009688',
data3: '#00796B'
}
},
grid: {
y: {
show: true
}
}
});
// Resize chart on sidebar width change
$(".sidebar-control").on('click', function() {
transform.resize();
zoomable_chart.resize();
subchart.resize();
label_format.resize();
data_color.resize();
});
});
+187
View File
@@ -0,0 +1,187 @@
/* ------------------------------------------------------------------------------
*
* # C3.js - chart axis
*
* Demo setup of chart axis with options
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Categorized axis
// ------------------------------
// Generate chart
var axis_categorized = c3.generate({
bindto: '#c3-axis-categorized',
size: { height: 400 },
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250, 50, 100, 250]
]
},
color: {
pattern: ['#03A9F4']
},
axis: {
x: {
type: 'category',
categories: ['cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7', 'cat8', 'cat9']
}
},
grid: {
x: {
show: true
}
}
});
// Additional axis
// ------------------------------
// Generate chart
var axis_additional = c3.generate({
bindto: '#c3-axis-additional',
size: { height: 400 },
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
],
axes: {
data1: 'y',
data2: 'y2'
}
},
color: {
pattern: ['#4CAF50', '#607D8B']
},
axis: {
y2: {
show: true
}
},
grid: {
y: {
show: true
}
}
});
// Axis tick culling
// ------------------------------
// Generate chart
var axis_tick_culling = c3.generate({
bindto: '#c3-axis-tick-culling',
size: { height: 400 },
data: {
columns: [
['sample', 30, 200, 100, 400, 150, 250, 30, 200, 100, 400, 150, 250, 30, 200, 100, 400, 150, 250, 200, 100, 400, 150, 250]
]
},
color: {
pattern: ['#FF5722']
},
axis: {
x: {
type: 'category',
tick: {
culling: {
max: 4
}
}
}
}
});
// Text label rotation
// ------------------------------
// Generate chart
var axis_tick_rotation = c3.generate({
bindto: '#c3-axis-tick-rotation',
size: { height: 400 },
data: {
x : 'x',
columns: [
['x', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
['pv', 90, 100, 140, 200, 100, 400, 90, 100, 140, 200, 100, 400],
],
type: 'bar'
},
color: {
pattern: ['#00BCD4']
},
axis: {
x: {
type: 'category',
tick: {
rotate: -90
},
height: 80
}
},
grid: {
x: {
show: true
}
}
});
// Axis labels
// ------------------------------
// Generate chart
var axis_labels = c3.generate({
bindto: '#c3-axis-labels',
size: { height: 400 },
data: {
columns: [
['sample', 30, 200, 100, 400, 150, 250],
['sample2', 130, 300, 200, 500, 250, 350]
],
axes: {
sample2: 'y2'
}
},
color: {
pattern: ['#9C27B0']
},
axis: {
x: {
label: 'X Label'
},
y: {
label: 'Y Label'
},
y2: {
show: true,
label: 'Y2 Label'
}
}
});
// Resize chart on sidebar width change
$(".sidebar-control").on('click', function() {
axis_categorized.resize();
axis_additional.resize();
axis_tick_culling.resize();
axis_tick_rotation.resize();
axis_labels.resize();
});
});
+295
View File
@@ -0,0 +1,295 @@
/* ------------------------------------------------------------------------------
*
* # C3.js - bars and pies
*
* Demo setup of bars, pies and chart combinations
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Pie chart
// ------------------------------
// Generate chart
var pie_chart = c3.generate({
bindto: '#c3-pie-chart',
size: { width: 350 },
color: {
pattern: ['#3F51B5', '#FF9800', '#4CAF50', '#00BCD4', '#F44336']
},
data: {
columns: [
['data1', 30],
['data2', 120],
],
type : 'pie'
}
});
// Change data
setTimeout(function () {
pie_chart.load({
columns: [
["setosa", 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2],
["versicolor", 1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1.0, 1.3, 1.4, 1.0, 1.5, 1.0, 1.4, 1.3, 1.4, 1.5, 1.0, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1.0, 1.1, 1.0, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3, 1.2, 1.4, 1.2, 1.0, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3],
["virginica", 2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2.0, 1.9, 2.1, 2.0, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2.0, 2.0, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2.0, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1, 2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2.0, 2.3, 1.8],
]
});
}, 4000);
setTimeout(function () {
pie_chart.unload({
ids: 'data1'
});
pie_chart.unload({
ids: 'data2'
});
}, 8000);
// Donut chart
// ------------------------------
// Generate chart
var donut_chart = c3.generate({
bindto: '#c3-donut-chart',
size: { width: 350 },
color: {
pattern: ['#3F51B5', '#FF9800', '#4CAF50', '#00BCD4', '#F44336']
},
data: {
columns: [
['data1', 30],
['data2', 120],
],
type : 'donut'
},
donut: {
title: "Iris Petal Width"
}
});
// Change data
setTimeout(function () {
donut_chart.load({
columns: [
["setosa", 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2],
["versicolor", 1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1.0, 1.3, 1.4, 1.0, 1.5, 1.0, 1.4, 1.3, 1.4, 1.5, 1.0, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1.0, 1.1, 1.0, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3, 1.2, 1.4, 1.2, 1.0, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3],
["virginica", 2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2.0, 1.9, 2.1, 2.0, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2.0, 2.0, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2.0, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1, 2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2.0, 2.3, 1.8],
]
});
}, 4000);
setTimeout(function () {
donut_chart.unload({
ids: 'data1'
});
donut_chart.unload({
ids: 'data2'
});
}, 8000);
// Bar chart
// ------------------------------
// Generate chart
var bar_chart = c3.generate({
bindto: '#c3-bar-chart',
size: { height: 400 },
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 130, 100, 140, 200, 150, 50]
],
type: 'bar'
},
color: {
pattern: ['#2196F3', '#FF9800', '#4CAF50']
},
bar: {
width: {
ratio: 0.5
}
},
grid: {
y: {
show: true
}
}
});
// Change data
setTimeout(function () {
bar_chart.load({
columns: [
['data3', 130, -150, 200, 300, -200, 100]
]
});
}, 6000);
// Stacked bar chart
// ------------------------------
// Generate chart
var bar_stacked_chart = c3.generate({
bindto: '#c3-bar-stacked-chart',
size: { height: 400 },
color: {
pattern: ['#FF9800', '#F44336', '#009688', '#4CAF50']
},
data: {
columns: [
['data1', -30, 200, 200, 400, -150, 250],
['data2', 130, 100, -100, 200, -150, 50],
['data3', -230, 200, 200, -300, 250, 250]
],
type: 'bar',
groups: [
['data1', 'data2']
]
},
grid: {
x: {
show: true
},
y: {
lines: [{value:0}]
}
}
});
// Change data
setTimeout(function () {
bar_stacked_chart.groups([['data1', 'data2', 'data3']])
}, 4000);
setTimeout(function () {
bar_stacked_chart.load({
columns: [['data4', 100, -50, 150, 200, -300, -100]]
});
}, 8000);
setTimeout(function () {
bar_stacked_chart.groups([['data1', 'data2', 'data3', 'data4']])
}, 10000);
// Combined chart
// ------------------------------
// Generate chart
var combined_chart = c3.generate({
bindto: '#c3-combined-chart',
size: { height: 400 },
color: {
pattern: ['#FF9800', '#F44336', '#009688', '#4CAF50', '#03A9F4', '#8BC34A']
},
data: {
columns: [
['data1', 30, 20, 50, 40, 60, 50],
['data2', 200, 130, 90, 240, 130, 220],
['data3', 300, 200, 160, 400, 250, 250],
['data4', 200, 130, 90, 240, 130, 220],
['data5', 130, 120, 150, 140, 160, 150],
['data6', 90, 70, 20, 50, 60, 120],
],
type: 'bar',
types: {
data3: 'spline',
data4: 'line',
data6: 'area',
},
groups: [
['data1','data2']
]
}
});
// Scatter chart
// ------------------------------
// Generate chart
var scatter_chart = c3.generate({
size: { height: 400 },
bindto: '#c3-scatter-chart',
data: {
xs: {
setosa: 'setosa_x',
versicolor: 'versicolor_x',
},
columns: [
["setosa_x", 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3.0, 3.0, 4.0, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3.0, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.6, 3.0, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3.0, 3.8, 3.2, 3.7, 3.3],
["versicolor_x", 3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2.0, 3.0, 2.2, 2.9, 2.9, 3.1, 3.0, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3.0, 2.8, 3.0, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3.0, 3.4, 3.1, 2.3, 3.0, 2.5, 2.6, 3.0, 2.6, 2.3, 2.7, 3.0, 2.9, 2.9, 2.5, 2.8],
["setosa", 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2],
["versicolor", 1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1.0, 1.3, 1.4, 1.0, 1.5, 1.0, 1.4, 1.3, 1.4, 1.5, 1.0, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1.0, 1.1, 1.0, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3, 1.2, 1.4, 1.2, 1.0, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3],
],
type: 'scatter'
},
color: {
pattern: ['#4CAF50', '#F44336']
},
grid: {
y: {
show: true
}
},
point: { r: 5 },
axis: {
x: {
label: 'Sepal.Width',
tick: {
fit: false
}
},
y: {
label: 'Petal.Width'
}
}
});
// Change data
setTimeout(function () {
scatter_chart.load({
xs: {
virginica: 'virginica_x'
},
columns: [
["virginica_x", 3.3, 2.7, 3.0, 2.9, 3.0, 3.0, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3.0, 2.5, 2.8, 3.2, 3.0, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3.0, 2.8, 3.0, 2.8, 3.8, 2.8, 2.8, 2.6, 3.0, 3.4, 3.1, 3.0, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3.0, 2.5, 3.0, 3.4, 3.0],
["virginica", 2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2.0, 1.9, 2.1, 2.0, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2.0, 2.0, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2.0, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1, 2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2.0, 2.3, 1.8],
]
});
}, 4000);
setTimeout(function () {
scatter_chart.unload({
ids: 'setosa'
});
}, 8000);
setTimeout(function () {
scatter_chart.load({
columns: [
["virginica", 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2],
]
});
}, 10000);
// Resize chart on sidebar width change
$(".sidebar-control").on('click', function() {
pie_chart.resize();
donut_chart.resize();
bar_chart.resize();
bar_stacked_chart.resize();
combined_chart.resize();
scatter_chart.resize();
});
});
+170
View File
@@ -0,0 +1,170 @@
/* ------------------------------------------------------------------------------
*
* # C3.js - chart grid
*
* Demo setup of chart grid with options
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Grid lines
// ------------------------------
// Generate chart
var grid_lines = c3.generate({
bindto: '#c3-grid-lines',
size: { height: 400 },
color: {
pattern: ['#2196F3']
},
data: {
columns: [
['sample', 30, 200, 100, 400, 150, 250, 120, 200]
]
},
grid: {
x: {
show: true
},
y: {
show: true
}
}
});
// Optional X grid lines
// ------------------------------
// Generate chart
var grid_lines_x = c3.generate({
bindto: '#c3-grid-lines-x',
size: { height: 400 },
color: {
pattern: ['#4CAF50']
},
data: {
columns: [
['sample', 30, 200, 100, 400, 150, 250]
]
},
grid: {
x: {
lines: [{value: 3, text: 'Label 3'}, {value: 4.5, text: 'Label 4.5'}]
}
}
});
// Optional Y grid lines
// ------------------------------
// Generate chart
var grid_lines_y = c3.generate({
bindto: '#c3-grid-lines-y',
size: { height: 400 },
data: {
columns: [
['sample', 30, 200, 100, 400, 150, 250],
['sample2', 1300, 1200, 1100, 1400, 1500, 1250],
],
axes: {
sample2: 'y2'
}
},
color: {
pattern: ['#607D8B', '#FF9800']
},
axis: {
y2: {
show: true
}
},
grid: {
y: {
lines: [{value: 50, text: 'Label 50'}, {value: 1300, text: 'Label 1300', axis: 'y2'}]
}
}
});
// Rects on chart
// ------------------------------
// Generate chart
var grid_region = c3.generate({
bindto: '#c3-grid-region',
size: { height: 400 },
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250, 400],
['data2', 830, 1200, 1100, 1400, 1150, 1250, 1500],
],
axes: {
data2: 'y2'
}
},
color: {
pattern: ['#607D8B', '#FF9800']
},
axis: {
y2: {
show: true
}
},
regions: [
{axis: 'x', end: 1, class: 'regionX'},
{axis: 'x', start: 2, end: 4, class: 'regionX'},
{axis: 'x', start: 5, class: 'regionX'},
{axis: 'y', end: 50, class: 'regionY'},
{axis: 'y', start: 80, end: 140, class: 'regionY'},
{axis: 'y', start: 400, class: 'regionY'},
{axis: 'y2', end: 900, class: 'regionY2'},
{axis: 'y2', start: 1150, end: 1250, class: 'regionY2'},
{axis: 'y2', start: 1300, class: 'regionY2'},
]
});
// Data regions
// ------------------------------
// Generate chart
var grid_region_chart = c3.generate({
bindto: '#c3-grid-chart-region',
size: { height: 400 },
color: {
pattern: ['#009688', '#9C27B0']
},
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
],
regions: {
'data1': [{'start':1, 'end':2, 'style':'dashed'},{'start':3}], // currently 'dashed' style only
'data2': [{'end':3}]
}
}
});
// Resize chart on sidebar width change
$(".sidebar-control").on('click', function() {
grid_lines.resize();
grid_lines_x.resize();
grid_lines_y.resize();
grid_region.resize();
grid_region_chart.resize();
});
});
+198
View File
@@ -0,0 +1,198 @@
/* ------------------------------------------------------------------------------
*
* # C3.js - lines and areas
*
* Demo setup of line, step and area charts
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Line chart
// ------------------------------
// Generate chart
var line_chart = c3.generate({
bindto: '#c3-line-chart',
point: {
r: 4
},
size: { height: 400 },
color: {
pattern: ['#4CAF50', '#F4511E', '#1E88E5']
},
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
],
type: 'spline'
},
grid: {
y: {
show: true
}
}
});
// Change data
setTimeout(function () {
line_chart.load({
columns: [
['data1', 230, 190, 300, 500, 300, 400]
]
});
}, 3000);
setTimeout(function () {
line_chart.load({
columns: [
['data3', 130, 150, 200, 300, 200, 100]
]
});
}, 6000);
setTimeout(function () {
line_chart.unload({
ids: 'data1'
});
}, 9000);
// Line chart with regions
// ------------------------------
// Generate chart
var chart_line_regions = c3.generate({
bindto: '#c3-line-regions-chart',
size: { height: 400 },
point: {
r: 4
},
color: {
pattern: ['#E53935', '#5E35B1']
},
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
],
regions: {
'data1': [{'start':1, 'end':2, 'style':'dashed'},{'start':3}],
'data2': [{'end':3}]
}
},
grid: {
y: {
show: true
}
}
});
// Area chart
// ------------------------------
// Generate chart
var area_chart = c3.generate({
bindto: '#c3-area-chart',
size: { height: 400 },
point: {
r: 4
},
color: {
pattern: ['#E53935', '#3949AB']
},
data: {
columns: [
['data1', 300, 350, 300, 0, 0, 0],
['data2', 130, 100, 140, 200, 150, 50]
],
types: {
data1: 'area-spline',
data2: 'area-spline'
}
},
grid: {
y: {
show: true
}
}
});
// Stacked area chart
// ------------------------------
// Generate chart
var area_stacked_chart = c3.generate({
bindto: '#c3-area-stacked-chart',
size: { height: 400 },
color: {
pattern: ['#1E88E5', '#F4511E']
},
point: {
r: 4
},
data: {
columns: [
['data1', 300, 350, 300, 0, 0, 120],
['data2', 130, 100, 140, 200, 150, 50]
],
types: {
data1: 'area-spline',
data2: 'area-spline'
},
groups: [['data1', 'data2']]
},
grid: {
y: {
show: true
}
}
});
// Step chart
// ------------------------------
// Generate chart
var step_chart = c3.generate({
bindto: '#c3-step-chart',
size: { height: 400 },
color: {
pattern: ['#6D4C41', '#039BE5']
},
data: {
columns: [
['data1', 300, 350, 300, 0, 0, 100],
['data2', 130, 100, 140, 200, 150, 50]
],
types: {
data1: 'step',
data2: 'area-step'
}
},
grid: {
y: {
show: true
}
}
});
// Resize chart on sidebar width change
$(".sidebar-control").on('click', function() {
line_chart.resize();
chart_line_regions.resize();
area_chart.resize();
area_stacked_chart.resize();
step_chart.resize();
});
});
File diff suppressed because one or more lines are too long
@@ -0,0 +1,7 @@
/*!
* chartjs-adapter-luxon v0.1.1
* https://www.chartjs.org
* (c) 2019 Chart.js Contributors
* Released under the MIT license
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("chart.js"),require("luxon")):"function"==typeof define&&define.amd?define(["chart.js","luxon"],t):t((e=e||self).Chart,e.luxon)}(this,function(e,t){"use strict";var n={datetime:"MMM d, yyyy, h:mm:ss a",millisecond:"h:mm:ss.SSS a",second:"h:mm:ss a",minute:"h:mm a",hour:"ha",day:"MMM d",week:"DD",month:"MMM yyyy",quarter:"'Q'q - yyyy",year:"yyyy"};function r(e){return t.DateTime.fromMillis(e)}e._adapters._date.override({_id:"luxon",formats:function(){return n},parse:function(n,f){if(e.helpers.isNullOrUndef(n))return null;var a=typeof n;return"number"===a?n=r(n):"string"===a?n="string"==typeof f?t.DateTime.fromFormat(n,f):t.DateTime.fromISO(n):"object"===a?n=t.DateTime.fromObject(n):n instanceof Date&&(n=t.DateTime.fromJSDate(n)),n.isValid?n.valueOf():null},format:function(e,t){return r(e).toFormat(t)},add:function(e,t,n){var f={};return f[n]=t,r(e).plus(f).valueOf()},diff:function(e,t,n){return r(e).diff(r(t)).as(n).valueOf()},startOf:function(e,t,n){return"isoWeek"===t?r(e).isoWeekday(n).valueOf():t?r(e).startOf(t).valueOf():e},endOf:function(e,t){return r(e).endOf(t).valueOf()}})});
@@ -0,0 +1,462 @@
/*!
* @license
* chartjs-chart-financial
* http://chartjs.org/
* Version: 0.1.0
*
* Copyright 2019 Chart.js Contributors
* Released under the MIT license
* https://github.com/chartjs/chartjs-chart-financial/blob/master/LICENSE.md
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('chart.js')) :
typeof define === 'function' && define.amd ? define(['chart.js'], factory) :
(global = global || self, factory(global.Chart));
}(this, function (Chart) { 'use strict';
Chart = Chart && Chart.hasOwnProperty('default') ? Chart['default'] : Chart;
var helpers = Chart.helpers;
var defaultConfig = {
position: 'left',
ticks: {
callback: Chart.Ticks.formatters.linear
}
};
var FinancialLinearScale = Chart.scaleService.getScaleConstructor('linear').extend({
determineDataLimits: function() {
var me = this;
var chart = me.chart;
var data = chart.data;
var datasets = data.datasets;
var isHorizontal = me.isHorizontal();
function IDMatches(meta) {
return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
}
// First Calculate the range
me.min = null;
me.max = null;
// Regular charts use x, y values
// For the financial chart we have rawValue.h (hi) and rawValue.l (low) for each point
helpers.each(datasets, function(dataset, datasetIndex) {
var meta = chart.getDatasetMeta(datasetIndex);
if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
helpers.each(dataset.data, function(rawValue) {
var high = rawValue.h;
var low = rawValue.l;
if (me.min === null) {
me.min = low;
} else if (low < me.min) {
me.min = low;
}
if (me.max === null) {
me.max = high;
} else if (high > me.max) {
me.max = high;
}
});
}
});
// Add whitespace around bars. Axis shouldn't go exactly from min to max
var space = (me.max - me.min) * 0.05;
me.min -= space;
me.max += space;
// Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
this.handleTickRangeOptions();
}
});
Chart.scaleService.registerScaleType('financialLinear', FinancialLinearScale, defaultConfig);
var helpers$1 = Chart.helpers;
Chart.defaults.financial = {
label: '',
hover: {
mode: 'label'
},
scales: {
xAxes: [{
type: 'time',
distribution: 'series',
categoryPercentage: 0.8,
barPercentage: 0.9,
ticks: {
source: 'data'
}
}],
yAxes: [{
type: 'financialLinear'
}]
},
tooltips: {
intersect: false,
mode: 'index',
callbacks: {
label: function(tooltipItem, data) {
var p = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].p;
var o = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].o;
var h = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].h;
var l = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].l;
var c = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].c;
var dataset = data.datasets[tooltipItem.datasetIndex];
var precision = helpers$1.valueOrDefault(dataset.precision, 2);
precision = Math.max(0, Math.min(100, precision));
o = o.toFixed(precision);
h = h.toFixed(precision);
l = l.toFixed(precision);
c = c.toFixed(precision);
return (p!=''?(p+'\r'):'') + ' O: ' + o + ' H: ' + h + ' L: ' + l + ' C: ' + c;
}
}
}
};
/**
* This class is based off controller.bar.js from the upstream Chart.js library
*/
var FinancialController = Chart.controllers.bar.extend({
dataElementType: Chart.elements.Financial,
/**
* @private
*/
_updateElementGeometry: function(element, index, reset) {
var me = this;
var model = element._model;
var vscale = me._getValueScale();
var base = vscale.getBasePixel();
var horizontal = vscale.isHorizontal();
var ruler = me._ruler || me.getRuler();
var vpixels = me.calculateBarValuePixels(me.index, index);
var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
var chart = me.chart;
var datasets = chart.data.datasets;
var indexData = datasets[me.index].data[index];
model.horizontal = horizontal;
model.base = reset ? base : vpixels.base;
model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
model.height = horizontal ? ipixels.size : undefined;
model.width = horizontal ? undefined : ipixels.size;
model.candleOpen = vscale.getPixelForValue(Number(indexData.o));
model.candleHigh = vscale.getPixelForValue(Number(indexData.h));
model.candleLow = vscale.getPixelForValue(Number(indexData.l));
model.candleClose = vscale.getPixelForValue(Number(indexData.c));
},
draw: function() {
var ctx = this.chart.chart.ctx;
var elements = this.getMeta().data;
var dataset = this.getDataset();
var ilen = elements.length;
var i = 0;
var d;
Chart.canvasHelpers.clipArea(ctx, this.chart.chartArea);
for (; i < ilen; ++i) {
d = dataset.data[i].o;
if (d !== null && d !== undefined && !isNaN(d)) {
elements[i].draw();
}
}
Chart.canvasHelpers.unclipArea(ctx);
},
});
var helpers$2 = Chart.helpers;
var globalOpts = Chart.defaults.global;
globalOpts.elements.financial = {
color: {
up: 'rgba(80, 160, 115, 1)',
down: 'rgba(215, 85, 65, 1)',
unchanged: 'rgba(90, 90, 90, 1)',
}
};
function isVertical(bar) {
return bar._view.width !== undefined;
}
/**
* Helper function to get the bounds of the candle
* @private
* @param bar {Chart.Element.financial} the bar
* @return {Bounds} bounds of the bar
*/
function getBarBounds(candle) {
var vm = candle._view;
var x1, x2, y1, y2;
var halfWidth = vm.width / 2;
x1 = vm.x - halfWidth;
x2 = vm.x + halfWidth;
y1 = vm.candleHigh;
y2 = vm.candleLow;
return {
left: x1,
top: y1,
right: x2,
bottom: y2
};
}
var FinancialElement = Chart.Element.extend({
height: function() {
var vm = this._view;
return vm.base - vm.y;
},
inRange: function(mouseX, mouseY) {
var inRange = false;
if (this._view) {
var bounds = getBarBounds(this);
inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom;
}
return inRange;
},
inLabelRange: function(mouseX, mouseY) {
var me = this;
if (!me._view) {
return false;
}
var inRange = false;
var bounds = getBarBounds(me);
if (isVertical(me)) {
inRange = mouseX >= bounds.left && mouseX <= bounds.right;
} else {
inRange = mouseY >= bounds.top && mouseY <= bounds.bottom;
}
return inRange;
},
inXRange: function(mouseX) {
var bounds = getBarBounds(this);
return mouseX >= bounds.left && mouseX <= bounds.right;
},
inYRange: function(mouseY) {
var bounds = getBarBounds(this);
return mouseY >= bounds.top && mouseY <= bounds.bottom;
},
getCenterPoint: function() {
var vm = this._view;
return {
x: vm.x,
y: (vm.candleHigh + vm.candleLow) / 2
};
},
getArea: function() {
var vm = this._view;
return vm.width * Math.abs(vm.y - vm.base);
},
tooltipPosition: function() {
var vm = this._view;
return {
x: vm.x,
y: (vm.candleOpen + vm.candleClose) / 2
};
},
hasValue: function() {
var model = this._model;
return helpers$2.isNumber(model.x) &&
helpers$2.isNumber(model.candleOpen) &&
helpers$2.isNumber(model.candleHigh) &&
helpers$2.isNumber(model.candleLow) &&
helpers$2.isNumber(model.candleClose);
}
});
var helpers$3 = Chart.helpers;
var globalOpts$1 = Chart.defaults.global;
globalOpts$1.elements.candlestick = helpers$3.merge({}, [globalOpts$1.elements.financial, {
borderColor: globalOpts$1.elements.financial.color.unchanged,
borderWidth: 1,
}]);
var CandlestickElement = FinancialElement.extend({
draw: function() {
var ctx = this._chart.ctx;
var vm = this._view;
var x = vm.x;
var o = vm.candleOpen;
var h = vm.candleHigh;
var l = vm.candleLow;
var c = vm.candleClose;
var borderColors = vm.borderColor;
if (typeof borderColors === 'string') {
borderColors = {
up: borderColors,
down: borderColors,
unchanged: borderColors
};
}
var borderColor;
if (c < o) {
borderColor = helpers$3.getValueOrDefault(borderColors ? borderColors.up : undefined, globalOpts$1.elements.candlestick.borderColor);
ctx.fillStyle = helpers$3.getValueOrDefault(vm.color ? vm.color.up : undefined, globalOpts$1.elements.candlestick.color.up);
} else if (c > o) {
borderColor = helpers$3.getValueOrDefault(borderColors ? borderColors.down : undefined, globalOpts$1.elements.candlestick.borderColor);
ctx.fillStyle = helpers$3.getValueOrDefault(vm.color ? vm.color.down : undefined, globalOpts$1.elements.candlestick.color.down);
} else {
borderColor = helpers$3.getValueOrDefault(borderColors ? borderColors.unchanged : undefined, globalOpts$1.elements.candlestick.borderColor);
ctx.fillStyle = helpers$3.getValueOrDefault(vm.color ? vm.color.unchanged : undefined, globalOpts$1.elements.candlestick.color.unchanged);
}
ctx.lineWidth = helpers$3.getValueOrDefault(vm.borderWidth, globalOpts$1.elements.candlestick.borderWidth);
ctx.strokeStyle = helpers$3.getValueOrDefault(borderColor, globalOpts$1.elements.candlestick.borderColor);
ctx.beginPath();
ctx.moveTo(x, h);
ctx.lineTo(x, Math.min(o, c));
ctx.moveTo(x, l);
ctx.lineTo(x, Math.max(o, c));
ctx.stroke();
ctx.fillRect(x - vm.width / 2, c, vm.width, o - c);
ctx.strokeRect(x - vm.width / 2, c, vm.width, o - c);
ctx.closePath();
},
});
Chart.defaults.candlestick = Chart.helpers.merge({}, Chart.defaults.financial);
var CandlestickController = Chart.controllers.candlestick = FinancialController.extend({
dataElementType: CandlestickElement,
updateElement: function(element, index, reset) {
var me = this;
var meta = me.getMeta();
var dataset = me.getDataset();
element._xScale = me.getScaleForId(meta.xAxisID);
element._yScale = me.getScaleForId(meta.yAxisID);
element._datasetIndex = me.index;
element._index = index;
element._model = {
datasetLabel: dataset.label || '',
// label: '', // to get label value please use dataset.data[index].label
// Appearance
color: dataset.color,
borderColor: dataset.borderColor,
borderWidth: dataset.borderWidth,
};
me._updateElementGeometry(element, index, reset);
element.pivot();
},
});
var helpers$4 = Chart.helpers;
var globalOpts$2 = Chart.defaults.global;
globalOpts$2.elements.ohlc = helpers$4.merge({}, [globalOpts$2.elements.financial, {
lineWidth: 2,
armLength: null,
armLengthRatio: 0.8,
}]);
var OhlcElement = FinancialElement.extend({
draw: function() {
var ctx = this._chart.ctx;
var vm = this._view;
var x = vm.x;
var o = vm.candleOpen;
var h = vm.candleHigh;
var l = vm.candleLow;
var c = vm.candleClose;
var armLength = helpers$4.getValueOrDefault(vm.armLength, globalOpts$2.elements.ohlc.armLength);
var armLengthRatio = helpers$4.getValueOrDefault(vm.armLengthRatio, globalOpts$2.elements.ohlc.armLengthRatio);
if (armLength === null) {
// The width of an ohlc is affected by barPercentage and categoryPercentage
// This behavior is caused by extending controller.financial, which extends controller.bar
// barPercentage and categoryPercentage are now set to 1.0 (see controller.ohlc)
// and armLengthRatio is multipled by 0.5,
// so that when armLengthRatio=1.0, the arms from neighbour ohcl touch,
// and when armLengthRatio=0.0, ohcl are just vertical lines.
armLength = vm.width * armLengthRatio * 0.5;
}
if (c < o) {
ctx.strokeStyle = helpers$4.getValueOrDefault(vm.color ? vm.color.up : undefined, globalOpts$2.elements.ohlc.color.up);
} else if (c > o) {
ctx.strokeStyle = helpers$4.getValueOrDefault(vm.color ? vm.color.down : undefined, globalOpts$2.elements.ohlc.color.down);
} else {
ctx.strokeStyle = helpers$4.getValueOrDefault(vm.color ? vm.color.unchanged : undefined, globalOpts$2.elements.ohlc.color.unchanged);
}
ctx.lineWidth = helpers$4.getValueOrDefault(vm.lineWidth, globalOpts$2.elements.ohlc.lineWidth);
ctx.beginPath();
ctx.moveTo(x, h);
ctx.lineTo(x, l);
ctx.moveTo(x - armLength, o);
ctx.lineTo(x, o);
ctx.moveTo(x + armLength, c);
ctx.lineTo(x, c);
ctx.stroke();
},
});
Chart.defaults.ohlc = Chart.helpers.merge({}, Chart.defaults.financial);
Chart.defaults.ohlc.scales.xAxes[0].barPercentage = 1.0;
Chart.defaults.ohlc.scales.xAxes[0].categoryPercentage = 1.0;
var OhlcController = Chart.controllers.ohlc = FinancialController.extend({
dataElementType: OhlcElement,
updateElement: function(element, index, reset) {
var me = this;
var meta = me.getMeta();
var dataset = me.getDataset();
element._xScale = me.getScaleForId(meta.xAxisID);
element._yScale = me.getScaleForId(meta.yAxisID);
element._datasetIndex = me.index;
element._index = index;
element._model = {
datasetLabel: dataset.label || '',
lineWidth: dataset.lineWidth,
armLength: dataset.armLength,
armLengthRatio: dataset.armLengthRatio,
color: dataset.color,
};
me._updateElementGeometry(element, index, reset);
element.pivot();
},
});
}));
File diff suppressed because one or more lines are too long
+333
View File
@@ -0,0 +1,333 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - hierarchical bar chart
*
* Demo d3.js hierarchical bar chart setup with .json data
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
stackedMultiples('#d3-hierarchical-bars', 400);
// Chart setup
function stackedMultiples(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 25, right: 40, bottom: 20, left: 130},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5,
barHeight = 30,
duration = 750,
delay = 25;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.range([0, width]);
// Colors
var color = d3.scale.ordinal()
.range(["#26A69A", "#ccc"]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("top");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Partition
var partition = d3.layout.partition()
.value(function(d) { return d.size; });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/bars/bars_hierarchical.json", function(error, root) {
partition.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
});
//
// Append chart elements
//
// Add background bars
svg.append("rect")
.attr("class", "d3-bars-background")
.attr("width", width)
.attr("height", height)
.style("fill", "#fff")
.on("click", up);
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong");
// Append bars
// ------------------------------
// Create hierarchical structure
function down(d, i) {
if (!d.children || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Entering nodes immediately obscure the clicked-on bar, so hide it.
exit.selectAll("rect").filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Enter the new bars for the clicked-on data.
// Per above, entering bars are immediately visible.
var enter = bar(d)
.attr("transform", stack(i))
.style("opacity", 1);
// Have the text fade-in, even though the bars are visible.
// Color the bars as parents; they will fade to children if appropriate.
enter.select("text").style("fill-opacity", 1e-6);
enter.select("rect").style("fill", color(true));
// Update the x-scale domain.
x.domain([0, d3.max(d.children, function(d) { return d.value; })]).nice();
// Update the x-axis.
svg.selectAll(".d3-axis-horizontal").transition()
.duration(duration)
.call(xAxis);
// Transition entering bars to their new position.
var enterTransition = enter.transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", function(d, i) { return "translate(0," + barHeight * i * 1.2 + ")"; });
// Transition entering text.
enterTransition.select("text")
.style("fill-opacity", 1);
// Transition entering rects to the new x-scale.
enterTransition.select("rect")
.attr("width", function(d) { return x(d.value); })
.style("fill", function(d) { return color(!!d.children); });
// Transition exiting bars to fade out.
var exitTransition = exit.transition()
.duration(duration)
.style("opacity", 1e-6)
.remove();
// Transition exiting bars to the new x-scale.
exitTransition.selectAll("rect")
.attr("width", function(d) { return x(d.value); });
// Rebind the current node to the background.
svg.select(".d3-bars-background")
.datum(d)
.transition()
.duration(end);
d.index = i;
}
// Return to parent level
function up(d) {
if (!d.parent || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Enter the new bars for the clicked-on data's parent.
var enter = bar(d.parent)
.attr("transform", function(d, i) { return "translate(0," + barHeight * i * 1.2 + ")"; })
.style("opacity", 1e-6);
// Color the bars as appropriate.
// Exiting nodes will obscure the parent bar, so hide it.
enter.select("rect")
.style("fill", function(d) { return color(!!d.children); })
.filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Update the x-scale domain.
x.domain([0, d3.max(d.parent.children, function(d) { return d.value; })]).nice();
// Update the x-axis.
svg.selectAll(".d3-axis-horizontal").transition()
.duration(duration)
.call(xAxis);
// Transition entering bars to fade in over the full duration.
var enterTransition = enter.transition()
.duration(end)
.style("opacity", 1);
// Transition entering rects to the new x-scale.
// When the entering parent rect is done, make it visible!
enterTransition.select("rect")
.attr("width", function(d) { return x(d.value); })
.each("end", function(p) { if (p === d) d3.select(this).style("fill-opacity", null); });
// Transition exiting bars to the parent's position.
var exitTransition = exit.selectAll("g").transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", stack(d.index));
// Transition exiting text to fade out.
exitTransition.select("text")
.style("fill-opacity", 1e-6);
// Transition exiting rects to the new scale and fade to parent color.
exitTransition.select("rect")
.attr("width", function(d) { return x(d.value); })
.style("fill", color(true));
// Remove exiting nodes when the last child has finished transitioning.
exit.transition()
.duration(end)
.remove();
// Rebind the current parent to the background.
svg.select(".d3-bars-background")
.datum(d.parent)
.transition()
.duration(end);
}
// Creates a set of bars for the given data node, at the specified index.
function bar(d) {
var bar = svg.insert("g", ".d3-axis-vertical")
.attr("class", "enter")
.attr("transform", "translate(0,5)")
.selectAll("g")
.data(d.children)
.enter()
.append("g")
.style("cursor", function(d) { return !d.children ? null : "pointer"; })
.on("click", down);
bar.append("text")
.attr("x", -6)
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d.name; });
bar.append("rect")
.attr("width", function(d) { return x(d.value); })
.attr("height", barHeight);
return bar;
}
// A stateful closure for stacking bars horizontally.
function stack(i) {
var x0 = 0;
return function(d) {
var tx = "translate(" + x0 + "," + barHeight * i * 1.2 + ")";
x0 += x(d.value);
return tx;
};
}
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Bars
svg.selectAll('.enter rect').attr("width", function(d) { return x(d.value); });
}
}
});
+198
View File
@@ -0,0 +1,198 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - histogram chart
*
* Demo d3.js histogram chart setup with tooltip and random data
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
stackedMultiples('#d3-histogram', 400);
// Chart setup
function stackedMultiples(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 15, right: 20, bottom: 20, left: 60},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Generate a Bates distribution of 10 random variables.
var values = d3.range(1000).map(d3.random.bates(4));
// Data format
var formatCount = d3.format(",.0f");
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.domain([0, 1])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
(values);
// Vertical
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
// Colors
var color = d3.scale.ordinal().range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Add tooltip
// ------------------------------
// Create tooltip
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-25, 0])
.html(function(d) {
return "Current value: " + "<span class='text-semibold'>" + formatCount(d.y) + "</span>";
})
// Initialize tooltip
svg.call(tip);
//
// Append chart elements
//
// Add bars
// ------------------------------
// Group each bar
var bar = svg.selectAll(".d3-bar")
.data(data)
.enter()
.append("g")
.attr("class", "d3-bar")
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; })
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
// Append bars
bar.append("rect")
.attr("x", 1)
.attr("width", x(data[0].dx) - 3)
.attr("height", function(d) { return height - y(d.y); })
.style("fill", function(d) { return color(d); });
// Append text
bar.append("text")
.attr("dy", ".75em")
.attr("y", -15)
.attr("x", x(data[0].dx) / 2)
.style("text-anchor", "middle")
.style("fill", "#333")
.text(function(d) { return formatCount(d.y); });
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Bar group
svg.selectAll('.d3-bar').attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
// Bar rect
svg.selectAll('.d3-bar rect').attr("x", 1).attr("width", x(data[0].dx) - 3);
// Bar text
svg.selectAll('.d3-bar text').attr("x", x(data[0].dx) / 2);
}
}
});
@@ -0,0 +1,271 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - bars with simple interaction
*
* Demo d3.js bar chart setup with animated data source change
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Create Uniform checkbox
$(".toggle-dataset").uniform();
// Initialize chart
interaction('#d3-simple-interaction', 400);
// Chart setup
function interaction(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 10},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Demo data set
var dataset = [40.5, 33.1, 31.6, 31.0, 29.9, 28.9, 25.2, 25.2, 24.8, 24.3, 24.0, 22.6, 20.5, 19.5, 19.0, 18.9, 18.8, 18.5, 18.4, 17.6, 17.1];
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.ordinal()
.domain(d3.range(dataset.length))
.rangeRoundBands([0, width], 0.05);
// Vertical
var y = d3.scale.linear()
.domain([0, d3.max(dataset)])
.range([0, height]);
// Colors
var colors = d3.scale.category20();
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Add tooltip
// ------------------------------
// Create tooltip
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) { return d })
// Initialize tooltip
svg.call(tip);
//
// Append chart elements
//
// Append bars
// ------------------------------
// Add bars
var drawBars = svg.selectAll(".d3-bar")
.data(dataset)
.enter()
.append("rect")
.attr("class", "d3-bar")
.attr("x", function(d, i) { return x(i) })
.attr("width", x.rangeBand())
.attr("height", 0)
.attr("y", height)
.attr("fill", function(d, i) { return colors(i); })
.style("cursor", "pointer")
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
// Add bar transition
drawBars.transition()
.delay(200)
.duration(1000)
.attr("height", function(d) { return y(d) })
.attr("y", function(d) { return height - y(d) })
// Add text labels
var drawLabels = svg.selectAll(".value-label")
.data(dataset)
.enter()
.append("text")
.attr("class", "value-label")
.attr("x", function(d, i) { return x(i) + x.rangeBand() / 2 })
.attr("y", function(d) { return height - y(d) + 25; })
.style('opacity', 0)
.style("text-anchor", "middle")
.style("fill", "white")
.text(function(d) {return d;});
// Add text label transition
drawLabels.transition()
.delay(1000)
.duration(500)
.style('opacity', 1);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Change data sets
// ------------------------------
$('.toggle-dataset').on('change', function() {
if(this.checked) {
dataset = [8.4, 12.1, 25.5, 10.3, 11.7, 10.9, 13.3, 23.1, 15.4, 12.3, 17.8, 18.8, 14.7, 8.8, 11.2, 10.2, 17.1, 14.5, 11.9, 7.3, 7.4];
// Update all rects
svg.selectAll("rect")
.data(dataset)
.transition()
.delay(0)
.duration(1000)
.ease('cubic-in-out')
.attr("y", function(d) { return height - y(d) })
.attr("height", function(d) { return y(d) })
.style("fill", colors)
// Update labels
var drawNewlabels = svg.selectAll("text")
.data(dataset)
.attr("x", function(d, i) {return x(i) + x.rangeBand() / 2 })
.attr("y", function(d) {return height - y(d) + 25 })
.style('opacity', 0)
.text(function(d) {return d;});
// Transition
drawNewlabels.transition()
.delay(1000)
.duration(500)
.style('opacity', 1)
}
else {
dataset = [40.5, 33.1, 31.6, 31.0, 29.9, 28.9, 25.2, 25.2, 24.8, 24.3, 24.0, 22.6, 20.5, 19.5, 19.0, 18.9, 18.8, 18.5, 18.4, 17.6, 17.1];
// Update all rects
svg.selectAll("rect")
.data(dataset)
.transition()
.delay(0)
.duration(1000)
.ease('cubic-in-out')
.attr("y", function(d) { return height - y(d) })
.attr("height", function(d) { return y(d) })
.style("fill", function(d, i) { return colors(i); });
/* Update labels */
var drawFirstlabels = svg.selectAll("text")
.data(dataset)
.attr("x", function(d, i) {return x(i) + x.rangeBand() / 2 })
.attr("y", function(d) {return height - y(d) + 25 })
.style('opacity', 0)
.text(function(d) {return d;});
drawFirstlabels.transition()
.delay(1000)
.duration(500)
.style('opacity', 1);
}
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.rangeRoundBands([0, width], 0.05);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Bars
svg.selectAll('.d3-bar').attr("x", function(d, i) { return x(i) }).attr("width", x.rangeBand());
// Text label
svg.selectAll(".value-label").attr("x", function(d, i) { return x(i) + x.rangeBand() / 2 });
}
}
});
@@ -0,0 +1,201 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - horizontal sortable bars
*
* Demo d3.js horizontal bar chart setup with animated sorting
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
sortableVertical('#d3-bar-sortable-horizontal', 400);
// Chart setup
function sortableVertical(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Add data
var index = d3.range(8),
data = index.map(d3.random.normal(40, 10));
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width]);
// Vertical
var y = d3.scale.ordinal()
.domain(index)
.rangeRoundBands([height, 0], .3);
// Colors
var colors = d3.scale.category20c();
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(8);
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Append bars
// ------------------------------
// Group each bar
var bar = svg.selectAll(".d3-bar")
.data(data)
.enter()
.append("g")
.attr("class", "d3-bar")
.attr("fill", function(d, i) { return colors(i); })
.attr("transform", function(d, i) { return "translate(0," + y(i) + ")"; });
// Append bar rectangle
bar.append("rect")
.attr("height", y.rangeBand())
.attr("width", x);
// Append text label
bar.append("text")
.attr("x", function(d) { return x(d) - 12 })
.attr("y", y.rangeBand() / 2)
.attr("dy", ".35em")
.style("fill", "#fff")
.style("text-anchor", "end")
.text(function(d, i) { return i; });
// Setup sort
// ------------------------------
var sort = false;
setInterval(function() {
if (sort = !sort) {
index.sort(function(a, b) { return data[a] - data[b]; });
} else {
index = d3.range(8);
}
y.domain(index);
bar.transition()
.duration(750)
.delay(function(d, i) { return i * 50; })
.attr("transform", function(d, i) { return "translate(0," + y(i) + ")"; });
}, 4000);
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Bar rect
svg.selectAll('.d3-bar rect').attr("width", x);
// Bar text
svg.selectAll('.d3-bar text').attr("x", function(d) { return x(d) - 12; });
}
}
});
@@ -0,0 +1,236 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - vertical sortable bars
*
* Demo d3.js vertical bar chart setup with animated sorting and .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Add uniform styling
$(".toggle-sort").uniform();
// Initialize chart
sortableVertical('#d3-bar-sortable-vertical', 400);
// Chart setup
function sortableVertical(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var formatPercent = d3.format(".0%");
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1, 1);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Colors
var colors = d3.scale.category20c();
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(formatPercent);
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/bars/bars_basic.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.frequency = +d.frequency;
});
// Set input domains
// ------------------------------
// Horizontal
x.domain(data.map(function(d) { return d.letter; }));
// Vertical
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Frequency");
// Append bars
// ------------------------------
svg.selectAll(".d3-bar")
.data(data)
.enter()
.append("rect")
.attr("class", "d3-bar")
.attr("fill", function(d, i) { return colors(i); })
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); });
// Change data sets
// ------------------------------
// Attach change event
d3.select(".toggle-sort").on("change", change);
// Sort values on page load with delay
var sortTimeout = setTimeout(function() {
d3.select(".toggle-sort").property("checked", true).each(change);
$.uniform.update();
}, 2000);
// Sorting function
function change() {
clearTimeout(sortTimeout);
// Copy-on-write since tweens are evaluated after a delay.
var x0 = x.domain(data.sort(this.checked
? function(a, b) { return b.frequency - a.frequency; }
: function(a, b) { return d3.ascending(a.letter, b.letter); })
.map(function(d) { return d.letter; }))
.copy();
var transition = svg.transition().duration(750),
delay = function(d, i) { return i * 50; };
transition.selectAll(".d3-bar")
.delay(delay)
.attr("x", function(d) { return x0(d.letter); });
transition.select(".d3-axis-horizontal")
.call(xAxis)
.selectAll("g")
.delay(delay);
}
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.rangeRoundBands([0, width], .1, 1);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-bar').attr("width", x.rangeBand()).attr("x", function(d) { return x(d.letter); });
}
}
});
@@ -0,0 +1,291 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - stacked and multiple bars
*
* Demo d3.js bar chart setup with animated transition between stacked and multiple bars
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Create Uniform checkbox
$(".stacked-multiple").uniform({
radioClass: 'choice'
});
// Initialize chart
stackedMultiples('#d3-bar-stacked-multiples', 400);
// Chart setup
function stackedMultiples(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 60},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%Y-%m").parse,
formatYear = d3.format("02d"),
formatDate = function(d) { return "Q" + ((d.getMonth() / 3 | 0) + 1) + formatYear(d.getFullYear() % 100); };
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .2);
// Vertical
var y = d3.scale.ordinal()
.rangeRoundBands([height, 0]);
var y0 = d3.scale.ordinal()
.rangeRoundBands([height, 0]);
var y1 = d3.scale.linear();
// Colors
var color = d3.scale.category20();
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(formatDate);
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "%");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Nest
var nest = d3.nest()
.key(function(d) { return d.browser; });
// Stack
var stack = d3.layout.stack()
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.value; })
.out(function(d, y0) { d.valueOffset = y0; });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/bars/bars_stacked_multiple.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
d.value = +d.value;
});
// Nest values
var dataByGroup = nest.entries(data);
// Set input domains
// ------------------------------
// Stack
stack(dataByGroup);
// Horizontal
x.domain(dataByGroup[0].values.map(function(d) { return d.date; }));
// Vertical
y0.domain(dataByGroup.map(function(d) { return d.key; }));
y1.domain([0, d3.max(data, function(d) { return d.value; })]).range([y0.rangeBand(), 0]);
//
// Append chart elements
//
// Add bars
// ------------------------------
// Group bars
var group = svg.selectAll(".d3-bar-group")
.data(dataByGroup)
.enter()
.append("g")
.attr("class", "d3-bar-group")
.attr("transform", function(d) { return "translate(0," + y0(d.key) + ")"; });
// Append text
group.append("text")
.attr("class", "d3-group-label")
.attr("x", -12)
.attr("y", function(d) { return y1(d.values[0].value / 2); })
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d.key; });
// Add bars
group.selectAll(".d3-bar")
.data(function(d) { return d.values; })
.enter()
.append("rect")
.attr("class", "d3-bar")
.attr("x", function(d) { return x(d.date); })
.attr("y", function(d) { return y1(d.value); })
.attr("width", x.rangeBand())
.attr("height", function(d) { return y0.rangeBand() - y1(d.value); })
.style("fill", function(d) { return color(d.browser); });
// Append axes
// ------------------------------
// Horizontal
group.filter(function(d, i) { return !i; }).append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + (y0.rangeBand() + 1) + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Appent text label
verticalAxis.append("text")
.attr('class', 'browser-label')
.attr("x", -12)
.attr("y", 12)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Browser");
// Setup layout change
// ------------------------------
// Add change event
d3.selectAll(".stacked-multiple").on("change", change);
// Change value on page load
var timeout = setTimeout(function() {
d3.select("input[value=\"stacked\"]").property("checked", true).each(change);
$.uniform.update();
}, 2000);
// Change function
function change() {
clearTimeout(timeout);
if (this.value === "multiples") transitionMultiples();
else transitionStacked();
}
// Transition to multiples
function transitionMultiples() {
var t = svg.transition().duration(750),
g = t.selectAll(".d3-bar-group").attr("transform", function(d) { return "translate(0," + y0(d.key) + ")"; });
g.selectAll(".d3-bar").attr("y", function(d) { return y1(d.value); });
g.select(".d3-group-label").attr("y", function(d) { return y1(d.values[0].value / 2); })
}
// Transition to stacked
function transitionStacked() {
var t = svg.transition().duration(750),
g = t.selectAll(".d3-bar-group").attr("transform", "translate(0," + y0(y0.domain()[0]) + ")");
g.selectAll(".d3-bar").attr("y", function(d) { return y1(d.value + d.valueOffset) });
g.select(".d3-group-label").attr("y", function(d) { return y1(d.values[0].value / 2 + d.values[0].valueOffset); })
}
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.rangeRoundBands([0, width], .2);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-bar').attr("x", function(d) { return x(d.date); }).attr("width", x.rangeBand());
}
}
});
+245
View File
@@ -0,0 +1,245 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - grouped bar chart
*
* Demo d3.js grouped bar chart setup with .csv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
barGrouped('#d3-bar-grouped', 400);
// Chart setup
function barGrouped(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Construct scales
// ------------------------------
// Horizontal
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Colors
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/bars/bars_grouped.csv", function(error, data) {
// Filter values by key
var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });
// Pull out values
data.forEach(function(d) {
d.ages = ageNames.map(function(name) { return {name: name, value: +d[name]}; });
});
// Set input domains
// ------------------------------
// Horizontal
x0.domain(data.map(function(d) { return d.State; }));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
// Vertical
y.domain([0, d3.max(data, function(d) { return d3.max(d.ages, function(d) { return d.value; }); })]);
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Population");
// Add bars
// ------------------------------
// Group values
var state = svg.selectAll(".bar-group")
.data(data)
.enter()
.append("g")
.attr("class", "bar-group")
.attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });
// Append bars
state.selectAll(".d3-bar")
.data(function(d) { return d.ages; })
.enter()
.append("rect")
.attr("class", "d3-bar")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
// Add legend
// ------------------------------
// Create legend
var legend = svg.selectAll(".d3-legend")
.data(ageNames.slice().reverse())
.enter()
.append("g")
.attr("class", "d3-legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
// Legend indicator
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
// Legend text
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.style("font-size", 12)
.text(function(d) { return d; });
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal ranges
x0.rangeRoundBands([0, width], .1);
x1.rangeRoundBands([0, x0.rangeBand()]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Bar group
svg.selectAll('.bar-group').attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });
// Bars
svg.selectAll('.d3-bar').attr("width", x1.rangeBand()).attr("x", function(d) { return x1(d.name); });
// Legend
svg.selectAll(".d3-legend text").attr("x", width - 24);
svg.selectAll(".d3-legend rect").attr("x", width - 18);
}
}
});
+209
View File
@@ -0,0 +1,209 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - horizontal bar chart
*
* Demo d3.js horizontal bar chart setup with .csv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
barVertical('#d3-bar-horizontal', 400);
// Chart setup
function barVertical(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 20, right: 10, bottom: 5, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5,
n = 12;
// Format data
var format = d3.format(",.0f");
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.range([0, width]);
// Verticals
var y = d3.scale.ordinal()
.rangeRoundBands([0, height], .1);
// Colors
var colors = d3.scale.category20();
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("top")
.tickSize(-height);
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickSize(5);
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/bars/bars_horizontal.csv", function(data) {
// Parse numbers, and sort by value.
data.forEach(function(d) { d.value = +d.value; });
data.sort(function(a, b) { return b.value - a.value; });
// Set input domains
// ------------------------------
// Horizontal
x.domain([0, d3.max(data, function(d) { return d.value; })]);
// Verticals
y.domain(data.map(function(d) { return d.name; }));
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.call(xAxis);
// Vertical
svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Remove lines
svg.selectAll(".d3-axis line, .d3-axis path").attr("stroke-width", 0);
// Append bars
// ------------------------------
// Group bars
var bar = svg.selectAll(".d3-bar-group")
.data(data)
.enter()
.append("g")
.attr("class", "d3-bar-group")
.attr("fill", function(d, i) { return colors(i); })
.attr("transform", function(d) { return "translate(0," + y(d.name) + ")"; });
// Add bar
bar.append("rect")
.attr("class", "d3-bar")
.attr("width", function(d) { return x(d.value); })
.attr("height", y.rangeBand());
// Add text label
bar.append("text")
.attr("class", "d3-label-value")
.attr("x", function(d) { return x(d.value); })
.attr("y", y.rangeBand() / 2)
.attr("dx", -10)
.attr("dy", ".35em")
.style("text-anchor", "end")
.style("fill", "#fff")
.style("font-size", 12)
.text(function(d) { return format(d.value); });
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-bar').attr("width", function(d) { return x(d.value); })
// Text label
svg.selectAll('.d3-label-value').attr("x", function(d) { return x(d.value); });
}
}
});
+244
View File
@@ -0,0 +1,244 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - stacked bar chart
*
* Demo d3.js stacked bar chart setup with .csv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
barGrouped('#d3-bar-stacked', 400);
// Chart setup
function barGrouped(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1, .5);
// Vertical
var y = d3.scale.linear()
.rangeRound([height, 0]);
// Colors
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/bars/bars_stacked.csv", function(error, data) {
// Filter values by key
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "State"; }));
// Pull out values
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.total = d.ages[d.ages.length - 1].y1;
});
// Sort data
data.sort(function(a, b) { return b.total - a.total; });
// Set input domains
// ------------------------------
// Horizontal
x.domain(data.map(function(d) { return d.State; }));
// Vertical
y.domain([0, d3.max(data, function(d) { return d.total; })]);
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Population");
// Add bars
// ------------------------------
// Group values
var state = svg.selectAll(".bar-group")
.data(data)
.enter()
.append("g")
.attr("class", "bar-group")
.attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });
// Append bars
state.selectAll(".d3-bar")
.data(function(d) { return d.ages; })
.enter()
.append("rect")
.attr("class", "d3-bar")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); });
// Add legend
// ------------------------------
// Create legend
var legend = svg.selectAll(".d3-legend")
.data(color.domain().slice().reverse())
.enter()
.append("g")
.attr("class", "d3-legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
// Legend indicator
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
// Legend text
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal ranges
x.rangeRoundBands([0, width], .1, .5);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Bar group
svg.selectAll('.bar-group').attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });
// Bars
svg.selectAll('.d3-bar').attr("width", x.rangeBand()).attr("x", function(d) { return x(d.name); });
// Legend
svg.selectAll(".d3-legend text").attr("x", width - 24);
svg.selectAll(".d3-legend rect").attr("x", width - 18);
}
}
});
@@ -0,0 +1,231 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - normalized bar chart
*
* Demo d3.js normalized bar chart setup with .csv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
barNormalized('#d3-bar-normalized', 400);
// Chart setup
function barNormalized(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 130, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
// Vertical
var y = d3.scale.linear()
.rangeRound([height, 0]);
// Color
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".0%"));
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/bars/bars_stacked.csv", function(error, data) {
// Filter values by key
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "State"; }));
// Pull out values
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.ages.forEach(function(d) { d.y0 /= y0; d.y1 /= y0; });
});
// Sort data
data.sort(function(a, b) { return b.ages[0].y1 - a.ages[0].y1; });
// Set input domains
// ------------------------------
// Horizontal
x.domain(data.map(function(d) { return d.State; }));
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add bars
// ------------------------------
// Group values
var state = svg.selectAll(".bar-group")
.data(data)
.enter()
.append("g")
.attr("class", "bar-group")
.attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });
// Append bars
state.selectAll(".d3-bar")
.data(function(d) { return d.ages; })
.enter()
.append("rect")
.attr("class", "d3-bar")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); });
// Add legend
// ------------------------------
// Create legend
var legend = svg.select(".bar-group:last-child")
.selectAll(".d3-legend")
.data(function(d) { return d.ages; })
.enter().append("g")
.attr("class", "d3-legend")
.attr("transform", function(d) { return "translate(" + x.rangeBand() + "," + y((d.y0 + d.y1) / 2) + ")"; });
// Legend line
legend.append("line")
.attr("x2", 10)
.attr("stroke", "#333")
.attr("shape-rendering", "crispEdges");
// Legend text
legend.append("text")
.attr("x", 15)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal ranges
x.rangeRoundBands([0, width], .1);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Bar group
svg.selectAll('.bar-group').attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });
// Bars
svg.selectAll('.d3-bar').attr("width", x.rangeBand())
// Legend
svg.selectAll(".d3-legend").attr("transform", function(d) { return "translate(" + x.rangeBand() + "," + y((d.y0 + d.y1) / 2) + ")"; });
}
}
});
+209
View File
@@ -0,0 +1,209 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - bar chart with tooltip
*
* Demo d3.js bar chart setup with tooltip and .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
barTooltip('#d3-bar-tooltip', 400);
// Chart setup
function barTooltip(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1, .5);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Color
var color = d3.scale.category20c();
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "%");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Create tooltip
// ------------------------------
// Create tooltip
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return d.frequency;
});
// Initialize tooltip
svg.call(tip);
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/bars/bars_tooltip.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.frequency = +d.frequency;
});
// Set input domains
// ------------------------------
// Horizontal
x.domain(data.map(function(d) { return d.letter; }));
// Vertical
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Frequency");
// Append bars
svg.selectAll(".d3-bar")
.data(data)
.enter()
.append("rect")
.attr("class", "d3-bar")
.style("fill", function(d) { return color(d.letter); })
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); })
.on('mouseover', tip.attr('class', 'tooltip-inner in').show)
.on('mouseout', tip.hide);
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.rangeRoundBands([0, width], .1, .5);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Bars
svg.selectAll('.d3-bar').attr("x", function(d) { return x(d.letter); }).attr("width", x.rangeBand());
}
}
});
+191
View File
@@ -0,0 +1,191 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - vertical bar chart
*
* Demo d3.js vertical bar chart setup with .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
barVertical('#d3-bar-vertical', 400);
// Chart setup
function barVertical(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1, .5);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Color
var color = d3.scale.category20c();
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "%");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/bars/bars_basic.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.frequency = +d.frequency;
});
// Set input domains
// ------------------------------
// Horizontal
x.domain(data.map(function(d) { return d.letter; }));
// Vertical
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Frequency");
// Add bars
svg.selectAll(".d3-bar")
.data(data)
.enter()
.append("rect")
.attr("class", "d3-bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); })
.style("fill", function(d) { return color(d.letter); });
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.rangeRoundBands([0, width], .1, .5);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-bar').attr("x", function(d) { return x(d.letter); }).attr("width", x.rangeBand());
}
}
});
+259
View File
@@ -0,0 +1,259 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - chord arc tweens
*
* Demo chord diagram setup with arc shapes animation
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Basic setup
// ------------------------------
// Data set
var data = [
[6,32,47,81,31,89,24,68,50,39],
[37,83,57,80,87,7,85,7,68,17],
[50,15,31,3,1,85,36,95,83,99],
[19,99,97,79,74,43,78,18,4,57],
[77,2,87,41,93,52,6,42,11,76],
[91,56,97,65,23,60,63,68,45,48],
[17,77,96,22,87,98,58,15,36,16],
[44,54,60,69,36,44,76,58,50,16]
];
// Construct layout
// ------------------------------
d3.chart = d3.chart || {};
d3.chart.chord = function(container) {
// Main variables
var self = {},
svg;
// Layout variables
var w = 400,
h = 400,
r0 = Math.min(w, h) * .37,
r1 = r0 * 1.1;
// Colors
var fill = d3.scale.category20c();
// Construct chart layout
// ------------------------------
// Chord layout
var chord = d3.layout.chord()
.padding(.05)
.sortSubgroups(d3.descending);
// Arc
var arc = d3.svg.arc()
.innerRadius(r0)
.outerRadius(r1);
// Setup chart
// ------------------------------
// Update chart
self.update = function(data) {
if (!chord.matrix()) {
chord.matrix(data);
self.render();
} else {
var old = {
groups: chord.groups()
};
chord.matrix(data);
self.transition(old);
}
};
// Clear chart
self.clear = function() {
d3.select(container).selectAll('svg').remove();
};
// Transition
self.transition = function(old) {
svg.selectAll(".d3-arc")
.data(chord.groups)
.transition()
.duration(1500)
.attrTween("d", arcTween(arc, old));
};
// Render chart
self.render = function() {
self.clear();
// Create chart
svg = d3.select(container)
.append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");
// Add arc
svg.append("g")
.selectAll("path")
.data(chord.groups)
.enter()
.append("path")
.attr("class", "d3-arc")
.style("fill", function(d) { return fill(d.index); })
.style("stroke", function(d) { return fill(d.index); })
.attr("d", arc)
.on("mouseover", fade(.1, svg))
.on("mouseout", fade(1, svg));
// Add ticks
// ------------------------------
// Group
var ticks = svg.append("g")
.selectAll("g")
.data(chord.groups)
.enter()
.append("g")
.selectAll("g")
.data(groupTicks)
.enter()
.append("g")
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
+ "translate(" + r1 + ",0)";
});
// Add tick line
ticks.append("line")
.attr("x1", 1)
.attr("y1", 0)
.attr("x2", 5)
.attr("y2", 0)
.style("stroke", "#000");
// Add tick text
ticks.append("text")
.attr("x", 8)
.attr("dy", ".35em")
.attr("text-anchor", function(d) {
return d.angle > Math.PI ? "end" : null;
})
.attr("transform", function(d) {
return d.angle > Math.PI ? "rotate(180)translate(-16)" : null;
})
.style("font-size", 12)
.text(function(d) { return d.label; });
// Add chord
// ------------------------------
svg.append("g")
.attr("class", "d3-chord")
.selectAll("path")
.data(chord.chords)
.enter()
.append("path")
.attr("d", d3.svg.chord().radius(r0))
.style("fill", function(d) { return fill(d.target.index); })
.style("stroke", "#000")
.style("stroke-width", 0.5)
.style("fill-opacity", 0.7)
};
return self;
};
// Utility functions
// ------------------------------
// Returns an array of tick angles and labels, given a group
function groupTicks(d) {
var k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, d.value, 50).map(function(v, i) {
return {
angle: v * k + d.startAngle,
label: i % 2 ? null : v
};
});
}
// Returns an event handler for fading a given chord group
function fade(opacity, svg) {
return function(g, i) {
svg.selectAll(".d3-chord path").filter(function(d) {
return d.source.index != i && d.target.index != i;
})
.transition()
.style("opacity", opacity);
};
}
// Interpolate the arcs in data space.
function arcTween(arc, old) {
return function(d,i) {
var i = d3.interpolate(old.groups[i], d);
return function(t) {
return arc(i(t));
}
}
}
// Random data
function random_matrix(size) {
var matrix = [];
for (var i=0; i<size; i++) {
var row = [];
for (var j=0; j<size; j++) {
var num = Math.round(100*Math.pow(Math.random(),2)+1);
row.push(num);
}
matrix.push(row);
}
return matrix;
};
// Initialize chart
// ------------------------------
for (var i=1; i<=3; i++) {
initChord(i);
}
function initChord(i) {
var chord = d3.chart.chord("#d3-chord-arc");
chord.update(data);
d3.select("#update-arc").on("click", function() {
var data = random_matrix(8);
chord.update(data);
});
d3.select("#clear-arc").on("click", function() {
chord.clear();
});
d3.select("#render-arc").on("click", function() {
chord.render();
});
}
});
+195
View File
@@ -0,0 +1,195 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - basic chord diagram
*
* Demo chord diagram setup with mouseover interaction
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Basic setup
// ------------------------------
// Data set
var data = [
[6,32,47,81,31,89,24,68,50,39],
[37,83,57,80,87,7,85,7,68,17],
[50,15,31,3,1,85,36,95,83,99],
[37,25,37,81,72,98,32,13,70,25],
[19,99,97,79,74,43,78,18,4,57],
[77,2,87,41,93,52,6,42,11,76],
[44,54,60,69,36,44,76,58,50,16]
];
// Construct layout
// ------------------------------
d3.chart = d3.chart || {};
d3.chart.chord = function(container) {
var self = {};
// Main variables
var w = 400,
h = 400,
r0 = Math.min(w, h) * .37,
r1 = r0 * 1.1;
// Colors
var fill = d3.scale.category20c();
// Add chord layout
var chord = d3.layout.chord()
.padding(.05)
.sortSubgroups(d3.descending)
// Update chart
self.update = function(data) {
chord.matrix(data);
self.render();
};
// Clear chart
self.clear = function() {
d3.select(container).selectAll('svg').remove();
};
// Render chart
self.render = function() {
self.clear();
// Create chart
var svg = d3.select(container)
.append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");
// Bind data and add chord path
svg.append("g")
.selectAll(".chord-path")
.data(chord.groups)
.enter()
.append("path")
.attr("class", "chord-path")
.style("fill", function(d) { return fill(d.index); })
.style("stroke", function(d) { return fill(d.index); })
.attr("d", d3.svg.arc().innerRadius(r0).outerRadius(r1))
.on("mouseover", fade(.1, svg))
.on("mouseout", fade(1, svg));
// Add ticks
// ------------------------------
// Group
var ticks = svg.append("g")
.selectAll("g")
.data(chord.groups)
.enter()
.append("g")
.selectAll("g")
.data(groupTicks)
.enter()
.append("g")
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
+ "translate(" + r1 + ",0)";
});
// Add tick lines
ticks.append("line")
.attr("x1", 1)
.attr("y1", 0)
.attr("x2", 5)
.attr("y2", 0)
.style("stroke", "#000");
// Add tick text
ticks.append("text")
.attr("x", 8)
.attr("dy", ".35em")
.attr("text-anchor", function(d) {
return d.angle > Math.PI ? "end" : null;
})
.attr("transform", function(d) {
return d.angle > Math.PI ? "rotate(180)translate(-16)" : null;
})
.style("font-size", 12)
.text(function(d) { return d.label; });
// Add chord
// ------------------------------
svg.append("g")
.attr("class", "d3-chord")
.selectAll("path")
.data(chord.chords)
.enter()
.append("path")
.style("fill", function(d) { return fill(d.target.index); })
.style("stroke", "#000")
.style("stroke-width", 0.5)
.style("fill-opacity", 0.7)
.attr("d", d3.svg.chord().radius(r0))
.style("opacity", 1);
};
return self;
};
// Utility functions
// ------------------------------
// Returns an array of tick angles and labels, given a group
function groupTicks(d) {
var k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, d.value, 50).map(function(v, i) {
return {
angle: v * k + d.startAngle,
label: i % 2 ? null : v
};
});
}
// Returns an event handler for fading a given chord group
function fade(opacity, svg) {
return function(g, i) {
svg.selectAll(".d3-chord path").filter(function(d) {
return d.source.index != i && d.target.index != i;
})
.transition()
.style("opacity", opacity);
};
}
// Initialize chart
// ------------------------------
initChord();
function initChord() {
var chord = d3.chart.chord("#d3-chord-basic");
chord.update(data);
d3.select("#clear-basic").on("click", function() {
chord.clear();
});
d3.select("#render-basic").on("click", function() {
chord.render();
});
}
});
+212
View File
@@ -0,0 +1,212 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - basic chord diagram
*
* Demo chord diagram setup with tools such as update, render and clear
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Basic setup
// ------------------------------
// Data set
var data = [
[6,32,47,81,31,89,24,68,50,39],
[37,83,57,80,87,7,85,7,68,17],
[50,15,31,3,1,85,36,95,83,99],
[37,25,37,81,72,98,32,13,70,25],
[19,99,97,79,74,43,78,18,4,57],
[77,2,87,41,93,52,6,42,11,76],
[44,54,60,69,36,44,76,58,50,16]
];
// Construct layout
// ------------------------------
d3.chart = d3.chart || {};
d3.chart.chord = function(container) {
var self = {};
// Main variables
var w = 400,
h = 400,
r0 = Math.min(w, h) * .37,
r1 = r0 * 1.1;
// Colors
var fill = d3.scale.category20c();
// Add chord layout
var chord = d3.layout.chord()
.padding(.05)
.sortSubgroups(d3.descending)
// Update chart
self.update = function(data) {
chord.matrix(data);
self.render();
};
// Clear chart
self.clear = function() {
d3.select(container).selectAll('svg').remove();
};
// Render chart
self.render = function() {
self.clear();
// Create chart
var svg = d3.select(container)
.append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");
// Bind data and add chord path
svg.append("g")
.selectAll("path")
.data(chord.groups)
.enter()
.append("path")
.style("fill", function(d) { return fill(d.index); })
.style("stroke", function(d) { return fill(d.index); })
.attr("d", d3.svg.arc().innerRadius(r0).outerRadius(r1))
.on("mouseover", fade(.1, svg))
.on("mouseout", fade(1, svg));
// Add ticks
// ------------------------------
// Group
var ticks = svg.append("g")
.selectAll("g")
.data(chord.groups)
.enter()
.append("g")
.selectAll("g")
.data(groupTicks)
.enter()
.append("g")
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
+ "translate(" + r1 + ",0)";
});
// Add tick lines
ticks.append("line")
.attr("x1", 1)
.attr("y1", 0)
.attr("x2", 5)
.attr("y2", 0)
.style("stroke", "#000");
// Add tick text
ticks.append("text")
.attr("x", 8)
.attr("dy", ".35em")
.attr("text-anchor", function(d) {
return d.angle > Math.PI ? "end" : null;
})
.attr("transform", function(d) {
return d.angle > Math.PI ? "rotate(180)translate(-16)" : null;
})
.style("font-size", 12)
.text(function(d) { return d.label; });
// Add chord
// ------------------------------
svg.append("g")
.attr("class", "d3-chord")
.selectAll("path")
.data(chord.chords)
.enter()
.append("path")
.attr("d", d3.svg.chord().radius(r0))
.style("fill", function(d) { return fill(d.target.index); })
.style("stroke", "#000")
.style("stroke-width", 0.5)
.style("fill-opacity", 0.7)
};
return self;
};
// Utility functions
// ------------------------------
// Returns an array of tick angles and labels, given a group
function groupTicks(d) {
var k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, d.value, 50).map(function(v, i) {
return {
angle: v * k + d.startAngle,
label: i % 2 ? null : v
};
});
}
// Returns an event handler for fading a given chord group
function fade(opacity, svg) {
return function(g, i) {
svg.selectAll(".d3-chord path").filter(function(d) {
return d.source.index != i && d.target.index != i;
})
.transition()
.style("opacity", opacity);
};
}
// Random data
function random_matrix(size) {
var matrix = [];
for (var i=0; i<size; i++) {
var row = [];
for (var j=0; j<size; j++) {
var num = Math.round(100*Math.pow(Math.random(),2)+1);
row.push(num);
}
matrix.push(row);
}
return matrix;
};
// Initialize chart
// ------------------------------
initChord();
function initChord() {
var chord = d3.chart.chord("#d3-chord-charts");
chord.update(data);
d3.select("#update-chart").on("click", function() {
var data = random_matrix(8);
chord.update(data);
});
d3.select("#clear-chart").on("click", function() {
chord.clear();
});
d3.select("#render-chart").on("click", function() {
chord.render();
});
}
});
+298
View File
@@ -0,0 +1,298 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - chord animations
*
* Demo chord diagram setup with ticks, labels and arcs animation
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Basic setup
// ------------------------------
// Data set
var data = [
[6,32,47,81,31,89,24,68,50,39],
[37,83,57,80,87,7,85,7,68,17],
[50,15,31,3,1,85,36,95,83,99],
[77,2,87,41,93,52,6,42,11,76],
[91,56,97,65,23,60,63,68,45,48],
[97,50,79,52,85,31,85,21,79,44],
[17,77,96,22,87,98,58,15,36,16],
[44,54,60,69,36,44,76,58,50,16]
];
// Construct layout
// ------------------------------
d3.chart = d3.chart || {};
d3.chart.chord = function(container) {
// Main variables
var self = {},
svg;
// Layout variables
var w = 400,
h = 400,
r0 = Math.min(w, h) * .37,
r1 = r0 * 1.1;
// Colors
var fill = d3.scale.category20();
// Construct chart layout
// ------------------------------
// Chord layout
var chord = d3.layout.chord()
.padding(.05)
.sortSubgroups(d3.descending);
// Arc
var arc_svg = d3.svg.arc()
.innerRadius(r0)
.outerRadius(r1);
// Chord
var chord_svg = d3.svg.chord().radius(r0);
// Setup chart
// ------------------------------
// Update chart
self.update = function(data) {
if (!chord.matrix()) {
chord.matrix(data);
self.render();
} else {
var old = {
groups: chord.groups(),
chords: chord.chords()
};
chord.matrix(data);
self.transition(old);
}
};
// Clear chart
self.clear = function() {
d3.select(container).selectAll('svg').remove();
};
// Transitions
self.transition = function(old) {
// Animate ticks
svg.selectAll(".d3-chord-ticks")
.transition()
.duration(200)
.attr("opacity", 0);
// Animate arc
svg.selectAll(".d3-arc")
.data(chord.groups)
.transition()
.duration(1500)
.attrTween("d", arcTween(arc_svg, old));
// Animate chord
svg.selectAll(".d3-chord")
.selectAll("path")
.data(chord.chords)
.transition()
.duration(1500)
.attrTween("d", chordTween(chord_svg, old));
setTimeout(self.drawTicks, 1100);
};
// Render chart
self.render = function() {
self.clear();
// Create chart
svg = d3.select(container).append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");
// Add arc
svg.append("g")
.selectAll(".d3-arc")
.data(chord.groups)
.enter()
.append("path")
.attr("class", "d3-arc")
.attr("d", arc_svg)
.style("fill", function(d) { return fill(d.index); })
.style("stroke", function(d) { return fill(d.index); })
.on("mouseover", fade(.1, svg))
.on("mouseout", fade(1, svg));
// Add chord
svg.append("g")
.attr("class", "d3-chord")
.selectAll("path")
.data(chord.chords)
.enter()
.append("path")
.style("fill", function(d) { return fill(d.target.index); })
.attr("d", chord_svg)
.style("stroke", "#000")
.style("stroke-width", 0.5)
.style("fill-opacity", 0.7)
// Draw ticks
self.drawTicks();
};
// Draw ticks
self.drawTicks = function() {
// Remove on load
svg.selectAll(".d3-chord-ticks").remove();
// Append ticks
var ticks = svg.append("g")
.attr("class", "d3-chord-ticks")
.attr("opacity", 0.1)
.selectAll("g")
.data(chord.groups)
.enter()
.append("g")
.selectAll("g")
.data(groupTicks)
.enter()
.append("g")
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
+ "translate(" + r1 + ",0)";
});
// Add line
ticks.append("line")
.attr("x1", 1)
.attr("y1", 0)
.attr("x2", 5)
.attr("y2", 0)
.style("stroke", "#000");
// Add text labels
ticks.append("text")
.attr("x", 8)
.attr("dy", ".35em")
.attr("text-anchor", function(d) {
return d.angle > Math.PI ? "end" : null;
})
.attr("transform", function(d) {
return d.angle > Math.PI ? "rotate(180)translate(-16)" : null;
})
.style("font-size", 12)
.text(function(d) { return d.label; });
// Transitions
svg.selectAll(".d3-chord-ticks").transition()
.duration(340)
.attr("opacity", 1);
};
return self;
};
// Utility functions
// Returns an array of tick angles and labels, given a group
function groupTicks(d) {
var k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, d.value, 50).map(function(v, i) {
return {
angle: v * k + d.startAngle,
label: i % 2 ? null : v
};
});
}
// Returns an event handler for fading a given chord group
function fade(opacity, svg) {
return function(g, i) {
svg.selectAll(".d3-chord path")
.filter(function(d) {
return d.source.index != i && d.target.index != i;
})
.transition()
.style("opacity", opacity);
};
}
// Interpolate the arcs
function arcTween(arc_svg, old) {
return function(d,i) {
var i = d3.interpolate(old.groups[i], d);
return function(t) {
return arc_svg(i(t));
}
}
}
// Interpolate the chords
function chordTween(chord_svg, old) {
return function(d,i) {
var i = d3.interpolate(old.chords[i], d);
return function(t) {
return chord_svg(i(t));
}
}
}
// Random data
function random_matrix(size) {
var matrix = [];
for (var i=0; i<size; i++) {
var row = [];
for (var j=0; j<size; j++) {
var num = Math.round(100*Math.pow(Math.random(),2)+1);
row.push(num);
}
matrix.push(row);
}
return matrix;
};
// Initialize chart
// ------------------------------
initChord();
function initChord() {
var chord = d3.chart.chord("#d3-chord-tweens");
chord.update(data);
d3.select("#update-tween").on("click", function() {
var data = random_matrix(8);
chord.update(data);
});
d3.select("#clear-tween").on("click", function() {
chord.clear();
});
d3.select("#render-tween").on("click", function() {
chord.render();
});
}
});
+252
View File
@@ -0,0 +1,252 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - difference line chart
*
* Demo d3.js difference line chart setup with .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
difference('#d3-difference', 400);
// Chart setup
function difference(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%Y%m%d").parse;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(6);
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Line
var line = d3.svg.area()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d["New York"]); });
// Area
var area = d3.svg.area()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y1(function(d) { return y(d["New York"]); });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/lines/lines_difference.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
d["New York"]= +d["New York"];
d["San Francisco"] = +d["San Francisco"];
});
// Bind data
svg.datum(data);
// Set input domains
// ------------------------------
// Horizontal
x.domain(d3.extent(data, function(d) { return d.date; }));
// Vertical
y.domain([
d3.min(data, function(d) { return Math.min(d["New York"], d["San Francisco"]); }),
d3.max(data, function(d) { return Math.max(d["New York"], d["San Francisco"]); })
]);
//
// Append chart elements
//
// Add masks
// ------------------------------
svg.append("clipPath")
.attr("id", "clip-below")
.append("path")
.attr("d", area.y0(height));
svg.append("clipPath")
.attr("id", "clip-above")
.append("path")
.attr("d", area.y0(0));
svg.append("path")
.attr("class", "area mask-above")
.attr("clip-path", "url(#clip-above)")
.attr("fill", "#FF8A65")
.attr("d", area.y0(function(d) { return y(d["San Francisco"]); }));
svg.append("path")
.attr("class", "area mask-below")
.attr("clip-path", "url(#clip-below)")
.attr("fill", "#9CCC65")
.attr("d", area);
// Add line
svg.append("path")
.attr("class", "d3-line d3-line-medium")
.style("stroke", "#558B2F")
.attr("d", line);
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Temperature (ºF)");
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-line').attr("d", line);
// Bottom clip
svg.select('#clip-below path').attr("d", area.y0(height));
// Top clip
svg.select('#clip-above path').attr("d", area.y0(0));
// Top mask
svg.select('.mask-above').attr("d", area.y0(function(d) { return y(d["San Francisco"]); }))
// Bottom mask
svg.select('.mask-below').attr("d", area);
}
}
});
+213
View File
@@ -0,0 +1,213 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - area chart with missing data
*
* Demo d3.js area chart setup with tooltip and missing data
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
areaMissing('#d3-missing-data', 400);
// Chart setup
function areaMissing(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Data set
var data = d3.range(60).map(function(i) {
return {x: i / 59, y: i % 5 ? (Math.sin(i / 3) + 2) / 4 : null};
});
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Add tooltip
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return d.x;
});
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.datum(data)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(tip);
// Construct chart layout
// ------------------------------
// Line
var line = d3.svg.line()
.defined(function(d) { return d.y != null; })
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
// Area
var area = d3.svg.area()
.defined(line.defined())
.x(line.x())
.y1(line.y())
.y0(y(0));
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Chart elements
// ------------------------------
// Add area
svg.append("path")
.attr("class", "d3-area")
.attr("d", area)
.style("fill", "#81C784");
// Add line
svg.append("path")
.attr("class", "d3-line d3-line-medium")
.attr("d", line)
.style("stroke", "#43A047");
// Add dots
svg.selectAll(".d3-dot")
.data(data.filter(function(d) { return d.y; }))
.enter()
.append("circle")
.attr("class", "d3-dot")
.attr("cx", line.x())
.attr("cy", line.y())
.attr("r", 3)
.style("fill", "#fff")
.style("stroke", "#43A047")
.style("stroke-width", 1.5)
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-line').attr("d", line);
// Area path
svg.selectAll('.d3-area').attr("d", area);
// Dots
svg.selectAll('.d3-dot').attr("cx", line.x());
}
}
});
@@ -0,0 +1,180 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - small multiples chart
*
* Demo d3.js small multiples chart setup with .csv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
smallMultiples('#d3-small-multiples', 100);
// Chart setup
function smallMultiples(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 5, left: 10},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%b %Y").parse;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Construct chart layout
// ------------------------------
// Area
var area = d3.svg.area()
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.price); });
// Line
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.price); });
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/lines/lines_small_multiples.csv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.price = +d.price;
d.date = parseDate(d.date);
})
// Nest data by symbol
var symbols = d3.nest()
.key(function(d) { return d.symbol; })
.entries(data);
// Compute the maximum price per symbol, needed for the y-domain.
symbols.forEach(function(s) {
s.maxPrice = d3.max(s.values, function(d) { return d.price; });
});
// Compute the minimum and maximum date across symbols.
// We assume values are sorted by date.
x.domain([
d3.min(symbols, function(s) { return s.values[0].date; }),
d3.max(symbols, function(s) { return s.values[s.values.length - 1].date; })
]);
// Create chart
// ------------------------------
// Add SVG elements
var svg = d3Container.selectAll("svg")
.data(symbols)
.enter()
.append("svg")
.attr("class", "multiples")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//
// Append chart elements
//
// Add area
svg.append("path")
//.attr("class", function(d) {return d.key.toLowerCase();})
.attr("d", function(d) { y.domain([0, d.maxPrice]); return area(d.values); })
.attr("class", "d3-area")
.style("fill", "#81D4FA");
// Add line
svg.append("path")
.attr("d", function(d) { y.domain([0, d.maxPrice]); return line(d.values); })
.attr("class", "d3-line")
.style("stroke", "rgba(0,0,0,0.5)");
// Add name label
svg.append("text")
.attr("class", "multiples-label")
.attr("x", width - 8)
.attr("y", height - 8)
.style("fill", "#fff")
.style("text-anchor", "end")
.style("text-weight", 500)
.text(function(d) { return d.key; });
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Resize all multiples
d3.selectAll(".multiples").attr("width", width + margin.left + margin.right);
// Horizontal range
x.range([0, width]);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-line').attr("d", function(d) { y.domain([0, d.maxPrice]); return line(d.values); })
// Area path
svg.selectAll('.d3-area').attr("d", function(d) { y.domain([0, d.maxPrice]); return area(d.values); });
// Text label
svg.selectAll('.multiples-label').attr("x", width - 8);
}
});
}
});
@@ -0,0 +1,208 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - spline transition
*
* Demo d3.js line chart setup with spline transition
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
splineTrransition('#d3-spline-transition', 400);
// Chart setup
function splineTrransition(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 5, bottom: 5, left: 30},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Add data
var n = 50,
random = d3.random.normal(0, .35),
data = d3.range(n).map(random);
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.domain([1, n - 2])
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.domain([-1, 1])
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Line
var line = d3.svg.line()
.interpolate("basis")
.x(function(d, i) { return x(i); })
.y(function(d, i) { return y(d); });
//
// Append chart elements
//
// Add mask
svg.append("defs")
.append("clipPath")
.attr("id", "transition-clip")
.append("rect")
.attr("width", width)
.attr("height", height);
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + y(0) + ")")
.call(xAxis);
// Vertical
svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add line
var path = svg.append("g")
.attr("clip-path", "url(#transition-clip)")
.append("path")
.datum(data)
.attr("d", line)
.attr("class", "d3-line d3-line-medium")
.style("stroke", "#607D8B");
// Transition
// ------------------------------
// Initialize transition
tick();
// Setup transition
function tick() {
// push a new data point onto the back
data.push(random());
// redraw the line, and slide it to the left
path
.attr("d", line)
.attr("transform", null)
.transition()
.duration(500)
.ease("linear")
.attr("transform", "translate(" + x(0) + ",0)")
.each("end", tick);
// pop the old data point off the front
data.shift();
}
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-line').attr("d", line);
// Crosshair
svg.selectAll('#transition-clip rect').attr("width", width);
}
}
});
+259
View File
@@ -0,0 +1,259 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - line chart with chained transitions
*
* Demo d3.js line chart setup with chained transitions and .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Create Uniform checkbox
$(".chained").uniform({
radioClass: 'choice',
wrapperClass: 'border-teal'
});
// Initialize chart
chainedTransitions('#d3-chained-transitions', 400);
// Chart setup
function chainedTransitions(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 90, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// City name
var city = "New York";
// Format data
parseDate = d3.time.format("%Y%m%d").parse;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(6)
.tickFormat(d3.time.format("%b"));
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Line
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d[city]); });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/lines/lines_transitions.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
d["New York"] = +d["New York"];
d["San Francisco"] = +d["San Francisco"];
});
// Set input domains
// ------------------------------
// Horizontal
x.domain([data[0].date, data[data.length - 1].date]);
// Vertical
y.domain(d3.extent(data, function(d) { return d[city]; }));
//
// Append chart elements
//
// Add line
svg.append("path")
.datum(data)
.attr("d", line)
.attr("class", "d3-line d3-line-medium")
.style("stroke", "#FF5722");
// Add text
svg.append("text")
.datum(data[data.length - 1])
.attr("class", "d3-city")
.attr("transform", transform)
.attr("x", 3)
.attr("dy", ".35em")
.text(city);
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Temperature (ºF)");
// Transitions
// ------------------------------
// Do stuff on value change
d3.selectAll(".chained").on("change", change);
// Set timeout for auto change
var timeout = setTimeout(function() {
d3.select("input[value=\"San Francisco\"]").property("checked", true).each(change);
$.uniform.update();
}, 3000);
// Change function
function change() {
clearTimeout(timeout);
city = this.value;
// First transition the line & label to the new city.
var t0 = svg.transition().duration(750);
t0.selectAll(".d3-line").attr("d", line);
t0.selectAll(".d3-city").attr("transform", transform).text(city);
// Then transition the y-axis.
y.domain(d3.extent(data, function(d) { return d[city]; }));
var t1 = t0.transition();
t1.selectAll(".d3-line").attr("d", line);
t1.selectAll(".d3-city").attr("transform", transform);
t1.selectAll(".d3-axis-vertical").call(yAxis);
}
// Transform text
function transform(d) {
return "translate(" + x(d.date) + "," + y(d[city]) + ")";
}
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-line').attr("d", line);
// Text
svg.selectAll(".d3-city").attr("transform", transform);
}
});
}
});
+265
View File
@@ -0,0 +1,265 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - line chart with pan and zoom
*
* Demo d3.js line chart setup with pan and zoom
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
panZoom('#d3-pan-zoom', 400);
// Chart setup
function panZoom(element, height) {
// Basic setup
// ------------------------------
// Demo data set
var data = [
[{'x':1,'y':0},{'x':2,'y':5},{'x':3,'y':10},{'x':4,'y':0},{'x':5,'y':6},{'x':6,'y':11},{'x':7,'y':9},{'x':8,'y':4},{'x':9,'y':11},{'x':10,'y':2}],
[{'x':1,'y':1},{'x':2,'y':6},{'x':3,'y':11},{'x':4,'y':1},{'x':5,'y':7},{'x':6,'y':12},{'x':7,'y':8},{'x':8,'y':3},{'x':9,'y':13},{'x':10,'y':3}],
[{'x':1,'y':2},{'x':2,'y':7},{'x':3,'y':12},{'x':4,'y':2},{'x':5,'y':8},{'x':6,'y':13},{'x':7,'y':7},{'x':8,'y':2},{'x':9,'y':4},{'x':10,'y':7}]
];
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Colors
var colors = ['#EF5350', '#5C6BC0', '#66BB6A']
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.domain([0, 11])
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.domain([-1, 14])
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.tickSize(-height)
.tickPadding(10)
.tickSubdivide(true)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.tickPadding(10)
.tickSize(-width)
.tickSubdivide(true)
.orient("left");
// Add zoom
// ------------------------------
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, 10])
.on("zoom", zoomed);
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.call(zoom)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Line
var line = d3.svg.line()
.interpolate("monotone")
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong d3-grid")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong d3-grid")
.call(yAxis);
// Append line
// ------------------------------
// Add clip path
svg.append("clipPath")
.attr("id", "zoom-clip")
.append("rect")
.attr("width", width)
.attr("height", height);
// Add line
var path = svg.selectAll('.d3-line')
.data(data)
.enter()
.append("path")
.attr("d", line)
.attr("class", "d3-line d3-line-medium")
.attr("clip-path", "url(#zoom-clip)")
.style('stroke', function(d,i){
return colors[i%colors.length];
});
// Append dots
// ------------------------------
// Group dots
var points = svg.selectAll('.d3-dots')
.data(data)
.enter()
.append("g")
.attr("class", "d3-dots")
.attr("clip-path", "url(#clip)");
// Add dots
points.selectAll('.d3-dot')
.data(function(d, index) {
var a = [];
d.forEach(function(point,i) {
a.push({'index': index, 'point': point});
});
return a;
})
.enter()
.append('circle')
.attr('class', 'd3-dot')
.attr("r", 3)
.attr("transform", function(d) {
return "translate(" + x(d.point.x) + "," + y(d.point.y) + ")"; }
)
.style("fill", "#fff")
.style("stroke-width", 2)
.style('stroke', function(d,i){
return colors[d.index%colors.length];
})
.style("cursor", "pointer");
// Update elements on zoom
// ------------------------------
function zoomed() {
svg.select(".d3-axis-horizontal").call(xAxis);
svg.select(".d3-axis-vertical").call(yAxis);
svg.selectAll('.d3-line').attr('d', line);
points.selectAll('.d3-dot').attr("transform", function(d) {
return "translate(" + x(d.point.x) + "," + y(d.point.y) + ")"; }
);
}
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
svg.selectAll('.d3-axis-vertical').call(yAxis.tickSize(-width));
// Chart elements
// -------------------------
// Mask
svg.select('#zoom-clip rect').attr("width", width);
// Line path
svg.selectAll('.d3-line').attr("d", line);
// Dots
points.selectAll('.d3-dot').attr("transform", function(d) {
return "translate(" + x(d.point.x) + "," + y(d.point.y) + ")"; }
);
}
}
});
+257
View File
@@ -0,0 +1,257 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - basic line chart
*
* Demo d3.js line chart setup with tooltip and .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
lineBasic('#d3-line-basic', 400);
// Chart setup
function lineBasic(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%d-%b-%y").parse,
bisectDate = d3.bisector(function(d) { return d.date; }).left,
formatValue = d3.format(",.2f"),
formatCurrency = function(d) { return "$" + formatValue(d); }
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(6)
.tickFormat(d3.time.format("%b"));
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Line
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/lines/lines_basic.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// Sort data
data.sort(function(a, b) {
return a.date - b.date;
});
// Set input domains
// ------------------------------
// Horizontal
x.domain(d3.extent(data, function(d) { return d.date; }));
// Vertical
y.domain([0, d3.max(data, function(d) { return d.close; })]);
//
// Append chart elements
//
// Add line
svg.append("path")
.datum(data)
.attr("class", "d3-line d3-line-medium")
.attr("d", line)
.style("fill", "none")
.style("stroke-width", 2)
.style("stroke", "#4CAF50");
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Price ($)");
// Append tooltip
// -------------------------
// Group elements
var focus = svg.append("g")
.attr("class", "d3-crosshair-pointer")
.style("display", "none");
// Pointer
focus.append("circle")
.attr("r", 3.5)
.style("fill", "#fff")
.style("stroke", "#4CAF50")
.style("stroke-width", 2);
// Text
focus.append("text")
.attr("dy", ".35em")
.style("fill", "#333")
.style("stroke", "none")
// Overlay
svg.append("rect")
.attr("class", "d3-crosshair-overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function() { focus.style("display", null); })
.on("mouseout", function() { focus.style("display", "none"); })
.on("mousemove", mousemove);
// Display tooltip on mousemove
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
focus.attr("transform", "translate(" + x(d.date) + "," + y(d.close) + ")");
focus.select("text").text(formatCurrency(d.close)).attr("dx", -26).attr("dy", 30);
}
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-line').attr("d", line);
// Crosshair
svg.selectAll('.d3-crosshair-overlay').attr("width", width);
}
}
});
+201
View File
@@ -0,0 +1,201 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - basic area chart
*
* Demo d3.js area chart setup with .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
areaBasic('#d3-area-basic', 400);
// Chart setup
function areaBasic(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%d-%b-%y").parse;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(6)
.tickFormat(d3.time.format("%b"));
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Area
var area = d3.svg.area()
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.close); });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/lines/lines_basic.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// Set input domains
// ------------------------------
// Horizontal
x.domain(d3.extent(data, function(d) { return d.date; }));
// Vertical
y.domain([0, d3.max(data, function(d) { return d.close; })]);
//
// Append chart elements
//
// Add area
svg.append("path")
.datum(data)
.attr("class", "d3-area")
.attr("fill", "#29B6F6")
.attr("d", area);
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("fill", "#999")
.style("font-size", 12)
.style("text-anchor", "end")
.text("Price ($)");
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Area path
svg.selectAll('.d3-area').attr("d", area);
}
}
});
+201
View File
@@ -0,0 +1,201 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - bivariate area chart
*
* Demo d3.js bivariate area chart setup with .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
areaBivariate('#d3-area-bivariate', 400);
// Chart setup
function areaBivariate(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%Y%m%d").parse;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(6)
.tickFormat(d3.time.format("%b"));
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Area
var area = d3.svg.area()
.x(function(d) { return x(d.date); })
.y0(function(d) { return y(d.low); })
.y1(function(d) { return y(d.high); });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/lines/lines_bivariate.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
d.low = +d.low;
d.high = +d.high;
});
// Set input domains
// ------------------------------
// Horizontal
x.domain(d3.extent(data, function(d) { return d.date; }));
// Vertical
y.domain([d3.min(data, function(d) { return d.low; }), d3.max(data, function(d) { return d.high; })]);
//
// Append chart elements
//
// Add area
svg.append("path")
.datum(data)
.attr("class", "d3-area")
.attr("fill", "#FF7043")
.attr("d", area);
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("fill", "#999")
.style("font-size", 12)
.style("text-anchor", "end")
.text("Temperature (ºF)");
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Area path
svg.selectAll('.d3-area').attr("d", area);
}
}
});
+220
View File
@@ -0,0 +1,220 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - gradient encoding line chart
*
* Demo d3.js gradient encoding line chart setup with .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
lineGradient('#d3-line-gradient', 400);
// Chart setup
function lineGradient(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%Y%m%d").parse;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(7)
.tickFormat(d3.time.format("%b"));
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Line
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.temperature); });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/lines/lines_gradient.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
d.temperature = +d.temperature;
});
// Set input domains
// ------------------------------
// Horizontal
x.domain([data[0].date, data[data.length - 1].date]);
// Vertical
y.domain(d3.extent(data, function(d) { return d.temperature; }));
//
// Append chart elements
//
// Add gradient
svg.append("linearGradient")
.attr("id", "temperature-gradient")
.attr("gradientUnits", "userSpaceOnUse")
.attr("x1", 0)
.attr("y1", y(50))
.attr("x2", 0)
.attr("y2", y(60))
.selectAll("stop")
.data([
{offset: "0%", color: "#4CAF50"},
{offset: "50%", color: "#81C784"},
{offset: "100%", color: "#FF5722"}
])
.enter()
.append("stop")
.attr("offset", function(d) { return d.offset; })
.attr("stop-color", function(d) { return d.color; });
// Add line
svg.append("path")
.datum(data)
.attr("class", "d3-line d3-line-medium")
.attr("fill", "none")
.attr("stroke", "url(#temperature-gradient)")
.attr("stroke-width", 2)
.attr("d", line);
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Temperature (ºF)");
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-line').attr("d", line);
}
}
});
+242
View File
@@ -0,0 +1,242 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - multi series line chart
*
* Demo d3.js multi series line chart setup with .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
lineBasic('#d3-line-multi-series', 400);
// Chart setup
function lineBasic(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 100, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%Y%m%d").parse;
// Colors
var color = d3.scale.category10();
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5)
.tickFormat(d3.time.format("%b"));
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Line
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.temperature); });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/lines/lines_multi_series.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
});
// Set color domains
// ------------------------------
// Filter by date
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
// Set colors
var cities = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, temperature: +d[name]};
})
}
});
// Set input domains
// ------------------------------
// Horizontal
x.domain(d3.extent(data, function(d) { return d.date; }));
// Vertical
y.domain([
d3.min(cities, function(c) { return d3.min(c.values, function(v) { return v.temperature; }); }),
d3.max(cities, function(c) { return d3.max(c.values, function(v) { return v.temperature; }); })
]);
//
// Append chart elements
//
// Bind data
var city = svg.selectAll(".multiline-city")
.data(cities)
.enter()
.append("g")
.attr("class", "multiline-city");
// Add line
city.append("path")
.attr("class", "d3-line d3-line-medium")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
// Add text
city.append("text")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")"; })
.attr("class", "d3-cities")
.attr("x", 10)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Add text label
verticalAxis.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 10)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Temperature (ºF)");
})
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-line').attr("d", function(d) { return line(d.values); });
// Text
svg.selectAll('.d3-cities').attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")"; })
}
}
});
+232
View File
@@ -0,0 +1,232 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - stacked area chart
*
* Demo d3.js stacked area chart setup with .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
areaStacked('#d3-area-stacked', 400);
// Chart setup
function areaStacked(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 20, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%y-%b-%d").parse,
formatPercent = d3.format(".0%");
// Colors
var color = d3.scale.category20();
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(6)
.tickFormat(d3.time.format("%b"));
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(formatPercent);
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Area
var area = d3.svg.area()
.x(function(d) { return x(d.date); })
.y0(function(d) { return y(d.y0); })
.y1(function(d) { return y(d.y0 + d.y); });
// Stack
var stack = d3.layout.stack()
.values(function(d) { return d.values; });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/lines/lines_stacked.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
});
// Set color domains
// ------------------------------
// Filter by date
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
// Set colors
var browsers = stack(color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, y: d[name] / 100};
})
};
}));
// Set input domains
// ------------------------------
// Horizontal
x.domain(d3.extent(data, function(d) { return d.date; }));
//
// Append chart elements
//
// Bind data
var browser = svg.selectAll(".browser")
.data(browsers)
.enter()
.append("g")
.attr("class", "browser");
// Add area
browser.append("path")
.attr("class", "d3-area")
.attr("d", function(d) { return area(d.values); })
.style("fill", function(d) { return color(d.name); });
// Add text
browser.append("text")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.y0 + d.value.y / 2) + ")"; })
.attr("class", "d3-browsers")
.attr("x", -15)
.attr("dy", ".35em")
.style("fill", "#fff")
.style("text-anchor", "end")
.text(function(d) { return d.name; });
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-area').attr("d", function(d) { return area(d.values); });
// Text
svg.selectAll('.d3-browsers').attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.y0 + d.value.y / 2) + ")"; });
}
}
});
+214
View File
@@ -0,0 +1,214 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - stacked nested area chart
*
* Demo d3.js stacked nested area chart setup with .tsv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
areaNested('#d3-area-stacked-nest', 400);
// Chart setup
function areaNested(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 40},
n = 3,
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var format = d3.time.format("%m/%d/%y");
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale()
.range([0, width]);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Colors
var z = d3.scale.linear()
.domain([0, n - 1])
.range(["#4DB6AC", "#B2DFDB"]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.days);
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Stack
var stack = d3.layout.stack()
.offset("zero")
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.value; });
// Nest
var nest = d3.nest()
.key(function(d) { return d.key; });
// Area
var area = d3.svg.area()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y0(function(d) { return y(d.y0); })
.y1(function(d) { return y(d.y0 + d.y); });
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/lines/lines_stacked_nest.csv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = format.parse(d.date);
d.value = +d.value;
});
// Pull out nested entries
var layers = stack(nest.entries(data));
// Set input domains
// ------------------------------
// Horizontal
x.domain(d3.extent(data, function(d) { return d.date; }));
// Vertical
y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);
//
// Append chart elements
//
// Add area
svg.selectAll(".d3-area")
.data(layers)
.enter()
.append("path")
.attr("class", "d3-area")
.attr("d", function(d) { return area(d.values); })
.style("stroke", "#fff")
.style("stroke-width", 0.5)
.style("fill", function(d, i) { return z(i); });
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Vertical
svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.range([0, width]);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-area').attr("d", function(d) { return area(d.values); })
}
}
});
+118
View File
@@ -0,0 +1,118 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - bubble chart
*
* Demo of a bubble chart setup with tooltip and .json data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
bubbles('#d3-bubbles', 700);
// Chart setup
function bubbles(element, diameter) {
// Basic setup
// ------------------------------
// Format data
var format = d3.format(",d");
// Color scale
color = d3.scale.category10();
// Create chart
// ------------------------------
var svg = d3.select(element).append("svg")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
// Create chart
// ------------------------------
// Add tooltip
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-5, 0])
.html(function(d) {
return d.className + ": " + format(d.value);;
});
// Initialize tooltip
svg.call(tip);
// Construct chart layout
// ------------------------------
// Pack
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/other/bubble.json", function(error, root) {
//
// Append chart elements
//
// Bind data
var node = svg.selectAll(".d3-bubbles-node")
.data(bubble.nodes(classes(root))
.filter(function(d) { return !d.children; }))
.enter()
.append("g")
.attr("class", "d3-bubbles-node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
// Append circles
node.append("circle")
.attr("r", function(d) { return d.r; })
.style("fill", function(d) { return color(d.packageName); })
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
// Append text
node.append("text")
.attr("dy", ".3em")
.style("fill", "#fff")
.style("font-size", 12)
.style("text-anchor", "middle")
.text(function(d) { return d.className.substring(0, d.r / 3); });
});
// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
else classes.push({packageName: name, className: node.name, value: node.size});
}
recurse(null, root);
return {children: classes};
}
}
});
+451
View File
@@ -0,0 +1,451 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - streamgraph
*
* Demo of streamgraph chart setup with tooltip and .csv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
streamgraph('#d3-streamgraph', 400); // initialize chart
// Chart setup
function streamgraph(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 50, bottom: 40, left: 50},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom,
tooltipOffset = 30;
// Tooltip
var tooltip = d3Container
.append("div")
.attr("class", "d3-tip e")
.style("display", "none")
// Format date
var format = d3.time.format("%m/%d/%y %H:%M");
var formatDate = d3.time.format("%H:%M");
// Colors
var colorrange = ['#03A9F4', '#29B6F6', '#4FC3F7', '#81D4FA', '#B3E5FC', '#E1F5FE'];
// Construct scales
// ------------------------------
// Horizontal
var x = d3.time.scale().range([0, width]);
// Vertical
var y = d3.scale.linear().range([height, 0]);
// Colors
var z = d3.scale.ordinal().range(colorrange);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.hours, 4)
.innerTickSize(4)
.tickPadding(8)
.tickFormat(d3.time.format("%H:%M")); // Display hours and minutes in 24h format
// Left vertical
var yAxis = d3.svg.axis()
.scale(y)
.ticks(6)
.innerTickSize(4)
.outerTickSize(0)
.tickPadding(8)
.tickFormat(function (d) { return (d/1000) + "k"; });
// Right vertical
var yAxis2 = yAxis;
// Dash lines
var gridAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(6)
.tickPadding(8)
.tickFormat("")
.tickSize(-width, 0, 0);
// Create chart
// ------------------------------
// Container
var container = d3Container.append("svg")
// SVG element
var svg = container
.attr('width', width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Stack
var stack = d3.layout.stack()
.offset("silhouette")
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.value; });
// Nest
var nest = d3.nest()
.key(function(d) { return d.key; });
// Area
var area = d3.svg.area()
.interpolate("cardinal")
.x(function(d) { return x(d.date); })
.y0(function(d) { return y(d.y0); })
.y1(function(d) { return y(d.y0 + d.y); });
// Load data
// ------------------------------
d3.csv("assets/demo_data/dashboard/traffic_sources.csv", function (error, data) {
// Pull out values
data.forEach(function (d) {
d.date = format.parse(d.date);
d.value = +d.value;
});
// Stack and nest layers
var layers = stack(nest.entries(data));
// Set input domains
// ------------------------------
// Horizontal
x.domain(d3.extent(data, function(d, i) { return d.date; }));
// Vertical
y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);
// Add grid
// ------------------------------
// Horizontal grid. Must be before the group
svg.append("g")
.attr("class", "d3-grid-dashed")
.call(gridAxis);
//
// Append chart elements
//
// Stream layers
// ------------------------------
// Create group
var group = svg.append('g')
.attr('class', 'streamgraph-layers-group');
// And append paths to this group
var layer = group.selectAll(".streamgraph-layer")
.data(layers)
.enter()
.append("path")
.attr("class", "streamgraph-layer")
.attr("d", function(d) { return area(d.values); })
.style('stroke', '#fff')
.style('stroke-width', 0.5)
.style("fill", function(d, i) { return z(i); });
// Add transition
var layerTransition = layer
.style('opacity', 0)
.transition()
.duration(750)
.delay(function(d, i) { return i * 50; })
.style('opacity', 1)
// Append axes
// ------------------------------
//
// Left vertical
//
svg.append("g")
.attr("class", "d3-axis d3-axis-left d3-axis-solid")
.call(yAxis.orient("left"));
// Hide first tick
d3.select(svg.selectAll('.d3-axis-left .tick text')[0][0])
.style("visibility", "hidden");
//
// Right vertical
//
svg.append("g")
.attr("class", "d3-axis d3-axis-right d3-axis-solid")
.attr("transform", "translate(" + width + ", 0)")
.call(yAxis2.orient("right"));
// Hide first tick
d3.select(svg.selectAll('.d3-axis-right .tick text')[0][0])
.style("visibility", "hidden");
//
// Horizontal
//
var xaxisg = svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-solid")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add extra subticks for hidden hours
xaxisg.selectAll(".d3-axis-subticks")
.data(x.ticks(d3.time.hours), function(d) { return d; })
.enter()
.append("line")
.attr("class", "d3-axis-subticks")
.attr("y1", 0)
.attr("y2", 4)
.attr("x1", x)
.attr("x2", x);
// Add hover line and pointer
// ------------------------------
// Append group to the group of paths to prevent appearance outside chart area
var hoverLineGroup = group.append("g")
.attr("class", "hover-line");
// Add line
var hoverLine = hoverLineGroup
.append("line")
.attr("y1", 0)
.attr("y2", height)
.style('fill', 'none')
.style('stroke', '#fff')
.style('stroke-width', 1)
.style('pointer-events', 'none')
.style('shape-rendering', 'crispEdges')
.style("opacity", 0);
// Add pointer
var hoverPointer = hoverLineGroup
.append("rect")
.attr("x", 2)
.attr("y", 2)
.attr("width", 6)
.attr("height", 6)
.style('fill', '#03A9F4')
.style('stroke', '#fff')
.style('stroke-width', 1)
.style('shape-rendering', 'crispEdges')
.style('pointer-events', 'none')
.style("opacity", 0);
// Append events to the layers group
// ------------------------------
layerTransition.each("end", function() {
layer
.on("mouseover", function (d, i) {
svg.selectAll(".streamgraph-layer")
.transition()
.duration(250)
.style("opacity", function (d, j) {
return j != i ? 0.75 : 1; // Mute all except hovered
});
})
.on("mousemove", function (d, i) {
mouse = d3.mouse(this);
mousex = mouse[0];
mousey = mouse[1];
datearray = [];
var invertedx = x.invert(mousex);
invertedx = invertedx.getHours();
var selected = (d.values);
for (var k = 0; k < selected.length; k++) {
datearray[k] = selected[k].date
datearray[k] = datearray[k].getHours();
}
mousedate = datearray.indexOf(invertedx);
pro = d.values[mousedate].value;
// Display mouse pointer
hoverPointer
.attr("x", mousex - 3)
.attr("y", mousey - 6)
.style("opacity", 1);
hoverLine
.attr("x1", mousex)
.attr("x2", mousex)
.style("opacity", 1);
//
// Tooltip
//
// Tooltip data
tooltip.html(
"<ul class='list-unstyled mb-5'>" +
"<li>" + "<div class='text-size-base mt-5 mb-5'><i class='icon-circle-left2 position-left'></i>" + d.key + "</div>" + "</li>" +
"<li>" + "Visits: &nbsp;" + "<span class='text-semibold pull-right'>" + pro + "</span>" + "</li>" +
"<li>" + "Time: &nbsp; " + "<span class='text-semibold pull-right'>" + formatDate(d.values[mousedate].date) + "</span>" + "</li>" +
"</ul>"
)
.style("display", "block");
// Tooltip arrow
tooltip.append('div').attr('class', 'd3-tip-arrow');
})
.on("mouseout", function (d, i) {
// Revert full opacity to all paths
svg.selectAll(".streamgraph-layer")
.transition()
.duration(250)
.style("opacity", 1);
// Hide cursor pointer
hoverPointer.style("opacity", 0);
// Hide tooltip
tooltip.style("display", "none");
hoverLine.style("opacity", 0);
});
});
// Append events to the chart container
// ------------------------------
d3Container
.on("mousemove", function (d, i) {
mouse = d3.mouse(this);
mousex = mouse[0];
mousey = mouse[1];
// Display hover line
//.style("opacity", 1);
// Move tooltip vertically
tooltip.style("top", (mousey - ($('.d3-tip').outerHeight() / 2)) - 2 + "px") // Half tooltip height - half arrow width
// Move tooltip horizontally
if(mousex >= ($(element).outerWidth() - $('.d3-tip').outerWidth() - margin.right - (tooltipOffset * 2))) {
tooltip
.style("left", (mousex - $('.d3-tip').outerWidth() - tooltipOffset) + "px") // Change tooltip direction from right to left to keep it inside graph area
.attr("class", "d3-tip w");
}
else {
tooltip
.style("left", (mousex + tooltipOffset) + "px" )
.attr("class", "d3-tip e");
}
});
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resizeStream);
// Call function on sidebar width change
$('.sidebar-control').on('click', resizeStream);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resizeStream() {
// Layout
// -------------------------
// Define width
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Horizontal range
x.range([0, width]);
// Chart elements
// -------------------------
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Horizontal axis subticks
svg.selectAll('.d3-axis-subticks').attr("x1", x).attr("x2", x);
// Grid lines width
svg.selectAll(".d3-grid-dashed").call(gridAxis.tickSize(-width, 0, 0))
// Right vertical axis
svg.selectAll(".d3-axis-right").attr("transform", "translate(" + width + ", 0)");
// Area paths
svg.selectAll('.streamgraph-layer').attr("d", function(d) { return area(d.values); });
}
}
});
+212
View File
@@ -0,0 +1,212 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - zoomable treemap
*
* Demo of treemap setup with zoom and .json data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Create Uniform checkbox
$(".treemap_actions").uniform({
radioClass: 'choice'
});
// Initialize chart
treemap('#d3-treemap', 800);
// Chart setup
function treemap(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
width = d3Container.node().getBoundingClientRect().width,
root,
node;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.range([0, width]);
// Vertical
var y = d3.scale.linear().range([0, height]);
// Colors
var color = d3.scale.category20();
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(.5,.5)")
.style("font-size", 12)
.style("overflow", "hidden")
.style("text-indent", 2);
// Construct chart layout
// ------------------------------
// Treemap
var treemap = d3.layout.treemap()
.round(false)
.size([width, height])
.sticky(true)
.value(function(d) { return d.size; });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/other/treemap.json", function(data) {
node = root = data;
var nodes = treemap.nodes(root)
.filter(function(d) { return !d.children; });
// Add cells
// ------------------------------
// Bind data
var cell = svg.selectAll(".d3-treemap-cell")
.data(nodes)
.enter()
.append("g")
.attr("class", "d3-treemap-cell")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.style("cursor", "pointer")
.on("click", function(d) { return zoom(node == d.parent ? root : d.parent); });
// Append cell rects
cell.append("rect")
.attr("width", function(d) { return d.dx - 1; })
.attr("height", function(d) { return d.dy - 1; })
.style("fill", function(d, i) { return color(i); });
// Append text
cell.append("text")
.attr("x", function(d) { return d.dx / 2; })
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("fill", "#fff")
.style("opacity", function(d) { d.width = this.getComputedTextLength(); return d.dx > d.width ? 1 : 0; });
});
// Change data
// ------------------------------
d3.selectAll(".treemap_actions").on("change", change);
// Change data function
function change() {
treemap.value(this.value == "size" ? size : count).nodes(root);
zoom(node);
}
// Size
function size(d) {
return d.size;
}
// Count
function count(d) {
return 1;
}
// Zoom
function zoom(d) {
var kx = width / d.dx, ky = height / d.dy;
x.domain([d.x, d.x + d.dx]);
y.domain([d.y, d.y + d.dy]);
// Cell transition
var t = svg.selectAll(".d3-treemap-cell").transition()
.duration(500)
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
// Cell rect transition
t.select("rect")
.attr("width", function(d) { return kx * d.dx - 1; })
.attr("height", function(d) { return ky * d.dy - 1; })
// Text transition
t.select("text")
.attr("x", function(d) { return kx * d.dx / 2; })
.attr("y", function(d) { return ky * d.dy / 2; })
.style("opacity", function(d) { return kx * d.dx > d.width ? 1 : 0; });
node = d;
d3.event.stopPropagation();
}
// Add click event
d3.select(window).on("click", function() { zoom(root); });
// Resize chart
// ------------------------------
// Call function on window resize
d3.select(window).on('resize', resize);
// Call function on sidebar width change
d3.select('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width;
// Layout
// -------------------------
// Main svg width
container.attr("width", width);
// Width of appended group
svg.attr("width", width);
// Horizontal range
x.range([0, width]);
// Redraw chart
zoom(root);
}
}
});
+250
View File
@@ -0,0 +1,250 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - waterfall chart
*
* Demo of waterfall chart setup with .csv data source and rotated axis labels
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
waterfall('#d3-waterfall', 400); // initialize chart
// Chart setup
function waterfall(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 10, bottom: 100, left: 50},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom,
padding = 0.3;
// Format data
function dollarFormatter(n) {
n = Math.round(n);
var result = n;
if (Math.abs(n) > 1000) {
result = Math.round(n/1000) + 'K';
}
return '$' + result;
}
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], padding);
// Vertical
var y = d3.scale.linear()
.range([height, 0]);
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(function(d) { return dollarFormatter(d); });
// Create chart
// ------------------------------
// Container
var container = d3Container.append("svg")
// SVG element
var svg = container
.attr('width', width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/other/waterfall.csv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.value = +d.value;
});
// Transform data (i.e., finding cumulative values and total) for easier charting
var cumulative = 0;
for (var i = 0; i < data.length; i++) {
data[i].start = cumulative;
cumulative += data[i].value;
data[i].end = cumulative;
data[i].class = ( data[i].value >= 0 ) ? 'positive' : 'negative'
}
data.push({
name: 'Total',
end: cumulative,
start: 0,
class: 'total'
});
// Set input domains
// ------------------------------
// Horizontal
x.domain(data.map(function(d) { return d.name; }));
// Vertical
y.domain([0, d3.max(data, function(d) { return d.end; })]);
//
// Append chart elements
//
// Append axes
// ------------------------------
// Horizontal
svg.append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-15px")
.attr("dy", "-6px")
.attr("transform", function(d) {
return "rotate(-90)"
});
// Vertical
svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Append bars
// ------------------------------
// Bind data
var bar = svg.selectAll(".d3-waterfall-bar")
.data(data)
.enter()
.append("g")
.attr("class", function(d) { return "d3-waterfall-bar " + d.class })
.attr("transform", function(d) { return "translate(" + x(d.name) + ",0)"; });
// Append bar rects
bar.append("rect")
.attr("y", function(d) { return y( Math.max(d.start, d.end) ); })
.attr("height", function(d) { return Math.abs( y(d.start) - y(d.end) ); })
.attr("width", x.rangeBand());
// Append text
bar.append("text")
.attr("x", x.rangeBand() / 2)
.attr("y", function(d) { return y(d.end) + 5; })
.attr("dy", function(d) { return ((d.class=='negative') ? '-' : '') + "1.5em" })
.style("fill", "#fff")
.style("text-anchor", "middle")
.text(function(d) { return dollarFormatter(d.end - d.start);});
// Apply colors
bar.filter(function(d) { return d.class == "positive" }).select('rect').style("fill", "#EF5350");
bar.filter(function(d) { return d.class == "negative" }).select('rect').style("fill", "#66BB6A");
bar.filter(function(d) { return d.class == "total" }).select('rect').style("fill", "#42A5F5");
// Add connector line
bar.filter(function(d) { return d.class != "total" })
.append("line")
.attr("class", "d3-waterfall-connector")
.attr("x1", x.rangeBand() + 5 )
.attr("y1", function(d) { return y(d.end) })
.attr("x2", x.rangeBand() / ( 1 - padding) - 5)
.attr("y2", function(d) { return y(d.end) })
.style("stroke", "#999")
.style("stroke-dasharray", 3);
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.rangeRoundBands([0, width], padding);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis).selectAll('text').style("text-anchor", "end").attr("dy", "-6px");
// Chart elements
// -------------------------
// Bar group
svg.selectAll(".d3-waterfall-bar").attr("transform", function(d) { return "translate(" + x(d.name) + ",0)"; });
// Bar rect
svg.selectAll(".d3-waterfall-bar rect").attr("width", x.rangeBand());
// Bar text
svg.selectAll(".d3-waterfall-bar text").attr("x", x.rangeBand() / 2);
// Connector line
svg.selectAll(".d3-waterfall-connector").attr("x1", x.rangeBand() + 5 ).attr("x2", x.rangeBand() / ( 1 - padding) - 5 );
}
}
});
+95
View File
@@ -0,0 +1,95 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - arc tween animation
*
* Demo d3.js demonstration of arc tween animation
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
donutTweenAnimation('#d3-donut-arc-tween', 120);
// Chart setup
function donutTweenAnimation(element, radius) {
// Basic setup
// ------------------------------
// Define main variables
var τ = 2 * Math.PI;
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius / 1.4)
.startAngle(0);
//
// Append chart elements
//
// Add the background arc, from 0 to 100% (τ).
var background = svg.append("path")
.datum({endAngle: τ})
.style("fill", "#eee")
.attr("d", arc);
// Add the foreground arc in orange, currently showing 12.7%.
var foreground = svg.append("path")
.datum({endAngle: .127 * τ})
.style("fill", "#7986CB")
.attr("d", arc);
// Start a transition to a new random angle
setInterval(function() {
foreground.transition()
.duration(750)
.call(arcTween, Math.random() * τ);
}, 1500);
// Creates a tween on the specified transition's "d" attribute, transitioning
// any selected arcs from their current angle to the specified new angle.
function arcTween(transition, newAngle) {
transition.attrTween("d", function(d) {
// Interpolate between the two angles
var interpolate = d3.interpolate(d.endAngle, newAngle);
// Return value of the attrTween
return function(t) {
// Calculate the current arc angle based on the transition time, t
d.endAngle = interpolate(t);
// Lastly, compute the arc path given the updated data
return arc(d);
};
});
}
}
});
+94
View File
@@ -0,0 +1,94 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - basic donut chart
*
* Demo d3.js donut chart setup with .csv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
donutBasic('#d3-donut-basic', 120);
// Chart setup
function donutBasic(element, radius) {
// Basic setup
// ------------------------------
// Colors
var color = d3.scale.category20();
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius / 1.75);
// Pie
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/pies/pies_basic.csv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.population = +d.population;
});
//
// Append chart elements
//
// Bind data
var g = svg.selectAll(".d3-arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "d3-arc");
// Add arc path
g.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return color(d.data.age); });
// Add text labels
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("fill", "#fff")
.style("font-size", 12)
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
});
}
});
+145
View File
@@ -0,0 +1,145 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - donut chart entry animation
*
* Demo d3.js donut chart setup with .csv data source and loading animation
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
donutEntryAnimation('#d3-donut-entry-animation', 120);
// Chart setup
function donutEntryAnimation(element, radius) {
// Basic setup
// ------------------------------
// Colors
var color = d3.scale.category20();
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius / 1.75);
// Pie
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/pies/pies_basic.csv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.population = +d.population;
});
//
// Append chart elements
//
// Bind data
var g = svg.selectAll(".d3-arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "d3-arc");
// Add arc path
g.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return color(d.data.age); })
.transition()
.ease("linear")
.duration(1000)
.attrTween("d", tweenPie);
// Add text labels
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("opacity", 0)
.style("fill", "#fff")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; })
.transition()
.ease("linear")
.delay(1000)
.duration(500)
.style("opacity", 1);
// Tween
function tweenPie(b) {
b.innerRadius = 0;
var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
return function(t) { return arc(i(t)); };
}
// Animate donut
// ------------------------------
$('.donut-animation').on('click', function (b) {
// Remove old paths
svg.selectAll("path").remove();
// Arc path
g.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return color(d.data.age); })
.transition()
.ease("linear")
.duration(1000)
.attrTween("d", tweenPie);
// Text labels
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.style("opacity", 0)
.style("fill", "#fff")
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; })
.transition()
.ease("linear")
.delay(1000)
.duration(500)
.style("opacity", 1);
});
});
}
});
+74
View File
@@ -0,0 +1,74 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - multiple donut charts
*
* Demo d3.js multiple donut charts setup
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
donutMultiple('#d3-donut-multiple', 110, 10);
// Chart setup
function donutMultiple(element, radius, margin) {
// Basic setup
// ------------------------------
// Define the data as a two-dimensional array of numbers
var data = [
[11975, 5871, 8916, 2868],
[ 1951, 10048, 2060, 6171],
[ 8010, 16145, 8090, 8045],
[ 1013, 990, 940, 6907]
];
// Colors
var colors = d3.scale.category10();
// Create chart
// ------------------------------
// Insert an svg element (with margin) for each row in our dataset
var svg = d3.select(element)
.selectAll("svg")
.data(data)
.enter()
.append("svg")
.attr("width", (radius + margin) * 2)
.attr("height", (radius + margin) * 2)
.append("g")
.attr("class", "d3-arc")
.attr("transform", "translate(" + (radius + margin) + "," + (radius + margin) + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.innerRadius(radius / 1.75)
.outerRadius(radius);
//
// Append chart elements
//
// The data for each svg element is a row of numbers (an array)
svg.selectAll("path")
.data(d3.layout.pie())
.enter()
.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d, i) { return colors(i); });
}
});
+115
View File
@@ -0,0 +1,115 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - multiple nested donut charts
*
* Demo d3.js multiple donut charts setup with nesting
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
donutMultipleNested('#d3-donut-nesting', 110, 10);
// Chart setup
function donutMultipleNested(element, radius, margin) {
// Basic setup
// ------------------------------
// Colors
var colors = d3.scale.category20c();
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/pies/pies_nesting.csv", function(flights) {
// Nest the flight data by originating airport
var airports = d3.nest()
.key(function(d) { return d.origin; })
.entries(flights);
// Create chart
// ------------------------------
// Insert an svg element (with margin) for each row in our dataset
var svg = d3.select(element)
.selectAll("svg")
.data(airports)
.enter()
.append("svg")
.attr("width", (radius + margin) * 2)
.attr("height", (radius + margin) * 2)
.append("g")
.attr("transform", "translate(" + (radius + margin) + "," + (radius + margin) + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.innerRadius(radius / 2)
.outerRadius(radius);
// Pie
var pie = d3.layout.pie()
.value(function(d) { return +d.count; })
.sort(function(a, b) { return b.count - a.count; });
//
// Append chart elements
//
// Add a label for the airport
svg.append("text")
.attr("dy", ".35em")
.style("text-anchor", "middle")
.style("font-weight", 500)
.text(function(d) { return d.key; });
// Pass the nested values to the pie layout
var g = svg.selectAll("g")
.data(function(d) { return pie(d.values); })
.enter()
.append("g")
.attr("class", "d3-arc");
// Add a colored arc path, with a mouseover title showing the count
g.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return colors(d.data.carrier); })
.append("title")
.text(function(d) { return d.data.carrier + ": " + d.data.count; });
// Add a label to the larger arcs, translated to the arc centroid and rotated.
g.filter(function(d) { return d.endAngle - d.startAngle > .2; }).append("text")
.attr("dy", ".35em")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")rotate(" + angle(d) + ")"; })
.style("fill", "#fff")
.style("font-size", 12)
.style("text-anchor", "middle")
.text(function(d) { return d.data.carrier; });
// Computes the label angle of an arc, converting from radians to degrees.
function angle(d) {
var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
return a > 90 ? a - 180 : a;
}
});
}
});
+120
View File
@@ -0,0 +1,120 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - donut chart update animation
*
* Demo d3.js donut chart setup with .tsv data source and update animation
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Create Uniform checkbox
$(".donut-radios input").uniform({
radioClass: 'choice'
});
// Initialize chart
pieUpdateAnimation('#d3-donut-update', 120);
// Chart setup
function pieUpdateAnimation(element, radius) {
// Basic setup
// ------------------------------
// Colors
var color = d3.scale.category20();
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius / 1.75);
// Pie
var pie = d3.layout.pie()
.value(function(d) { return d.lemons; })
.sort(null);
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/pies/donuts_update.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.lemons = +d.lemons || 0;
d.melons = +d.melons || 0;
});
//
// Append chart elements
//
// Bind data
var path = svg.datum(data).selectAll("path")
.data(pie)
.enter()
.append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc)
.style("stroke", "#fff")
.each(function(d) { this._current = d; }); // store the initial angles
// Apply change event
d3.selectAll(".donut-radios input").on("change", change);
// Change values on page load
var timeout = setTimeout(function() {
d3.select("input[value=\"melons\"]").property("checked", true).each(change);
$.uniform.update();
}, 2000);
// Change values
function change() {
var value = this.value;
clearTimeout(timeout);
pie.value(function(d) { return d[value]; }); // change the value function
path = path.data(pie); // compute the new angles
path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
}
});
// Store the displayed angles in _current.
// Then, interpolate from _current to the new angles.
// During the transition, _current is updated in-place by d3.interpolate.
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
}
});
+95
View File
@@ -0,0 +1,95 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - arc tween animation
*
* Demo d3.js demonstration of arc tween animation
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
pieTweenAnimation('#d3-pie-arc-tween', 120);
// Chart setup
function pieTweenAnimation(element, radius) {
// Basic setup
// ------------------------------
// Define main variables
var τ = 2 * Math.PI;
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(0)
.startAngle(0);
//
// Append chart elements
//
// Add the background arc, from 0 to 100% (τ).
var background = svg.append("path")
.datum({endAngle: τ})
.style("fill", "#f5f5f5")
.attr("d", arc);
// Add the foreground arc in orange, currently showing 12.7%.
var foreground = svg.append("path")
.datum({endAngle: .127 * τ})
.style("fill", "#81C784")
.attr("d", arc);
// Start a transition to a new random angle
setInterval(function() {
foreground.transition()
.duration(750)
.call(arcTween, Math.random() * τ);
}, 1500);
// Creates a tween on the specified transition's "d" attribute, transitioning
// any selected arcs from their current angle to the specified new angle.
function arcTween(transition, newAngle) {
transition.attrTween("d", function(d) {
// Interpolate between the two angles
var interpolate = d3.interpolate(d.endAngle, newAngle);
// Return value of the attrTween
return function(t) {
// Calculate the current arc angle based on the transition time, t
d.endAngle = interpolate(t);
// Lastly, compute the arc path given the updated data
return arc(d);
};
});
}
}
});
+94
View File
@@ -0,0 +1,94 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - basic pie chart
*
* Demo d3.js pie chart setup with .csv data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
pieBasic('#d3-pie-basic', 120);
// Chart setup
function pieBasic(element, radius) {
// Basic setup
// ------------------------------
// Colors
var color = d3.scale.category20();
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(0);
// Pie
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/pies/pies_basic.csv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.population = +d.population;
});
//
// Append chart elements
//
// Bind data
var g = svg.selectAll(".d3-arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "d3-arc");
// Add arc path
g.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return color(d.data.age); });
// Add text labels
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("fill", "#fff")
.style("font-size", 12)
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
});
}
});
+148
View File
@@ -0,0 +1,148 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - pie chart entry animation
*
* Demo d3.js pie chart setup with .csv data source and loading animation
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
pieEntryAnimation('#d3-pie-entry-animation', 120);
// Chart setup
function pieEntryAnimation(element, radius) {
// Basic setup
// ------------------------------
// Colors
var color = d3.scale.category20();
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(0);
// Pie
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/pies/pies_basic.csv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.population = +d.population;
});
//
// Append chart elements
//
// Bind data
var g = svg.selectAll(".d3-arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "d3-arc");
// Add arc path
g.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return color(d.data.age); })
.transition()
.ease("bounce")
.duration(2000)
.attrTween("d", tweenPie);
// Add text labels
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("opacity", 0)
.style("fill", "#fff")
.style("font-size", 12)
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; })
.transition()
.ease("linear")
.delay(2000)
.duration(500)
.style("opacity", 1)
// Tween
function tweenPie(b) {
b.innerRadius = 0;
var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
return function(t) { return arc(i(t));
};
}
// Animate pie
// ------------------------------
$('.pie-animation').on('click', function (b) {
// Remove old paths
svg.selectAll("path").remove();
// Arc path
g.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return color(d.data.age); })
.transition()
.ease("bounce")
.duration(2000)
.attrTween("d", tweenPie);
// Text labels
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("opacity", 0)
.style("fill", "#fff")
.style("font-size", 12)
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; })
.transition()
.ease("linear")
.delay(2000)
.duration(500)
.style("opacity", 1)
});
});
}
});
+74
View File
@@ -0,0 +1,74 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - multiple pie charts
*
* Demo d3.js multiple pie charts setup
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
pieMultiple('#d3-pie-multiple', 110, 10);
// Chart setup
function pieMultiple(element, radius, margin) {
// Basic setup
// ------------------------------
// Define the data as a two-dimensional array of numbers
var data = [
[11975, 5871, 8916, 2868],
[ 1951, 10048, 2060, 6171],
[ 8010, 16145, 8090, 8045],
[ 1013, 990, 940, 6907]
];
// Colors
var colors = d3.scale.category10();
// Create chart
// ------------------------------
// Insert an svg element (with margin) for each row in our dataset
var svg = d3.select(element)
.selectAll("svg")
.data(data)
.enter()
.append("svg")
.attr("width", (radius + margin) * 2)
.attr("height", (radius + margin) * 2)
.append("g")
.attr("class", "d3-arc")
.attr("transform", "translate(" + (radius + margin) + "," + (radius + margin) + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.innerRadius(0)
.outerRadius(radius);
//
// Append chart elements
//
// The data for each svg element is a row of numbers (an array)
svg.selectAll("path")
.data(d3.layout.pie())
.enter()
.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d, i) { return colors(i); });
}
});
+118
View File
@@ -0,0 +1,118 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - multiple nested pie charts
*
* Demo d3.js multiple pie charts setup with nesting
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
pieMultipleNested('#d3-pie-nesting', 110, 10);
// Chart setup
function pieMultipleNested(element, radius, margin) {
// Basic setup
// ------------------------------
// Main variables
var marginTop = 20;
// Colors
var colors = d3.scale.category20c();
// Load data
// ------------------------------
d3.csv("assets/demo_data/d3/pies/pies_nesting.csv", function(flights) {
// Nest the flight data by originating airport
var airports = d3.nest()
.key(function(d) { return d.origin; })
.entries(flights);
// Create chart
// ------------------------------
// Insert an svg element (with margin) for each row in our dataset
var svg = d3.select(element)
.selectAll("svg")
.data(airports)
.enter()
.append("svg")
.attr("width", (radius + margin) * 2)
.attr("height", (radius + margin + marginTop) * 2)
.append("g")
.attr("transform", "translate(" + (radius + margin) + "," + (radius + margin + marginTop) + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.innerRadius(0)
.outerRadius(radius);
// Pie
var pie = d3.layout.pie()
.value(function(d) { return +d.count; })
.sort(function(a, b) { return b.count - a.count; });
//
// Append chart elements
//
// Add a label for the airport
svg.append("text")
.attr("dy", ".35em")
.attr("y", -130)
.style("text-anchor", "middle")
.style("font-weight", 500)
.text(function(d) { return d.key; });
// Pass the nested values to the pie layout
var g = svg.selectAll("g")
.data(function(d) { return pie(d.values); })
.enter()
.append("g")
.attr("class", "d3-arc");
// Add a colored arc path, with a mouseover title showing the count
g.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return colors(d.data.carrier); })
.append("title")
.text(function(d) { return d.data.carrier + ": " + d.data.count; });
// Add a label to the larger arcs, translated to the arc centroid and rotated
g.filter(function(d) { return d.endAngle - d.startAngle > .2; }).append("text")
.attr("dy", ".35em")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")rotate(" + angle(d) + ")"; })
.style("fill", "#fff")
.style("font-size", 12)
.style("text-anchor", "middle")
.text(function(d) { return d.data.carrier; });
// Computes the label angle of an arc, converting from radians to degrees
function angle(d) {
var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
return a > 90 ? a - 180 : a;
}
});
}
});
+121
View File
@@ -0,0 +1,121 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - pie chart update animation
*
* Demo d3.js pie chart setup with .tsv data source and update animation
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Create Uniform checkbox
$(".pie-radios input").uniform({
radioClass: 'choice'
});
// Initialize chart
pieUpdateAnimation('#d3-pie-update', 120);
// Chart setup
function pieUpdateAnimation(element, radius) {
// Basic setup
// ------------------------------
// Colors
var color = d3.scale.category20();
// Create chart
// ------------------------------
// Add SVG element
var container = d3.select(element).append("svg");
// Add SVG group
var svg = container
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Construct chart layout
// ------------------------------
// Arc
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(0);
// Pie
var pie = d3.layout.pie()
.value(function(d) { return d.apples; })
.sort(null);
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/pies/pies_update.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.apples = +d.apples || 0;
d.oranges = +d.oranges || 0;
});
//
// Append chart elements
//
// Bind data
var path = svg.datum(data)
.selectAll("path")
.data(pie)
.enter()
.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d, i) { return color(i); })
.each(function(d) { this._current = d; }); // store the initial angles
// Apply change event
d3.selectAll(".pie-radios input").on("change", change);
// Change values on page load
var timeout = setTimeout(function() {
d3.select("input[value=\"oranges\"]").property("checked", true).each(change);
$.uniform.update();
}, 2000);
// Change values
function change() {
var value = this.value;
clearTimeout(timeout);
pie.value(function(d) { return d[value]; }); // change the value function
path = path.data(pie); // compute the new angles
path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
}
});
// Store the displayed angles in _current.
// Then, interpolate from _current to the new angles.
// During the transition, _current is updated in-place by d3.interpolate.
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
}
});
+114
View File
@@ -0,0 +1,114 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - basic sunbirst diagram
*
* Demo sunbirst diagram setup with .json data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize Uniform plugin
$('.basic-options input').uniform({
radioClass: 'choice'
});
// Initialize chart
sunburstBasic('#d3-sunburst-basic', 400, 400);
// Chart setup
function sunburstBasic(element, width, height) {
// Basic setup
// ------------------------------
// Define main variables
var radius = Math.min(width, height) / 2,
color = d3.scale.category20();
// Create chart
// ------------------------------
var svg = d3.select(element).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Construct chart layout
// ------------------------------
// Partition layout
var partition = d3.layout.partition()
.sort(null)
.size([2 * Math.PI, radius * radius])
.value(function(d) { return 1; });
// Arc
var arc = d3.svg.arc()
.startAngle(function(d) { return d.x; })
.endAngle(function(d) { return d.x + d.dx; })
.innerRadius(function(d) { return Math.sqrt(d.y); })
.outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/sunburst/sunburst_basic.json", function(error, root) {
// Add sunbirst
var path = svg.datum(root).selectAll("path")
.data(partition.nodes)
.enter()
.append("path")
.attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return color((d.children ? d : d.parent).name); })
.style("fill-rule", "evenodd")
.each(stash);
// Change data
d3.selectAll(".basic-options input").on("change", function change() {
var value = this.value === "count"
? function() { return 1; }
: function(d) { return d.size; };
// Transition
path.data(partition.value(value).nodes)
.transition()
.duration(750)
.attrTween("d", arcTween);
});
});
// Stash the old values for transition.
function stash(d) {
d.x0 = d.x;
d.dx0 = d.dx;
}
// Interpolate the arcs in data space.
function arcTween(a) {
var i = d3.interpolate({x: a.x0, dx: a.dx0}, a);
return function(t) {
var b = i(t);
a.x0 = b.x;
a.dx0 = b.dx;
return arc(b);
};
}
}
});
+165
View File
@@ -0,0 +1,165 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - sunbirst diagram combined
*
* Demo sunbirst diagram setup with interactive zoom and data update combination
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize Uniform plugin
$('.combined-options input').uniform({
radioClass: 'choice'
});
// Initialize chart
sunburstZoomable('#d3-sunburst-combined', 400, 400);
// Chart setup
function sunburstZoomable(element, width, height) {
// Basic setup
// ------------------------------
// Define main variables
var radius = Math.min(width, height) / 2;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.range([0, 2 * Math.PI]);
// Vertical
var y = d3.scale.sqrt()
.range([0, radius]);
// Colors
var color = d3.scale.category20();
// Create chart
// ------------------------------
var svg = d3.select(element).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Construct chart layout
// ------------------------------
// Partition layout
var partition = d3.layout.partition()
.sort(null)
.value(function(d) { return 1; });
// Arc
var arc = d3.svg.arc()
.startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
.endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
.innerRadius(function(d) { return Math.max(0, y(d.y)); })
.outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); });
// Load data
// ------------------------------
// Keep track of the node that is currently being displayed as the root.
var node;
d3.json("assets/demo_data/d3/sunburst/sunburst_basic.json", function(error, root) {
node = root;
// Append sunbirst
var path = svg.datum(root).selectAll(".d3-sunbirst")
.data(partition.nodes)
.enter()
.append("path")
.attr("class", "d3-sunbirst")
.attr("d", arc)
.style("fill", function(d) { return color((d.children ? d : d.parent).name); })
.on("click", click)
.each(stash);
// Change data
d3.selectAll(".combined-options input").on("change", function change() {
var value = this.value === "count"
? function() { return 1; }
: function(d) { return d.size; };
// Transition
path
.data(partition.value(value).nodes)
.transition()
.duration(750)
.attrTween("d", arcTweenData);
});
// Animate on click
function click(d) {
node = d;
path.transition()
.duration(750)
.attrTween("d", arcTweenZoom(d));
}
});
// Setup for switching data: stash the old values for transition.
function stash(d) {
d.x0 = d.x;
d.dx0 = d.dx;
}
// When switching data: interpolate the arcs in data space.
function arcTweenData(a, i) {
var oi = d3.interpolate({x: a.x0, dx: a.dx0}, a);
function tween(t) {
var b = oi(t);
a.x0 = b.x;
a.dx0 = b.dx;
return arc(b);
}
if (i == 0) {
// If we are on the first arc, adjust the x domain to match the root node
// at the current zoom level. (We only need to do this once.)
var xd = d3.interpolate(x.domain(), [node.x, node.x + node.dx]);
return function(t) {
x.domain(xd(t));
return tween(t);
};
}
else {
return tween;
}
}
// When zooming: interpolate the scales
function arcTweenZoom(d) {
var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
yd = d3.interpolate(y.domain(), [d.y, 1]),
yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]);
return function(d, i) {
return i
? function(t) { return arc(d); }
: function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); return arc(d); };
};
}
}
});
+125
View File
@@ -0,0 +1,125 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - sunbirst diagram with distortion
*
* Demo sunbirst diagram setup with interactive distortion
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
sunburstDistortion('#d3-sunburst-distortion', 400, 400);
// Chart setup
function sunburstDistortion(element, width, height) {
// Basic setup
// ------------------------------
// Define main variables
var radius = Math.min(width, height) / 2;
color = d3.scale.category20c();
// Create chart
// ------------------------------
var svg = d3.select(element).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Construct chart layout
// ------------------------------
// Partition layout
var partition = d3.layout.partition()
.size([2 * Math.PI, radius])
.value(function(d) { return d.size; });
// Arc
var arc = d3.svg.arc()
.startAngle(function(d) { return d.x; })
.endAngle(function(d) { return d.x + d.dx; })
.innerRadius(function(d) { return d.y; })
.outerRadius(function(d) { return d.y + d.dy; });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/sunburst/sunburst_basic.json", function(root) {
// Add sunbirst
path = svg.data([root]).selectAll("path")
.data(partition.nodes)
.enter()
.append("path")
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) { return color((d.children ? d : d.parent).name); })
.on("click", magnify)
.each(stash);
});
// Distort the specified node to 80% of its parent.
function magnify(node) {
if (parent = node.parent) {
var parent,
x = parent.x,
k = .8;
parent.children.forEach(function(sibling) {
x += reposition(sibling, x, sibling === node
? parent.dx * k / node.value
: parent.dx * (1 - k) / (parent.value - node.value));
});
}
else {
reposition(node, 0, node.dx / node.value);
}
path.transition()
.duration(750)
.attrTween("d", arcTween);
}
// Recursively reposition the node at position x with scale k.
function reposition(node, x, k) {
node.x = x;
if (node.children && (n = node.children.length)) {
var i = -1, n;
while (++i < n) x += reposition(node.children[i], x, k);
}
return node.dx = node.value * k;
}
// Stash the old values for transition.
function stash(d) {
d.x0 = d.x;
d.dx0 = d.dx;
}
// Interpolate the arcs in data space.
function arcTween(a) {
var i = d3.interpolate({x: a.x0, dx: a.dx0}, a);
return function(t) {
var b = i(t);
a.x0 = b.x;
a.dx0 = b.dx;
return arc(b);
};
}
}
});
+108
View File
@@ -0,0 +1,108 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - sunbirst diagram with zoom
*
* Demo sunbirst diagram setup with interactive zoom
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
sunburstZoomable('#d3-sunburst-zoom', 400, 400);
// Chart setup
function sunburstZoomable(element, width, height) {
// Basic setup
// ------------------------------
// Define main variables
var radius = Math.min(width, height) / 2;
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.linear()
.range([0, 2 * Math.PI]);
// Vertical
var y = d3.scale.sqrt()
.range([0, radius]);
// Colors
var color = d3.scale.category20c();
// Create chart
// ------------------------------
var svg = d3.select(element).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Construct chart layout
// ------------------------------
// Partition layout
var partition = d3.layout.partition()
.value(function(d) { return d.size; });
// Arc
var arc = d3.svg.arc()
.startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
.endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
.innerRadius(function(d) { return Math.max(0, y(d.y)); })
.outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/sunburst/sunburst_basic.json", function(error, root) {
// Append sunbirst
var path = svg.selectAll(".d3-sunbirst")
.data(partition.nodes(root))
.enter()
.append("path")
.attr("class", "d3-sunbirst")
.attr("d", arc)
.style("fill", function(d) { return color((d.children ? d : d.parent).name); })
.on("click", click);
// Run transition on click
function click(d) {
path.transition()
.duration(750)
.attrTween("d", arcTween(d));
}
});
// Interpolate the scales
function arcTween(d) {
var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
yd = d3.interpolate(y.domain(), [d.y, 1]),
yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]);
return function(d, i) {
return i
? function(t) { return arc(d); }
: function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); return arc(d); };
};
}
}
});
+168
View File
@@ -0,0 +1,168 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - basic tree layout
*
* Demo of tree layout setup with .json data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
treeBasic('#d3-tree-basic', 800);
// Chart setup
function treeBasic(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 0, right: 0, bottom: 0, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Tree
var tree = d3.layout.tree()
.size([height, width - 180]);
// Diagonal projection
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/tree/tree_data_basic.json", function(error, json) {
var nodes = tree.nodes(json),
links = tree.links(nodes);
// Links
// ------------------------------
// Append link group
var linkGroup = svg.append("g")
.attr("class", "d3-tree-link-group");
// Append link path
var link = linkGroup.selectAll(".d3-tree-link")
.data(links)
.enter()
.append("path")
.attr("class", "d3-tree-link")
.attr("d", diagonal)
.style("fill", "none")
.style("stroke", "#ddd")
.style("stroke-width", 1.5);
// Nodes
// ------------------------------
// Append node group
var nodeGroup = svg.append("g")
.attr("class", "d3-tree-node-group");
// Append node
var node = nodeGroup.selectAll(".d3-tree-node")
.data(nodes)
.enter()
.append("g")
.attr("class", "d3-tree-node")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
// Append node circles
node.append("circle")
.attr("r", 4.5)
.attr("class", "d3-tree-circle")
.style("fill", "#fff")
.style("stroke", "#2196F3")
.style("stroke-width", 1.5);
// Append node text
node.append("text")
.attr("dx", function(d) { return d.children ? -12 : 12; })
.attr("dy", 4)
.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
.style("font-size", 12)
.text(function(d) { return d.name; });
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
nodes = tree.nodes(json),
links = tree.links(nodes);
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Tree size
tree.size([height, width - 180]);
// Chart elements
// -------------------------
// Link paths
svg.selectAll(".d3-tree-link").attr("d", diagonal)
// Node paths
svg.selectAll(".d3-tree-node").attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
}
});
}
});
+327
View File
@@ -0,0 +1,327 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - bracket tree layout
*
* Demo of double sided bracket layout setup with pan and zoom
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
brackets('#d3-tree-bracket', 600);
// Chart setup
function brackets(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 0, right: 0, bottom: 0, left: 0},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
halfWidth = width / 2,
height = height - margin.top - margin.bottom - 5,
i = 0,
duration = 500,
root;
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Get children
var getChildren = function(d) {
var a = [];
if(d.winners) for(var i = 0; i < d.winners.length; i++){
d.winners[i].isRight = false;
d.winners[i].parent = d;
a.push(d.winners[i]);
}
if(d.challengers) for(var i = 0; i < d.challengers.length; i++){
d.challengers[i].isRight = true;
d.challengers[i].parent = d;
a.push(d.challengers[i]);
}
return a.length?a:null;
};
// Add zoom behavior
// ------------------------------
// Add zoom with scale
var zoom = d3.behavior.zoom()
.scaleExtent([1,2])
.on('zoom', function(){
svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
});
// Initialize zoom
container.call(zoom);
// Construct chart layout
// ------------------------------
// Tree
var tree = d3.layout.tree()
.size([height, width]);
// Diagonal projection
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
// Helper functions
// ------------------------------
// Connector
var elbow = function (d, i){
var source = calcLeft(d.source),
target = calcLeft(d.target),
hy = (target.y-source.y) / 2;
if(d.isRight) hy = -hy;
return "M" + source.y + "," + source.x + "H" + (source.y + hy) + "V" + target.x + "H" + target.y;
};
var connector = elbow;
// Calculate horizontal position
var calcLeft = function(d) {
var l = d.y;
if(!d.isRight) {
l = d.y-halfWidth;
l = halfWidth - l;
}
return {x : d.x, y : l};
};
var toArray = function(item, arr){
arr = arr || [];
var i = 0,
l = item.children?item.children.length : 0;
arr.push(item);
for(; i < l; i++) {
toArray(item.children[i], arr);
}
return arr;
};
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/tree/tree_bracket.json", function(json) {
root = json;
root.x0 = height / 2;
root.y0 = width / 2;
// Add tree layout
var t1 = d3.layout.tree().size([height, halfWidth]).children(function(d){return d.winners;}),
t2 = d3.layout.tree().size([height, halfWidth]).children(function(d){return d.challengers;});
t1.nodes(root);
t2.nodes(root);
// Rebuild children nodes
var rebuildChildren = function(node){
node.children = getChildren(node);
if(node.children) node.children.forEach(rebuildChildren);
}
rebuildChildren(root);
root.isRight = false;
update(root);
});
// Layout setup
// ------------------------------
// Update nodes
function update(source) {
// Compute the new tree layout.
var nodes = toArray(source);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 180 + halfWidth; });
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Stash the old positions for transition.
nodes.forEach(function(d) {
var p = calcLeft(d);
d.x0 = p.x;
d.y0 = p.y;
});
// Enter nodes
// ------------------------------
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", click);
// Add node circles
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("stroke", "#546E7A")
.style("stroke-width", 1.5)
.style("cursor", "pointer")
.style("fill", function(d) { return d._children ? "#546E7A" : "#fff"; });
// Add node text
nodeEnter.append("text")
.attr("dy", function(d) { return d.isRight?18:-12;})
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("font-size", 12)
.style("fill-opacity", 1e-6);
// Update nodes
// ------------------------------
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { p = calcLeft(d); return "translate(" + p.y + "," + p.x + ")"; });
// Update circle
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? "#546E7A" : "#fff"; });
// Update text
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Exit nodes
// ------------------------------
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { p = calcLeft(d.parent||source); return "translate(" + p.y + "," + p.x + ")"; })
.remove();
// Update circles
nodeExit.select("circle")
.attr("r", 1e-6);
// Update text
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Links
// ------------------------------
// Update the links
var link = svg.selectAll("path.link")
.data(tree.links(nodes), function(d) { return d.target.id; });
// Enter any new links at the parent's previous position
link.enter().insert("path", "g")
.attr("class", "link")
.style("stroke", "#546E7A")
.style("fill", "none")
.style("stroke-width", 1.5)
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return connector({source: o, target: o});
});
// Transition links to their new position
link.transition()
.duration(duration)
.attr("d", connector);
// Transition exiting nodes to the parent's new position
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = calcLeft(d.source||source);
if(d.source.isRight) o.y -= halfWidth - (d.target.y - d.source.y);
else o.y += halfWidth - (d.target.y - d.source.y);
return connector({source: o, target: o});
})
.remove();
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(source);
}
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
}
}
}
});
+282
View File
@@ -0,0 +1,282 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - collapsible tree layout
*
* Demo of tree layout setup with collapsible nodes
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
treeCollapsible('#d3-tree-collapsible', 800);
// Chart setup
function treeCollapsible(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 0, right: 0, bottom: 0, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5,
i = 0,
root;
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Tree
var tree = d3.layout.tree()
.size([height, width - 180]);
// Diagonal projection
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/tree/tree_data_collapsible.json", function(error, json) {
root = json;
root.x0 = height/2;
root.y0 = 0;
// Toggle nodes function
function toggleAll(d) {
if (d.children) {
d.children.forEach(toggleAll);
toggle(d);
}
}
// Initialize the display to show a few nodes
root.children.forEach(toggleAll);
toggle(root.children[1]);
toggle(root.children[1].children[2]);
toggle(root.children[9]);
toggle(root.children[9].children[0]);
update(root);
});
// Layout setup
// ------------------------------
// Update nodes
function update(source) {
// Set duration
var duration = d3.event && d3.event.altKey ? 5000 : 500;
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse();
// Normalize for fixed-depth.
//nodes.forEach(function(d) { d.y = d.depth * 250; });
// Update the nodes…
var node = svg.selectAll(".d3-tree-node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter nodes
// ------------------------------
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "d3-tree-node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", function(d) { toggle(d); update(d); });
// Add node circles
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", "#fff")
.style("stroke", "#2196F3")
.style("stroke-width", 1.5)
.style("cursor", "pointer")
.style("fill", function(d) { return d._children ? "#2196F3" : "#fff"; });
// Add nodes text
nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
.attr("dy", ".35em")
.style("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.style("font-size", 12)
.style("fill-opacity", 1e-6)
.text(function(d) { return d.name; });
// Update nodes
// ------------------------------
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
// Update circle
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? "#2196F3" : "#fff"; });
// Update text
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Exit nodes
// ------------------------------
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit()
.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
// Update circles
nodeExit.select("circle")
.attr("r", 1e-6);
// Update text
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Links
// ------------------------------
// Update the links…
var link = svg.selectAll(".d3-tree-link")
.data(tree.links(nodes), function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "d3-tree-link")
.style("fill", "none")
.style("stroke", "#ddd")
.style("stroke-width", 1.5)
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
})
.transition()
.duration(duration)
.attr("d", diagonal);
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control, .d3-tree-node circle').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
nodes = tree.nodes(root),
links = tree.links(nodes);
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Tree size
tree.size([height, width - 180]);
diagonal.projection(function(d) { return [d.y, d.x]; });
// Chart elements
// -------------------------
// Link paths
svg.selectAll(".d3-tree-link").attr("d", diagonal)
// Node paths
svg.selectAll(".d3-tree-node").attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
}
}
// Toggle childrens
function toggle(d) {
if (d.children) {
d._children = d.children;
d.children = null;
}
else {
d.children = d._children;
d._children = null;
}
}
}
});
+168
View File
@@ -0,0 +1,168 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - cluster dendrogram
*
* Demo of cluster dendrogram setup in cartesian orientation
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
treeCluster('#d3-tree-dendrogram', 800);
// Chart setup
function treeCluster(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 0, right: 0, bottom: 0, left: 40},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Cluster
var cluster = d3.layout.cluster()
.size([height, width - 180]);
// Diagonal projection
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/tree/tree_data_dendrogram.json", function(error, root) {
var nodes = cluster.nodes(root),
links = cluster.links(nodes);
// Links
// ------------------------------
// Append link group
var linkGroup = svg.append("g")
.attr("class", "d3-tree-link-group");
// Append link path
var link = linkGroup.selectAll(".d3-tree-link")
.data(links)
.enter()
.append("path")
.attr("class", "d3-tree-link")
.style("fill", "none")
.style("stroke", "#ddd")
.style("stroke-width", 1.5)
.attr("d", diagonal);
// Nodes
// ------------------------------
// Append node group
var nodeGroup = svg.append("g")
.attr("class", "d3-tree-node-group");
// Append node
var node = nodeGroup.selectAll(".d3-tree-node")
.data(nodes)
.enter()
.append("g")
.attr("class", "d3-tree-node")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
// Append node circles
node.append("circle")
.style("fill", "#fff")
.style("stroke", "#2196F3")
.style("stroke-width", 1.5)
.attr("r", 4.5);
// Append node text
var text = node.append("text")
.attr("dx", function(d) { return d.children ? -10 : 10; })
.attr("dy", 4)
.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
.style("font-size", 12)
.style("background-color", "#fff")
.text(function(d) { return d.name; });
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
nodes = cluster.nodes(root),
links = cluster.links(nodes);
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Tree size
cluster.size([height, width - 180]);
// Chart elements
// -------------------------
// Link paths
svg.selectAll(".d3-tree-link").attr("d", diagonal)
// Node paths
svg.selectAll(".d3-tree-node").attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
}
});
}
});
+105
View File
@@ -0,0 +1,105 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - radial dendrogram layout
*
* Demo of radial dendrogram layout setup with .json data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
dendrogramRadial('#d3-dendrogram-radial', 900);
// Chart setup
function dendrogramRadial(element, diameter) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element);
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", diameter)
.attr("height", diameter)
.append("g")
.attr("transform", "translate(" + (diameter / 2) + "," + (diameter / 2) + ")");
// Construct chart layout
// ------------------------------
// Cluster
var cluster = d3.layout.cluster()
.size([360, (diameter / 2) - 150]);
// Diagonal projection
var diagonal = d3.svg.diagonal.radial()
.projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/tree/tree_data_dendrogram_radial.json", function(error, root) {
var nodes = cluster.nodes(root);
// Links
// ------------------------------
// Append link paths
var link = svg.selectAll(".d3-tree-link")
.data(cluster.links(nodes))
.enter()
.append("path")
.attr("class", "d3-tree-link")
.attr("d", diagonal)
.style("fill", "none")
.style("stroke", "#ddd")
.style("stroke-width", 1.5);
// Nodes
// ------------------------------
// Append node group
var node = svg.selectAll(".d3-tree-node")
.data(nodes)
.enter()
.append("g")
.attr("class", "d3-tree-node")
.attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
// Append circles
node.append("circle")
.attr("r", 4.5)
.style("fill", "#fff")
.style("stroke", "#2196F3")
.style("stroke-width", 1.5);
// Append text
node.append("text")
.attr("dy", ".31em")
.attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
.attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; })
.style("font-size", 12)
.text(function(d) { return d.name; });
});
}
});
+108
View File
@@ -0,0 +1,108 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - radial tree layout
*
* Demo of radial tree layout setup with .json data source
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Initialize chart
treeRadial('#d3-tree-radial', 900);
// Chart setup
function treeRadial(element, diameter) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element);
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", diameter)
.attr("height", diameter - 140)
.append("g")
.attr("transform", "translate(" + (diameter / 2) + "," + (diameter / 2) + ")");
// Construct chart layout
// ------------------------------
// Tree
var tree = d3.layout.tree()
.size([360, (diameter / 2) - 110])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
// Diagonal projection
var diagonal = d3.svg.diagonal.radial()
.projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });
// Load data
// ------------------------------
d3.json("assets/demo_data/d3/tree/tree_data_radial.json", function(error, root) {
var nodes = tree.nodes(root),
links = tree.links(nodes);
// Links
// ------------------------------
// Append link paths
var link = svg.selectAll(".d3-tree-link")
.data(links)
.enter()
.append("path")
.attr("class", "d3-tree-link")
.attr("d", diagonal)
.style("fill", "none")
.style("stroke", "#ddd")
.style("stroke-width", 1.5);
// Nodes
// ------------------------------
// Append node group
var node = svg.selectAll(".d3-tree-node")
.data(nodes)
.enter()
.append("g")
.attr("class", "d3-tree-node")
.attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
// Append circles
node.append("circle")
.attr("r", 4.5)
.style("fill", "#fff")
.style("stroke", "#2196F3")
.style("stroke-width", 1.5);
// Append text
node.append("text")
.attr("dy", ".31em")
.attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
.attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; })
.style("font-size", 12)
.text(function(d) { return d.name; });
});
}
});
+51
View File
@@ -0,0 +1,51 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - basic Venn diagram
*
* Basic demo d3.js Venn diagram setup
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Data set
// ------------------------------
// Circles
var sets = [
{label: 'SE', size: 28},
{label: 'Treat', size: 35},
{label: 'Anti-CCP', size: 108},
{label: 'DAS28', size: 106}
];
// Overlaps
var overlaps = [
{sets: [0,1], size: 1},
{sets: [0,2], size: 1},
{sets: [0,3], size: 14},
{sets: [1,2], size: 6},
{sets: [1,3], size: 0},
{sets: [2,3], size: 1},
{sets: [0,2,3], size: 1},
{sets: [0,1,2], size: 0},
{sets: [0,1,3], size: 0},
{sets: [1,2,3], size: 0},
{sets: [0,1,2,3], size: 0}
];
// Initialize chart
// ------------------------------
// Draw diagram
var diagram = venn.drawD3Diagram(d3.select("#d3-venn-basic"), venn.venn(sets, overlaps), 350, 350);
// Make text semi bold
diagram.text.style("font-weight", "500");
});
+65
View File
@@ -0,0 +1,65 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - custom diagram colors
*
* Venn diagram demo with custom color options
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Data set
// ------------------------------
// Circles
var sets = [
{label: 'SE', size: 28},
{label: 'Treat', size: 35},
{label: 'Anti-CCP', size: 108},
{label: 'DAS28', size: 106}
];
// Overlaps
var overlaps = [
{sets: [0,1], size: 1},
{sets: [0,2], size: 1},
{sets: [0,3], size: 14},
{sets: [1,2], size: 6},
{sets: [1,3], size: 0},
{sets: [2,3], size: 1},
{sets: [0,2,3], size: 1},
{sets: [0,1,2], size: 0},
{sets: [0,1,3], size: 0},
{sets: [1,2,3], size: 0},
{sets: [0,1,2,3], size: 0}
];
// Initialize chart
// ------------------------------
// Define colors
var colours = d3.scale.category10();
// Draw diagram
var diagram = venn.drawD3Diagram(d3.select("#d3-venn-colors"), venn.venn(sets, overlaps), 350, 350);
// Style circles
diagram.circles
.style("fill-opacity", .7)
.style("stroke-opacity", 0)
.style("fill", function(d,i) { return colours(i); })
.style("stroke", function(d,i) { return colours(i); });
// Style text
diagram.text
.style("fill", "white")
.style("font-weight", "500");
});
+86
View File
@@ -0,0 +1,86 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - interactive Venn diagram
*
* Venn diagram demo setup with interactions
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Data set
// ------------------------------
// Circles
var sets = [
{label: 'SE', size: 28},
{label: 'Treat', size: 35},
{label: 'Anti-CCP', size: 108},
{label: 'DAS28', size: 106}
];
// Overlaps
var overlaps = [
{sets: [0,1], size: 1},
{sets: [0,2], size: 1},
{sets: [0,3], size: 14},
{sets: [1,2], size: 6},
{sets: [1,3], size: 0},
{sets: [2,3], size: 1},
{sets: [0,2,3], size: 1},
{sets: [0,1,2], size: 0},
{sets: [0,1,3], size: 0},
{sets: [1,2,3], size: 0},
{sets: [0,1,2,3], size: 0}
];
// Initialize chart
// ------------------------------
// Define colors
var colours = d3.scale.category10();
// Draw diagram
var diagram = venn.drawD3Diagram(d3.select("#d3-venn-interactive"), venn.venn(sets, overlaps), 350, 350);
// Circle styles
diagram.circles
.style("fill-opacity", 0)
.style("stroke-width", 4)
.style("stroke-opacity", .6)
.style("cursor", "pointer")
.style("fill", function(d,i) { return colours(i); })
.style("stroke", function(d,i) { return colours(i); });
// Text styles
diagram.text
.style("fill", function(d,i) { return colours(i)})
.style("cursor", "pointer")
.style("font-size", "14px")
.style("font-weight", "500");
// Add interaction
diagram.nodes
.on("mouseover", function(d, i) {
var node = d3.select(this).transition();
node.select("circle").style("fill-opacity", .1);
node.select("text").style("font-weight", "500").style("font-size", "16px");
})
.on("mouseout", function(d, i) {
var node = d3.select(this).transition();
node.select("circle").style("fill-opacity", 0);
node.select("text").style("font-weight", "500").style("font-size", "14px");
})
.on("click", function(d, i) {
alert("You have clicked on one of the rings!")
});
});
+66
View File
@@ -0,0 +1,66 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - ring Venn diagram
*
* Venn diagram demo with ring style option
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Data set
// ------------------------------
// Circles
var sets = [
{label: 'SE', size: 28},
{label: 'Treat', size: 35},
{label: 'Anti-CCP', size: 108},
{label: 'DAS28', size: 106}
];
// Overlaps
var overlaps = [
{sets: [0,1], size: 1},
{sets: [0,2], size: 1},
{sets: [0,3], size: 14},
{sets: [1,2], size: 6},
{sets: [1,3], size: 0},
{sets: [2,3], size: 1},
{sets: [0,2,3], size: 1},
{sets: [0,1,2], size: 0},
{sets: [0,1,3], size: 0},
{sets: [1,2,3], size: 0},
{sets: [0,1,2,3], size: 0}
];
// Initialize chart
// ------------------------------
// Define colors
var colours = d3.scale.category10();
// Draw diagram
var diagram = venn.drawD3Diagram(d3.select("#d3-venn-rings"), venn.venn(sets, overlaps), 350, 350);
// Style circles
diagram.circles
.style("fill-opacity", 0)
.style("stroke-width", 6)
.style("stroke-opacity", .6)
.style("fill", function(d,i) { return colours(i); })
.style("stroke", function(d,i) { return colours(i); });
// Style text
diagram.text
.style("fill", function(d,i) { return colours(i)})
.style("font-weight", "500");
});
+137
View File
@@ -0,0 +1,137 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - Venn diagram with tooltip
*
* Venn diagram demo setup with interactive data tooltip
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Data set
// ------------------------------
// Circles
var sets = [
{label: 'SE', size: 28},
{label: 'Treat', size: 35},
{label: 'Anti-CCP', size: 108},
{label: 'DAS28', size: 106}
];
// Overlaps
var overlaps = [
{sets: [0,1], size: 1},
{sets: [0,2], size: 1},
{sets: [0,3], size: 14},
{sets: [1,2], size: 6},
{sets: [1,3], size: 0},
{sets: [2,3], size: 1},
{sets: [0,2,3], size: 1},
{sets: [0,1,2], size: 0},
{sets: [0,1,3], size: 0},
{sets: [1,2,3], size: 0},
{sets: [0,1,2,3], size: 0}
];
// Initialize chart
// ------------------------------
// Define colors
var colours = d3.scale.category10();
// Get positions for each set
sets = venn.venn(sets, overlaps);
// Draw the diagram in the 'venn' div
var diagram = venn.drawD3Diagram(d3.select("#d3-venn-tooltip"), sets, 350, 350);
// Add tooltip
// ------------------------------
// Add a tooltip showing the size of each set/intersection
var tooltip = d3.select("body").append("div")
.attr("class", "venntooltip");
d3.selection.prototype.moveParentToFront = function() {
return this.each(function(){
this.parentNode.parentNode.appendChild(this.parentNode);
});
};
// Text styling
diagram.text.style("fill", "white").style("font-weight", "500").style("cursor", "pointer");
// Hover on all the circles
diagram.circles
.style("stroke-opacity", 0)
.style("stroke", "white")
.style("stroke-width", "2")
.style("fill-opacity", .7);
// Add events
diagram.nodes
.on("mousemove", function() {
tooltip.style("left", (d3.event.pageX + 20) + "px")
.style("top", (d3.event.pageY - 15) + "px");
})
.on("mouseover", function(d, i) {
var selection = d3.select(this).select("circle");
selection.moveParentToFront()
.transition()
.style("fill-opacity", .7)
.style("cursor", "pointer")
.style("stroke-opacity", 1);
tooltip.transition().style("display", "block");
tooltip.text(d.size + " users");
})
.on("mouseout", function(d, i) {
d3.select(this).select("circle").transition()
.style("fill-opacity", .7)
.style("stroke-opacity", 0);
tooltip.transition().style("display", "none");
});
// Draw a path around each intersection area, add hover there as well
diagram.svg.selectAll("path")
.data(overlaps)
.enter()
.append("path")
.attr("d", function(d) {
return venn.intersectionAreaPath(d.sets.map(function(j) { return sets[j]; }));
})
.style("fill-opacity","0")
.style("fill", "#333")
.style("stroke-opacity", 0)
.style("stroke", "white")
.style("stroke-width", "2")
.on("mouseover", function(d, i) {
d3.select(this).transition()
.style("fill-opacity", .1)
.style("stroke-opacity", 1);
tooltip.transition().style("display", "block");
tooltip.text(d.size + " users");
})
.on("mouseout", function(d, i) {
d3.select(this).transition()
.style("fill-opacity", 0)
.style("stroke-opacity", 0);
tooltip.transition().style("display", "none");
})
.on("mousemove", function() {
tooltip.style("left", (d3.event.pageX + 20) + "px")
.style("top", (d3.event.pageY - 15) + "px");
});
});
+75
View File
@@ -0,0 +1,75 @@
/* ------------------------------------------------------------------------------
*
* # D3.js - weighted Venn diagram
*
* Venn diagram demo with weights
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Data set
// ------------------------------
// Circles
var sets = [{label: "0", size: 7000},
{label: "1", size: 7000},
{label: "2", size: 2000},
{label: "3", size: 11000},
{label: "4", size: 11000}];
// Overlaps
var overlaps = [{id: 1, sets: [2,0], size: 300},
{id: 2, sets: [2,1], size: 300},
{id: 4, sets: [2,3], size: 100},
{id: 5, sets: [2,4], size: 100},
{sets: [0,0], size: 0, weight: 1e-10},
{sets: [0,1], size: 0, weight: 1e-10},
{sets: [0,3], size: 0, weight: 1e-10},
{sets: [0,4], size: 0, weight: 1e-10},
{sets: [1,0], size: 0, weight: 1e-10},
{sets: [1,1], size: 0, weight: 1e-10},
{sets: [1,3], size: 0, weight: 1e-10},
{sets: [1,4], size: 0, weight: 1e-10},
{sets: [3,0], size: 0, weight: 1e-10},
{sets: [3,1], size: 0, weight: 1e-10},
{sets: [3,3], size: 0, weight: 1e-10},
{sets: [3,4], size: 0, weight: 1e-10},
{sets: [4,0], size: 0, weight: 1e-10},
{sets: [4,1], size: 0, weight: 1e-10},
{sets: [4,3], size: 0, weight: 1e-10},
{sets: [4,4], size: 0, weight: 1e-10}];
// Initialize chart
// ------------------------------
// Colors
var colours = d3.scale.category10();
// Bind data
sets = venn.venn(sets, overlaps);
// Draw diagram
var diagram = venn.drawD3Diagram(d3.select("#d3-venn-weighted"), sets, 350, 350);
// Circle styles
diagram.circles
.style("fill-opacity", .7)
.style("stroke-opacity", 0)
.style("fill", function(d,i) { return colours(i); })
.style("stroke", function(d,i) { return colours(i); });
// Text styles
diagram.text
.style("fill", "white")
.style("font-weight", "500");
});
@@ -0,0 +1,100 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal area
*
* Demo of area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-horizontal", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 10, 10, 50);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", "Month");
x.addOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add area
var s = myChart
.addSeries(null, dimple.plot.area)
.interpolation = "basis";
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Remove axis titles
x.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Remove axis titles
x.titleShape.remove();
}
});
});
@@ -0,0 +1,100 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal grouped area
*
* Demo of grouped area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-horizontal-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 10, 10, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", ["Owner", "Month"]);
x.addGroupOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add area
var s = myChart
.addSeries("Owner", dimple.plot.area)
.interpolation = "basis";
// Line weight
s.lineWeight = 1;
// Area spacing
s.barGap = 0.05;
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
}
});
});
@@ -0,0 +1,116 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal stacked area
*
* Demo of stacked area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-horizontal-stacked", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 25, 10, 50);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", "Month");
x.addOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add area
var s = myChart
.addSeries("Channel", dimple.plot.area)
.interpolation = "basis";
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
}
});
});
@@ -0,0 +1,116 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal grouped stacked area
*
* Demo of grouped stacked area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-horizontal-stacked-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 10, 180, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", ["Owner", "Month"]);
x.addGroupOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add area
var s = myChart
.addSeries("SKU", dimple.plot.area)
.interpolation = "basis";
// Line weight
s.lineWeight = 1;
// Area spacing
s.barGap = 0.05;
// Add legend
// ------------------------------
var myLegend = myChart.addLegend("100%", 0, 0, "100%", "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,116 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal normalized stacked area
*
* Demo of normalized stacked area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-horizontal-stacked-normalized", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 25, 10, 50);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", "Month");
x.addOrderRule("Date");
// Vertical
var y = myChart.addPctAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add area
myChart
.addSeries("Channel", dimple.plot.area)
.interpolation = "basis";
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
}
});
});
@@ -0,0 +1,91 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical area
*
* Demo of area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-vertical", "100%", 500);
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 5, 20, 40);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", "Month");
y.addOrderRule("Date");
// Construct layout
// ------------------------------
// Add area
var s = myChart
.addSeries(null, dimple.plot.area)
.interpolation = "basis";
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
}
});
});
@@ -0,0 +1,100 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical grouped area
*
* Demo of grouped area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-vertical-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(70, 5, 20, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", ["Owner", "Month"]);
y.addGroupOrderRule("Date");
// Construct layout
// ------------------------------
// Add area
var s = myChart
.addSeries("Owner", dimple.plot.area)
.interpolation = "basis";
// Line weight
s.lineWeight = 1;
// Area spacing
s.barGap = 0.05;
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
}
});
});
@@ -0,0 +1,110 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical stacked area
*
* Demo of stacked area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-vertical-stacked", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 25, 20, 40);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", "Month");
y.addOrderRule("Date");
// Construct layout
// ------------------------------
// Add area
myChart
.addSeries("Channel", dimple.plot.area)
.interpolation = "basis";
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "left");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,114 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical grouped stacked area
*
* Demo of grouped stacked area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-vertical-stacked-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(70, 5, 180, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", ["Owner", "Month"]);
y.addGroupOrderRule("Date");
// Construct layout
// ------------------------------
// Add area
var s = myChart.addSeries("SKU", dimple.plot.area);
// Line weight
s.lineWeight = 1;
// Area spacing
s.barGap = 0.05;
// Add legend
// ------------------------------
var myLegend = myChart.addLegend("100%", 0, 0, "100%", "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,110 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical normalized stacked area
*
* Demo of normalized stacked area chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-area-vertical-stacked-normalized", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(65, 25, 20, 40);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addPctAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", "Month");
y.addOrderRule("Date");
// Construct layout
// ------------------------------
// Add area
myChart
.addSeries("Channel", dimple.plot.area)
.interpolation = "basis";
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,96 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal bars
*
* Demo of bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-horizontal", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%")
// Set margins
myChart.setMargins(55, 5, 0, 50);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", "Month");
x.addOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries(null, dimple.plot.bar);
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Remove axis titles
x.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Remove axis titles
x.titleShape.remove();
}
});
});
@@ -0,0 +1,104 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal grouped bars
*
* Demo of grouped bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-horizontal-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(60, 25, 10, 60);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", ["Price Tier", "Channel"]);
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries("Channel", dimple.plot.bar);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,112 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal stacked bars
*
* Demo of stacked bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-horizontal-stacked", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(60, 25, 0, 50);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", "Month");
x.addOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries("Channel", dimple.plot.bar);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Remove axis titles
x.titleShape.remove();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Remove axis titles
x.titleShape.remove();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,104 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal grouped stacked bars
*
* Demo of grouped stacked bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-horizontal-stacked-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(60, 5, 120, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", ["Price Tier", "Channel"]);
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries("Owner", dimple.plot.bar);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend("100%", 0, 0, "100%", "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,112 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal normalized stacked bars
*
* Demo of normalized stacked bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-horizontal-stacked-normalized", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(60, 25, 0, 50);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", "Month");
x.addOrderRule("Date");
// Vertical
var y = myChart.addPctAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries("Channel", dimple.plot.bar);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Remove axis titles
x.titleShape.remove();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Remove axis titles
x.titleShape.remove();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,96 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical bars
*
* Demo of bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-vertical", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%")
// Set margins
myChart.setMargins(70, 5, 20, 30);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", "Month");
y.addOrderRule("Date");
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries(null, dimple.plot.bar);
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Remove axis titles
x.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Remove axis titles
x.titleShape.remove();
}
});
});
@@ -0,0 +1,105 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical grouped bars
*
* Demo of grouped bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-vertical-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(60, 25, 20, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", ["Price Tier", "Channel"]);
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries("Channel", dimple.plot.bar);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,112 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical stacked bars
*
* Demo of stacked bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-vertical-stacked", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(70, 25, 20, 30);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", "Month");
y.addOrderRule("Date");
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries("Channel", dimple.plot.bar);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Remove axis titles
x.titleShape.remove();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Remove axis titles
x.titleShape.remove();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,105 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical grouped stacked bars
*
* Demo of grouped stacked bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-vertical-stacked-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 5, 120, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", ["Price Tier", "Channel"]);
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries("Owner", dimple.plot.bar);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend("100%", 0, 0, "100%", "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,112 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical normalized stacked bars
*
* Demo of normalized stacked bar chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bar-vertical-stacked-normalized", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(70, 25, 20, 30);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addPctAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", "Month");
y.addOrderRule("Date");
// Construct layout
// ------------------------------
// Add bars
myChart.addSeries("Channel", dimple.plot.bar);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Remove axis titles
x.titleShape.remove();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Remove axis titles
x.titleShape.remove();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,107 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - basic bubbles
*
* Demo of bubble chart with legend. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bubble-basic", "100%", 500);
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Date", "01/12/2011");
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(50, 25, 15, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales Monthly Change");
// Vertical
var y = myChart.addMeasureAxis("y", "Price Monthly Change");
// Other axes
myChart.addMeasureAxis("z", "Operating Profit");
// Construct layout
// ------------------------------
// Add bubbles
myChart.addSeries(["SKU", "Channel"], dimple.plot.bubble);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,116 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - horizontal lollipop
*
* Demo of horizontal lollipop chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bubble-lollipop-horizontal", "100%", 500);
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Date", [
"01/07/2011", "01/08/2011", "01/09/2011",
"01/10/2011", "01/11/2011", "01/12/2011"
]);
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(70, 25, 20, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addMeasureAxis("x", "Unit Sales");
// Vertical
var y = myChart.addCategoryAxis("y", "Month");
// Order by date
y.addOrderRule("Date");
// Show vertical grid lines
y.showGridlines = true;
// Other axes
myChart.addMeasureAxis("z", "Operating Profit");
// Construct layout
// ------------------------------
// Add bubbles
myChart.addSeries("Channel", dimple.plot.bubble);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "left");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,104 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - grouped lollipop
*
* Demo of grouped lollipop chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bubble-lollipop-grouped", "100%", 500);
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 38, 10, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", ["Price Tier", "Channel"]);
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Other axes
myChart.addMeasureAxis("z", "Operating Profit");
// Construct layout
// ------------------------------
// Add bubbles
myChart.addSeries("Channel", dimple.plot.bubble);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 20, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,110 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - bubble matrix
*
* Demo of bubble matrix. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bubble-matrix", "100%", 500);
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(95, 25, 10, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", ["Channel", "Price Tier"]);
// Vertical
var y = myChart.addCategoryAxis("y", "Owner");
// Other axes
var z = myChart.addMeasureAxis("z", "Distribution");
// Display grid lines
x.showGridlines = true;
y.showGridlines = true;
// Construct layout
// ------------------------------
// Add bubbles
var s = myChart.addSeries("Price Tier", dimple.plot.bubble);
s.aggregate = dimple.aggregateMethod.max;
z.overrideMax = 200;
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,111 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - vertical lollipop
*
* Demo of vertical lollipop chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-bubble-lollipop-vertical", "100%", 500);
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Date", [
"01/07/2011", "01/08/2011", "01/09/2011",
"01/10/2011", "01/11/2011", "01/12/2011"
]);
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(55, 35, 10, 45);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", "Month");
x.addOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Other axes
myChart.addMeasureAxis("z", "Operating Profit");
// Construct layout
// ------------------------------
// Add bubbles
myChart.addSeries("Channel", dimple.plot.bubble);
// Add legend
// ------------------------------
var myLegend = myChart.addLegend(0, 5, "100%", 0, "left");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
}
});
});
@@ -0,0 +1,121 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - multiple horizontal lines
*
* Demo of multiple line chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-line-horizontal-multiple", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(40, 25, 0, 50);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", "Month");
x.addOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add line
myChart
.addSeries("Channel", dimple.plot.line)
.interpolation = "basis";
// Add legend
// ------------------------------
var myLegend = myChart
.addLegend(0, 5, "100%", 0, "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
setTimeout(function() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
}, 100)
}
});
});
@@ -0,0 +1,124 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - multiple horizontal lines
*
* Demo of grouped multiple line chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-line-horizontal-multiple-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(40, 10, 90, 30);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", ["Owner", "Month"]);
x.addGroupOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add line
var s = myChart
.addSeries(["Brand"], dimple.plot.line)
.interpolation = "basis";
// Line space
s.barGap = 0.05;
// Add legend
// ------------------------------
var myLegend = myChart
.addLegend("100%", 0, 0, "100%", "right");
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
// Legend font style
myLegend.fontSize = "12";
myLegend.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
setTimeout(function() {
// Redraw chart
myChart.draw(0, true);
// Position legend text
myLegend.shapes.selectAll("text").attr("dy", "1");
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
}, 100)
}
});
});
@@ -0,0 +1,104 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - single horizontal line
*
* Demo of a single line chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-line-horizontal-single", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"])
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(40, 10, 0, 50);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", "Month");
x.addOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add line
var s = myChart
.addSeries(null, dimple.plot.line)
.interpolation = "basis";
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
setTimeout(function() {
// Redraw chart
myChart.draw(0, true);
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
}, 100)
}
});
});
@@ -0,0 +1,107 @@
/* ------------------------------------------------------------------------------
*
* # Dimple.js - single horizontal grouped line
*
* Demo of a grouped line chart. Data stored in .tsv file format
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Construct chart
var svg = dimple.newSvg("#dimple-line-horizontal-single-grouped", "100%", 500);
// Chart setup
// ------------------------------
d3.tsv("assets/demo_data/dimple/demo_data.tsv", function (data) {
// Filter data
data = dimple.filterData(data, "Owner", ["Aperture", "Black Mesa"]);
// Create chart
// ------------------------------
// Define chart
var myChart = new dimple.chart(svg, data);
// Set bounds
myChart.setBounds(0, 0, "100%", "100%");
// Set margins
myChart.setMargins(40, 10, 0, 30);
// Create axes
// ------------------------------
// Horizontal
var x = myChart.addCategoryAxis("x", ["Owner", "Month"]);
x.addGroupOrderRule("Date");
// Vertical
var y = myChart.addMeasureAxis("y", "Unit Sales");
// Construct layout
// ------------------------------
// Add line
var s = myChart
.addSeries("Owner", dimple.plot.line)
.interpolation = "basis";
// Bar space
s.barGap = 0.05;
// Add styles
// ------------------------------
// Font size
x.fontSize = "12";
y.fontSize = "12";
// Font family
x.fontFamily = "Roboto";
y.fontFamily = "Roboto";
//
// Draw chart
//
// Draw
myChart.draw();
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
// Resize chart
// ------------------------------
// Add a method to draw the chart on resize of the window
$(window).on('resize', resize);
$('.sidebar-control').on('click', resize);
// Resize function
function resize() {
setTimeout(function() {
// Redraw chart
myChart.draw(0, true);
// Remove axis titles
x.titleShape.remove();
y.titleShape.remove();
}, 100)
}
});
});

Some files were not shown because too many files have changed in this diff Show More