Skip to content

Sample chart (your first nvd3 chart!)

Andrew Tseng edited this page Feb 27, 2014 · 1 revision

This guide will help you create your first nvd3.js chart, a simple line graph which graphs the function f(x)=100/x.

HTML Skeleton

Start with an HTML file: mychart.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>My First Chart</title>
		<link href="nv.d3.css" rel="stylesheet" type="text/css">
		<script src="d3.v3.js"></script>
		<script src="nv.d3.js"></script>
	</head>
	<body>
		<svg style='height:600px'/>

		<script src="mychart.js"></script>
	</body>
</html>
  • Make sure to include correct HTML5 boilerplate, including the DOCTYPE and character set meta tag.
  • Include d3.v3.js, nv.d3.js and nv.d3.css.
  • Create a single <svg/> element which will contain the chart.
  • Include mychart.js, which will hold our chart initialization code.

Chart initialization code

In mychart.js, include the following lines:

function myData() {
	var series1 = [];
	for(var i =1; i < 100; i ++) {
		series1.push({
			x: i, y: 100 / i
		});
	}

	return [
		{
			key: "Series #1",
			values: series1,
			color: "#0000ff"
		}
	];
}

nv.addGraph(function() {
	var chart = nv.models.lineChart();

	chart.xAxis
		.axisLabel("X-axis Label");

	chart.yAxis
		.axisLabel("Y-axis Label")
		.tickFormat(d3.format("d"))
		;

	d3.select("svg")
		.datum(myData())
		.transition().duration(500).call(chart);

	nv.utils.windowResize(
			function() {
				chart.update();
			}
		);

	return chart;
});

Load mychart.html, and you should see the following:

Data Format

Data for line charts (and most charts in nvd3.js) are in the following JSON format:

[
	{
		key: "<Series name>",
		color: "<CSS color>",
		values: [
			{x: 0, y: 10},
			{x: 1, y: 20},
			{x: 2, y: 30}
			....
		]
	},
	{
		key: "<Series name>"
		...
	}
]

The myData() function generates a sample set in the above format.

Annotated Source

nv.addGraph(function() {				//This adds the chart to a global rendering queue.
	var chart = nv.models.lineChart();	//Create instance of nvd3 lineChart

	chart.xAxis
		.axisLabel("X-axis Label");		//Set X-axis attributes

	chart.yAxis
		.axisLabel("Y-axis Label")		//Set Y-Axis attributes.
		.tickFormat(d3.format("d"))		//Set Y-Axis label formatting.
		;

	d3.select("svg")					//Select the document's <svg> element
		.datum(myData())				//Attach data to the <svg> element.
		.transition().duration(500).call(chart);	//Define transition and pass the d3.selection to our lineChart.

	nv.utils.windowResize(				//Updates the window resize event callback.
			function() {
				chart.update();			//Renders the chart when window is resized.
			}
		);

	return chart;	//Must return the enclosed chart variable so the global rendering queue can store it.
});

Conclusion

As you can see, nvd3.js is a very powerful library for rendering web based charts. It handles much of the scaling and plotting, so you only ever need to concern yourself with the data.