I recently upgraded my D3ResponsiveGraphs library and added a new type of graph. D3LineChart is a line chart that supports negative values, responsive design, legends, tooltips, transitions, and ability to show data in a table view. My focus is on keeping the library modular, lightweight, and easy to use. With this new release, I created a D3Core module that covers most of the functionality that’s shared across several types of graphs. With this approach, I can very easily build new graphs and reuse most of the functionality.
Demo
Please notice that responsiveness doesn’t work here, because the demo is inserted through iframe. However, you can open the demo in a new page.
Usage
Html:
Javascript:
container: "#linechart"
});
linechart.show();
Data Structure
Data can be obtained from AJAX GET request (if dataUrl
property is used) or can be directly assigned to a data
property. Data has to have the following format with all the values
arrays having the same lengths:
{ key: "category 1", values: [{ x: 2013, y: -10 }, { x: 2014, y: 10 } ]},
{ key: "category 2", values: [{ x: 2013, y: -30 }, { x: 2014, y: 10 } ]},
{ key: "category 3", values: [{ x: 2013, y: 30 }, { x: 2014, y: 30 } ]}
]
Demo Source Code Example
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3LineChart</title>
<meta name="description" content="Demo example of D3LineChart">
<meta name="author" content="Matous Havlena (@matoushavlena)">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="./css/d3.linechart.css">
<script src="./js/d3.core.js" charset="utf-8"></script>
<script src="./js/d3.linechart.js" charset="utf-8"></script>
</head>
<body>
<div id="linechart"></div>
<button id="button">Generate Random Dataset</button>
<script type="text/javascript">
$(document).ready(function() {
var linechart = new D3LineChart({
container: "#linechart"
});
linechart.show();
$("#button").on("click", function() {
var newData = new Array();
var year = getRandomInt(2005, 2014);
var numCategories = getRandomInt(1, 10);
for (var i=0; i<numCategories; i++) {
var category = {};
category.key = "category "+i;
category.values = new Array();
for (var j=year; j<=2015; j++) {
category.values.push({ x: j, y: getRandomInt(-50, 50) });
};
newData.push(category);
}
linechart.dataset = newData;
linechart.update();
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
});
</script>
</body>
</html>
Source Code and Documentation
There is an extensive set of options that support flexibility and reusability of the graph. Please visit my GitHub D3ResponsiveGraphs repository for up-to-date documentation and source code.
it doesnt appear that the line chart supports date objects