{"id":273899,"date":"2018-07-19T06:58:20","date_gmt":"2018-07-19T13:58:20","guid":{"rendered":"http:\/\/css-tricks.com\/?p=273899"},"modified":"2018-07-20T07:08:04","modified_gmt":"2018-07-20T14:08:04","slug":"how-to-make-a-modern-dashboard-with-nvd3-js","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/how-to-make-a-modern-dashboard-with-nvd3-js\/","title":{"rendered":"How to make a modern dashboard with NVD3.js"},"content":{"rendered":"

NVD3.js<\/a> is a JavaScript visualization library that is free to use and open source. It\u2019s derived from the well-known d3.js<\/a> visualization library. When used the right way, this library can be extremely powerful for everyday tasks and even business operations.<\/p>\n

For example, an online dashboard. We can use NVD3.js to compile data into a centralized space that visualizes the information in neat charts and graphs. That\u2019s what we\u2019re going to look at in this post.<\/p>\n

<\/p>\n

Making a dashboard with NVD3.js for the first time is daunting, but after this tutorial, you should have the required knowledge to get your hands dirty and start building something awesome. Personally, I have a passion for visualizations on the web. They are both beautiful and meaningful at the same time.<\/p>\n

Real-world use case: A data dashboard<\/h3>\n

Dashboards can be used for pretty much anything. As long as you’ve got data to analyze, you\u2019re good to go, whether that be some sales data or the average weather for the last 20 years. Let\u2019s build something like this:<\/p>\n

See the Pen Dashboard NVD3.JS<\/a> by Danny Englishby (@DanEnglishby<\/a>) on CodePen<\/a>.<\/p>\n

Setting up the environment<\/h3>\n

To setup an NVD3 chart, we require three things:<\/p>\n

    \n
  1. The NVD3 JavaScript library<\/li>\n
  2. The NVD3 CSS library<\/li>\n
  3. The D3.js library (a dependency for NVD3)<\/li>\n<\/ol>\n

    All of these are available through Cloudflare’s CDN network<\/a>. Here\u2019s an HTML template with all those resources ready to go:<\/p>\n

    <!doctype html>\r\n<html lang=\"en\">\r\n<head>\r\n  <meta charset=\"utf-8\">\r\n  <title>Making a Dashboard<\/title>\r\n  <link rel=\"stylesheet\" href=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/nvd3\/1.8.6\/nv.d3.css\">\r\n<\/head>\r\n<body>\r\n  \r\n\r\n<script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/d3\/3.5.2\/d3.min.js\"><\/script>\r\n<script src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/nvd3\/1.8.6\/nv.d3.js\"><\/script>\r\n<\/body>\r\n<\/html><\/code><\/pre>\n

    Data sources<\/h3>\n

    For this tutorial, I thought using some raw, factual data that\u2019s already been formatted into JSON would be easiest. I\u2019m using two sources of information: one about global average temperatures over time<\/a> and the other reporting world population statistics<\/a>. I’ve already formatted the data into JSON, so it’s ready to copy and paste! <\/p>\n

    Creating a line chart<\/h3>\n

    Let\u2019s go ahead and create a line chart with some global temperature data. The raw data I’ve put together in JSON represents the last twenty years of temperature changes compared to the global average.<\/p>\n

    First, we\u2019ll add a placeholder element for the chart to attach to when the JavaScript is executed.<\/p>\n

    <div id=\"averageDegreesLineChart\" class='with-3d-shadow with-transitions averageDegreesLineChart'>\r\n  <svg><\/svg>\r\n<\/div><\/code><\/pre>\n

    Then add the following JSON in some script tags before the <\/body><\/code> tag:<\/p>\n

    var temperatureIndexJSON = [\r\n  {\r\n    key: \"Temp +- Avg.\",\r\n    values: [{ \"x\": 1998, \"y\": 0.45 }, { \"x\": 1999, \"y\": 0.48 }, { \"x\": 2000, \"y\": 0.5 }, { \"x\": 2001, \"y\": 0.52 }, { \"x\": 2002, \"y\": 0.55 }, { \"x\": 2003, \"y\": 0.58 }, { \"x\": 2004, \"y\": 0.6 }, { \"x\": 2005, \"y\": 0.61 }, { \"x\": 2006, \"y\": 0.61 }, { \"x\": 2007, \"y\": 0.61 }, { \"x\": 2008, \"y\": 0.62 }, { \"x\": 2009, \"y\": 0.62 }, { \"x\": 2010, \"y\": 0.62 }, { \"x\": 2011, \"y\": 0.63 }, { \"x\": 2012, \"y\": 0.67 }, { \"x\": 2013, \"y\": 0.71 }, { \"x\": 2014, \"y\": 0.77 }, { \"x\": 2015, \"y\": 0.83 }, { \"x\": 2016, \"y\": 0.89 }, { \"x\": 2017, \"y\": 0.95 }]\r\n  }\r\n];<\/code><\/pre>\n

    The x<\/code> value is the year and they<\/code> value is the temperature in Celsius degrees.<\/p>\n

    The last piece to the puzzle is the most important function that creates the chart. The function named nv.addGraph()<\/code> is the main function used throughout NVD3 and, within it, you initialize the chart object. In this example, we are using the lineChart<\/code> object which can have methods chained to it, depending on what the visual requirements may be.<\/p>\n

    Check out the JavaScript comments to see the which each line does.<\/p>\n

    nv.addGraph(function () {\r\n  var chart = nv.models.lineChart() \/\/ Initialise the lineChart object.\r\n    .useInteractiveGuideline(true); \/\/ Turn on interactive guideline (tooltips) \r\nchart.xAxis\r\n    .axisLabel('TimeStamp (Year)'); \/\/ Set the label of the xAxis (Vertical)\r\nchart.yAxis\r\n    .axisLabel('Degrees (c)') \/\/ Set the label of the xAxis (Horizontal)\r\n    .tickFormat(d3.format('.02f')); \/\/ Rounded Numbers Format.\r\nd3.select('#averageDegreesLineChart svg') \/\/ Select the ID of the html element we defined earlier.\r\n    .datum(temperatureIndexJSON) \/\/ Pass in the JSON\r\n    .transition().duration(500) \/\/ Set transition speed\r\n    .call(chart); \/\/ Call & Render the chart\r\n  nv.utils.windowResize(chart.update); \/\/ Intitiate listener for window resize so the chart responds and changes width.\r\n  return;\r\n});<\/code><\/pre>\n

    See the Pen Line Chart NVD3.JS<\/a> by Danny Englishby (@DanEnglishby<\/a>) on CodePen<\/a>.<\/p>\n

    Creating two bar charts for the price of one<\/h3>\n

    You will love the minimal effort of these next two charts. The power of NVD3.js enables switching between chart types. You can either have the toggle active so users can switch between a standard bar chart or a stacked bar chart. Or you can force the chart type and make it unchangeable.<\/p>\n

    The following examples show exactly how to do it.<\/p>\n

    Stacked multi-bar chart<\/h3>\n

    You know those bar charts that stack two values together in the same bar? That\u2019s what we\u2019re doing here.<\/p>\n

    <div id=\"worldPopulationMultiBar\" class=\"with-3d-shadow with-transitions worldPopulationMultiBar\">\r\n  <svg><\/svg>\r\n<\/div><\/code><\/pre>\n
    var populationBySexAndCountryJSON =[{\"key\":\"Male\",\"color\":\"#d62728\",\"values\":[{\"label\":\"China\",\"value\":717723466.166},{\"label\":\"India\",\"value\":647356171.132},{\"label\":\"United States of America\",\"value\":157464952.272},{\"label\":\"Indonesia\",\"value\":125682412.393},{\"label\":\"Brazil\",\"value\":98578067.1},{\"label\":\"Pakistan\",\"value\":93621293.316},{\"label\":\"Nigeria\",\"value\":88370210.605},{\"label\":\"Bangladesh\",\"value\":79237050.772},{\"label\":\"Russian Federation\",\"value\":65846330.629},{\"label\":\"Japan\",\"value\":61918921.999}]},{\"key\":\"Female\",\"color\":\"#1f77b4\",\"values\":[{\"label\":\"China\",\"value\":667843070.834},{\"label\":\"India\",\"value\":604783424.868},{\"label\":\"United States of America\",\"value\":162585763.728},{\"label\":\"Indonesia\",\"value\":124183218.607},{\"label\":\"Brazil\",\"value\":101783857.9},{\"label\":\"Pakistan\",\"value\":88521300.684},{\"label\":\"Nigeria\",\"value\":85245134.395},{\"label\":\"Bangladesh\",\"value\":77357911.228},{\"label\":\"Russian Federation\",\"value\":76987358.371},{\"label\":\"Japan\",\"value\":65224655.001}]}];\r\n\r\nnv.addGraph(function ()\r\n{\r\n  var chart = nv.models.multiBarChart()\r\n    .x(function (d) {\r\n      return d.label; \/\/ Configure x axis to use the \"label\" within the json.\r\n    })\r\n    .y(function (d) {\r\n      return d.value; \/\/ Configure y axis to use the \"value\" within the json.\r\n    }).margin({top: 30, right: 20, bottom: 50, left: 85}) \/\/ Add some CSS Margin to the chart.\r\n    .showControls(false) \/\/ Turn of switchable control\r\n    .stacked(true); \/\/ Force stacked mode.\r\n\r\n  chart.xAxis.axisLabel('Countries'); \/\/ add label to the horizontal axis\r\n\r\n  chart.yAxis.tickFormat(d3.format('0f')); \/\/ Round the yAxis values\r\n\r\n  d3.select('#worldPopulationMultiBar svg') \/\/ Select the html element by ID\r\n    .datum(populationBySexAndCountryJSON) \/\/ Pass in the data\r\n    .transition().duration(500) \/\/ Set transition speed\r\n    .call(chart); \/\/ Call & Render chart\r\n  \r\n  nv.utils.windowResize(chart.update); \/\/ Intitiate listener for window resize so the chart responds and changes width.\r\n  return;\r\n});<\/code><\/pre>\n

    The two important settings in the JavaScript here are the .showControls<\/code> and .stacked<\/code> booleans. They both do what they say on the tin: force the graph to a stacked bar chart and don’t allow switching of the chart type. You will see what I mean by switching soon.<\/p>\n

    See the Pen Multi StackedBar NVD3.JS<\/a> by Danny Englishby (@DanEnglishby<\/a>) on CodePen<\/a>.<\/p>\n

    Standard multi-bar chart<\/h3>\n

    Now, let\u2019s do something a little more traditional and compare values side-by-side instead of stacking them in the same bar.<\/p>\n

    This uses pretty much the same code as the stacked examples, but we can change the .stacked<\/code> boolean value to false<\/code>. This will, of course, make the stacked bar chart a normal bar chart.<\/p>\n

    <div id=\"worldPopulationMultiBar\" class=\"with-3d-shadow with-transitions worldPopulationMultiBar\">\r\n  <svg><\/svg>\r\n<\/div><\/code><\/pre>\n
    var populationBySexAndCountryJSON = [{\"key\":\"Male\",\"color\":\"#d62728\",\"values\":[{\"label\":\"China\",\"value\":717723466.166},{\"label\":\"India\",\"value\":647356171.132},{\"label\":\"United States of America\",\"value\":157464952.272},{\"label\":\"Indonesia\",\"value\":125682412.393},{\"label\":\"Brazil\",\"value\":98578067.1},{\"label\":\"Pakistan\",\"value\":93621293.316},{\"label\":\"Nigeria\",\"value\":88370210.605},{\"label\":\"Bangladesh\",\"value\":79237050.772},{\"label\":\"Russian Federation\",\"value\":65846330.629},{\"label\":\"Japan\",\"value\":61918921.999}]},{\"key\":\"Female\",\"color\":\"#1f77b4\",\"values\":[{\"label\":\"China\",\"value\":667843070.834},{\"label\":\"India\",\"value\":604783424.868},{\"label\":\"United States of America\",\"value\":162585763.728},{\"label\":\"Indonesia\",\"value\":124183218.607},{\"label\":\"Brazil\",\"value\":101783857.9},{\"label\":\"Pakistan\",\"value\":88521300.684},{\"label\":\"Nigeria\",\"value\":85245134.395},{\"label\":\"Bangladesh\",\"value\":77357911.228},{\"label\":\"Russian Federation\",\"value\":76987358.371},{\"label\":\"Japan\",\"value\":65224655.001}]}];\r\n\r\nnv.addGraph(function () {\r\n  var chart = nv.models.multiBarChart()\r\n    .x(function (d) {\r\n      return d.label; \/\/ Configure x axis to use the \"label\" within the json.\r\n    })\r\n    .y(function (d) {\r\n      return d.value; \/\/ Configure y axis to use the \"value\" within the json.\r\n    }).margin({top: 30, right: 20, bottom: 50, left: 85}) \/\/ Add some CSS Margin to the chart.\r\n    .showControls(false) \/\/ Turn of switchable control\r\n    .stacked(false); \/\/ ***Force normal bar mode.***\r\n\r\n  chart.xAxis.axisLabel('Countries'); \/\/ add label to the horizontal axis\r\n\r\n  chart.yAxis.tickFormat(d3.format('0f')); \/\/ Round the yAxis values\r\n\r\n  d3.select('#worldPopulationMultiBar svg') \/\/ Select the html element by ID\r\n    .datum(populationBySexAndCountryJSON) \/\/ Pass in the data\r\n    .transition().duration(500) \/\/ Set transition speed\r\n    .call(chart); \/\/ Call & Render chart\r\n\r\n  nv.utils.windowResize(chart.update); \/\/ Intitiate listener for window resize so the chart responds and changes width.\r\n\r\n  return;\r\n});<\/code><\/pre>\n

    The one change to the settings presents us with a brand-new looking chart.<\/p>\n

    See the Pen Multi Bar NVD3.JS<\/a> by Danny Englishby (@DanEnglishby<\/a>) on CodePen<\/a>.<\/p>\n

    Using one code set with minimal changes, you just created two epic charts for the price of one. Kudos for you!<\/p>\n

    There is one last setting, of course, if you want the functionality of switching charts. Change the .showControls<\/code> to true<\/code> and remove the .stacked<\/code> option. You will notice some controls at the top of the chart. Clicking them will toggle the view between a stacked and standard chart.<\/p>\n

    See the Pen Multi Bar Switchable NVD3.JS<\/a> by Danny Englishby (@DanEnglishby<\/a>) on CodePen<\/a>.<\/p>\n

    Making a dashboard<\/h3>\n

    There’s nothing I love looking at more in the world of web development than dashboards. They never get old and are super good looking. By using the charting techniques we\u2019ve already covered, we can make our own responsive dashboard on a single webpage.<\/p>\n

    If you remember within the JavaScript snippets earlier, there was a function set with a listener against each chart: nv.utils.windowResize(chart.update);<\/code><\/p>\n

    This magical function, resizes the chart for you as if it was set to width: 100%<\/code> in CSS. But it doesn’t just shrink<\/em>, but also moves and restructures the graph according to the size of the screen. It’s pretty awesome! All we need to worry about it are the heights. We can set this up by applying flexbox to the classes assigned to chart elements.<\/p>\n

    Let\u2019s bundle everything we have so far into one dashboard by wrapping each chart element in a flexbox container. Apply a small amount of CSS for the flexing and height, and finally, compile all the scripts into one (or, you can keep them separate in your own project). <\/p>\n

    See the Pen Dashboard NVD3.JS<\/a> by Danny Englishby (@DanEnglishby<\/a>) on CodePen<\/a>.<\/p>\n

    Summary<\/h3>\n

    This tutorial will hopefully give you the knowledge to get started with building data visualizations and, ultimately, add them into a production dashboard. Even if you only want to play with these concepts, I’m sure your mind will start running with ideas for how to transform different types of data into stunning visuals.<\/p>\n","protected":false},"excerpt":{"rendered":"

    NVD3.js is a JavaScript visualization library that is free to use and open source. It\u2019s derived from the well-known d3.js visualization library. When used the right way, this library can be extremely powerful for everyday tasks and even business operations. For example, an online dashboard. We can use NVD3.js to compile data into a centralized […]<\/p>\n","protected":false},"author":253645,"featured_media":273900,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"sig_custom_text":"","sig_image_type":"featured-image","sig_custom_image":0,"sig_is_disabled":false,"inline_featured_image":false,"c2c_always_allow_admin_comments":false,"footnotes":"","jetpack_publicize_message":"How to make a modern dashboard with NVD3.js","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":[]},"categories":[4],"tags":[881,1341],"jetpack_publicize_connections":[],"acf":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2018\/07\/dashboard-charts.jpg?fit=1200%2C600&ssl=1","jetpack-related-posts":[{"id":286756,"url":"https:\/\/css-tricks.com\/the-many-ways-of-getting-data-into-charts\/","url_meta":{"origin":273899,"position":0},"title":"The Many Ways of Getting Data Into Charts","date":"May 1, 2019","format":false,"excerpt":"Data is available everywhere nowadays, whether it\u2019s in a plain text file, a REST API, an online Google sheet\u2026 you name it! It\u2019s that variety of context that makes building graphs more than simply having a database in your local project \u2014 where there is data, there is a way.\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2019\/02\/bar-chart.png?fit=1200%2C600&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":259513,"url":"https:\/\/css-tricks.com\/react-dataviz\/","url_meta":{"origin":273899,"position":1},"title":"React + Dataviz","date":"September 18, 2017","format":false,"excerpt":"There is a natural connection between Data Visualization (dataviz) and SVG. SVG is a graphics format based on geometry and geometry is exactly what is needed to visually display data in compelling and accurate ways. SVG has got the \"visualization\" part, but SVG is more declarative than programmatic. To write\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2017\/09\/reactdataviz.png?fit=1000%2C412&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":291942,"url":"https:\/\/css-tricks.com\/introducing-netlify-analytics\/","url_meta":{"origin":273899,"position":2},"title":"Introducing Netlify Analytics","date":"July 10, 2019","format":false,"excerpt":"You work a while on a side project. You think it's pretty cool! You decide to release it into the world. And then\u2026 it goes well. Or it doesn\u2019t go well. Wait, is that right? You forgot to add analytics \u2014 it just didn\u2019t cross your mind at the time.\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2019\/07\/twitter-analytics-3.png?fit=1024%2C512&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":198588,"url":"https:\/\/css-tricks.com\/textures-js\/","url_meta":{"origin":273899,"position":3},"title":"Textures.js","date":"March 20, 2015","format":false,"excerpt":"SVG patterns for Data Visualization by Riccardo Scalco. This is like all my favorite web things smashed together. Beautiful design, SVG, accessibility, programmatic control with JavaScript, and open source. #swoon","rel":"","context":"In "Link"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":303676,"url":"https:\/\/css-tricks.com\/the-unseen-performance-costs-of-modern-css-in-js-libraries\/","url_meta":{"origin":273899,"position":4},"title":"The Unseen Performance Costs of Modern CSS-in-JS Libraries","date":"February 13, 2020","format":false,"excerpt":"This article is full of a bunch of data from Aggelos Arvanitakis. But lemme just focus on his final bit of advice: Investigate whether a zero-runtime CSS-in-JS library can work for your project. Sometimes we tend to prefer writing CSS in JS for the DX (developer experience) it offers, without\u2026","rel":"","context":"In "Link"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2018\/05\/css-in-js.jpg?fit=1200%2C600&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":333087,"url":"https:\/\/css-tricks.com\/embedding-an-interactive-analytics-component-with-cumul-io-and-any-web-framework\/","url_meta":{"origin":273899,"position":5},"title":"Embedding an Interactive Analytics Component with Cumul.io and Any Web Framework","date":"January 28, 2021","format":false,"excerpt":"In this article, we explain how to build an integrated and interactive data visualization layer into an application with Cumul.io. To do so, we\u2019ve built a demo application that visualizes Spotify Playlist analytics! We use Cumul.io as our interactive dashboard as it makes integration super easy and provides functionality that\u2026","rel":"","context":"In "Sponsored"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2021\/01\/0Uz2iFHvwRHTq4Gnz.gif?fit=1200%2C583&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]}],"featured_media_src_url":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2018\/07\/dashboard-charts.jpg?fit=1024%2C512&ssl=1","_links":{"self":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/273899"}],"collection":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/users\/253645"}],"replies":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/comments?post=273899"}],"version-history":[{"count":5,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/273899\/revisions"}],"predecessor-version":[{"id":274406,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/273899\/revisions\/274406"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/media\/273900"}],"wp:attachment":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/media?parent=273899"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/categories?post=273899"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/tags?post=273899"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}