Skip to content

Instantly share code, notes, and snippets.

@michalskop
Last active September 8, 2015 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalskop/c972824832b1bc23d7c3 to your computer and use it in GitHub Desktop.
Save michalskop/c972824832b1bc23d7c3 to your computer and use it in GitHub Desktop.
Timeline plot, barplot (reusable, responsive)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chart</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Plot">
<meta name="author" content="Michal Škop">
<script src="//cdn.bootcss.com/d3/3.5.6/d3.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="./modernizr.svg.js"></script>
<script src="./d3.rowplot.js"></script>
<body>
<div id="chart"></div>
<style>
rect:hover {
fill-opacity: 1;
stroke-width: 1px;
stroke: black;
}
.rowplot-axis path, .rowplot-axis line {stroke:#ccc; fill:none;}
.rowplot-axis text {
fill: gray;
font-weight: 600;
font-family: ubuntu;
font-size: 30px;
}
</style>
<script type="text/javascript">
data = [];
last = 0;
n = 1000;
for (i=1;i<=n;i++) {
if (Math.random() < (0.17 + 0.8*last))
last = 1;
else
last = 0;
data.push(last);
}
var $chart = $('#chart');
var graphic_data = data;
function drawGraphic() {
var margin = { top: 10, right: 30, bottom: 30, left: 40 };
var width = $chart.width() - margin.left - margin.right;
var rowplot = [{
"data": graphic_data,
"margin": margin,
"size":{"width":width,"height":70},
}];
// clear out existing graphics
$chart.empty();
var svg = d3.select("#chart")
.append("svg")
.attr("width",rowplot[0]['size']['width'])
.attr("height",rowplot[0]['size']['height']);
var tlp = d3.rowplot()
.data(function(d) {return d.data})
.margin(function(d) {return d.margin})
var timeline = svg.selectAll(".rowplot")
.data(rowplot)
.enter()
.append("svg:g")
.attr("transform", "translate(" + rowplot[0].margin.left + "," + rowplot[0].margin.top + ")")
.call(tlp);
}
if (Modernizr.svg) { // if svg is supported, draw dynamic chart
drawGraphic();
window.onresize = drawGraphic;
}
</script>
/* requires D3 + https://github.com/Caged/d3-tip */
d3.rowplot = function() {
//defaults
ticksnumber = 3;
colors = {"yes": "darkgreen" ,"no":"white"};
mobile_threshold = 500;
function rowplot(selection) {
selection.each(function(d, i) {
//options
var data = (typeof(data) === "function" ? data(d) : d.data),
margin = (typeof(margin) === "function" ? margin(d) : d.margin),
colors_val = (typeof(colors) === "function" ? colors(d) : (typeof(d.colors) === "undefined" ? colors : d.colors)),
size = (typeof(size) === "function" ? size(d) : d.size)
;
// chart sizes
var width = size['width'] - margin.left - margin.right,
height = size['height'] - margin.top - margin.bottom;
//set up scales
var xScale = d3.scale.linear()
.domain([0, 1])
.range([0, width])
var yScale = d3.scale.linear()
.domain([0, 1])
.range([height, 0]);
//set up axis
var xAxis = d3.svg.axis().scale(xScale);
// define element
var element = d3.select(this);
// 2 x axes
element.append("g")
.attr("class", "x-axis axis rowplot-axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis
//.orient("bottom")
.ticks(0)
.tickValues([])
);
element.append("g")
.attr("class", "x axis rowplot-axis")
//.attr("transform", "translate(0," + height + ")")
.call(xAxis
.ticks(0)
.tickValues([])
);
//create points
element.selectAll(".rectangle")
.data(data)
.enter()
.append("rect")
.attr("x", function(d,i) {
return xScale(i/n);
})
.attr("y", function(d,i) {
return yScale(1);
})
.attr("width", function() {
return xScale(1/n);
})
.attr("height",function() {
return yScale(0) - yScale(1);
})
.attr("fill", function(d) {
if (d == 1) return colors_val['yes'];
else return colors_val['no'];
})
.attr("fill-opacity", 1)
.attr("class","rowplot-rect");
});
}
//
rowplot.data = function(value) {
if (!arguments.length) return value;
data = value;
return rowplot;
}
rowplot.colors = function(value) {
if (!arguments.length) return value;
colors = value;
return rowplot;
}
rowplot.margin = function(value) {
if (!arguments.length) return value;
margin = value;
return rowplot;
}
rowplot.size = function(value) {
if (!arguments.length) return value;
size = value;
return rowplot;
}
return rowplot;
}
/* requires D3 + https://github.com/Caged/d3-tip */
d3.timelineplot = function() {
//defaults
ticksnumber = 3;
pointcolor = "red";
mobile_threshold = 500;
function timelineplot(selection) {
selection.each(function(d, i) {
//options
var data = (typeof(data) === "function" ? data(d) : d.data),
margin = (typeof(margin) === "function" ? margin(d) : d.margin),
minmaxdate = (typeof(minmaxdate) === "function" ? minmaxdate(d) : d.minmaxdate),
ticksnumber_val = (typeof(ticksnumber) === "function" ? ticksnumber(d) : (typeof(d.ticksnumber) === "undefined" ? ticksnumber : d.ticksnumber)),
pointcolor_val = (typeof(pointcolor) === "function" ? pointcolor(d) : (typeof(d.pointcolor) === "undefined" ? pointcolor : d.pointcolor)),
size = (typeof(size) === "function" ? size(d) : d.size)
;
// chart sizes
var width = size['width'] - margin.left - margin.right,
height = size['height'] - margin.top - margin.bottom;
// define the x scale (horizontal)
var mindate = minmaxdate['min'],
maxdate = minmaxdate['max'];
//set up scales
var xScale = d3.time.scale()
.domain([mindate, maxdate])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([0, 1])
.range([height, 0]);
//set up axis
var xAxis = d3.svg.axis().scale(xScale);
// define element
var element = d3.select(this);
// var svg = element.append("svg")
// .attr("width", width + margin.left + margin.right)
// .attr("height", height + margin.top + margin.bottom)
// .append("g")
// .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// 2 x axes
element.append("g")
.attr("class", "x-axis axis timeline-axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis
//.orient("bottom")
.ticks(ticksnumber_val)
//.tickValues([new Date(2013,0,1)])
);
element.append("g")
.attr("class", "x axis timeline-axis")
//.attr("transform", "translate(0," + height + ")")
.call(xAxis
.ticks(0)
.tickValues([])
);
//create points
element.selectAll(".rectangle")
.data(data)
.enter()
.append("rect")
.attr("x", function(d,i) {
return xScale(d);
})
.attr("y", function(d,i) {
return yScale(1);
})
.attr("width", 1)
.attr("height",function() {
return yScale(0) - yScale(1);
})
.attr("fill", pointcolor_val)
.attr("fill-opacity", 1)
.attr("class","timeline-rect");
});
}
//
timelineplot.data = function(value) {
if (!arguments.length) return value;
data = value;
return timelineplot;
}
timelineplot.minmaxdate = function(value) {
if (!arguments.length) return value;
minmaxdate = value;
return timelineplot;
}
timelineplot.ticksnumber = function(value) {
if (!arguments.length) return value;
ticksnumber = value;
return timelineplot;
}
timelineplot.pointcolor = function(value) {
if (!arguments.length) return value;
pointcolor = value;
return timelineplot;
}
timelineplot.margin = function(value) {
if (!arguments.length) return value;
margin = value;
return timelineplot;
}
timelineplot.size = function(value) {
if (!arguments.length) return value;
size = value;
return timelineplot;
}
return timelineplot;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chart</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="plot">
<meta name="author" content="Michal Škop">
<script src="//cdn.bootcss.com/d3/3.5.6/d3.min.js"></script>
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="./modernizr.svg.js"></script>
<script src="./d3.timelineplot.js"></script>
<body>
<div id="chart"></div>
<style>
.timeline-rect:hover {
fill-opacity: 1;
stroke-width: 3px;
stroke: black;
}
.timeline-axis path, .timeline-axis line {stroke:#ccc; fill:none;}
.timeline-axis text {
fill: gray;
font-weight: 600;
font-family: ubuntu;
font-size: 30px;
}
</style>
<script>
//some random data:
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
data = [];
var minmaxdate = {'min':new Date(2014,0,1),'max':new Date()}
n = 50;
for (i=1;i<=n;i++) {
data.push(randomDate(minmaxdate['min'], minmaxdate['max']));
//data.push(Math.random());
}
var $chart = $('#chart');
var graphic_data = data; //we need this (??)
var graphic_minmaxdate = minmaxdate;
function drawGraphic() {
var margin = { top: 10, right: 30, bottom: 30, left: 40 };
var width = $chart.width() - margin.left - margin.right;
var timelineplot = [{
"data": graphic_data,
"margin": margin,
"minmaxdate": graphic_minmaxdate,
"size":{"width":width,"height":70},
}];
// clear out existing graphics
$chart.empty();
var svg = d3.select("#chart")
.append("svg")
.attr("width",timelineplot[0]['size']['width'])
.attr("height",timelineplot[0]['size']['height']);
/* Initialize tooltip */
/* tip = d3.tip().attr('class', 'd3-tip').html(function(d) {
return "<span class=\'stronger\'>" + d + "</span><br>";
});*/
/* Invoke the tip in the context of your visualization */
/*svg.call(tip)*/
var tlp = d3.timelineplot()
.data(function(d) {return d.data})
.margin(function(d) {return d.margin})
.minmaxdate(function(d) {return d.minmaxdate})
var timeline = svg.selectAll(".timelineplot")
.data(timelineplot)
.enter()
.append("svg:g")
.attr("transform", "translate(" + timelineplot[0].margin.left + "," + timelineplot[0].margin.top + ")")
.call(tlp);
}
if (Modernizr.svg) { // if svg is supported, draw dynamic chart
drawGraphic();
window.onresize = drawGraphic;
}
</script>
/* Modernizr 2.8.3 (Custom Build) | MIT & BSD
* Build: http://modernizr.com/download/#-svg
*/
;window.Modernizr=function(a,b,c){function u(a){i.cssText=a}function v(a,b){return u(prefixes.join(a+";")+(b||""))}function w(a,b){return typeof a===b}function x(a,b){return!!~(""+a).indexOf(b)}function y(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:w(f,"function")?f.bind(d||b):f}return!1}var d="2.8.3",e={},f=b.documentElement,g="modernizr",h=b.createElement(g),i=h.style,j,k={}.toString,l={svg:"http://www.w3.org/2000/svg"},m={},n={},o={},p=[],q=p.slice,r,s={}.hasOwnProperty,t;!w(s,"undefined")&&!w(s.call,"undefined")?t=function(a,b){return s.call(a,b)}:t=function(a,b){return b in a&&w(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=q.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(q.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(q.call(arguments)))};return e}),m.svg=function(){return!!b.createElementNS&&!!b.createElementNS(l.svg,"svg").createSVGRect};for(var z in m)t(m,z)&&(r=z.toLowerCase(),e[r]=m[z](),p.push((e[r]?"":"no-")+r));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)t(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof enableClasses!="undefined"&&enableClasses&&(f.className+=" "+(b?"":"no-")+a),e[a]=b}return e},u(""),h=j=null,e._version=d,e}(this,this.document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment