<!DOCTYPE html> <html lang="en"> <head> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-3523953066677938", enable_page_level_ads: true }); </script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-79254642-6"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-79254642-6'); </script> <meta charset="utf-8"> <title>Line plot with dropdown to select group in d3.js</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="Create a line plot with a dropdown button to select data series. Group are stored in distincts column of .csv input. D3.js code and explanation provided."> <meta name="keywords" content="Data, Dataviz, Datavisualization, Javascript, JS, d3.js, connected scatter plot"> <meta name="author" content="Yan Holtz"> <link rel="icon" href="../img/logo/D3_single_small.png"> <meta property="og:title" content="Line plot with dropdown to select group in d3.js"> <meta property="og:image" content="https://www.d3-graph-gallery.com/img/logo/D3_full_medium.png"> <meta property="og:description" content="Create a line plot with a dropdown button to select data series. Group are stored in distincts column of .csv input. D3.js code and explanation provided."> <!-- Bootstrap core CSS --> <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="../css/agency.css" rel="stylesheet"> <!-- PRISM --> <script src="../LIB/prism.js"></script> <link href="../LIB/prism.css" rel="stylesheet" /> <!-- D3.JS v4 --> <script src="../js/d3.v4.js"></script> <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> <!-- JQUERY --> <script src="../vendor/jquery/jquery.min.js"></script> <!-- HTML TO CANVAS --> <script src="../js/html2canvas.js"></script> <!-- Function to parse html and js code chunks made by Yan Holtz --> <script src="../js/myParser.js"></script> </head> <body id="page-top"> <!-- THIS ALLOWS TO INSERT THE MENU THAT IS STORED IN A MENU.HTML FILE--> <nav class="navbar navbar-expand-lg fixed-top" id="mainNav"></nav> <script> $(function(){ $("#mainNav").load("../html_chunk/menu.html"); }); </script> <!-- THIS ALLOWS TO INSERT THE MODAL OF THE MENU THAT IS STORED IN A MENU_MODAL.HTML FILE--> <div id="modal_menu_insertion"> </div> <script> $(function(){ $("#modal_menu_insertion").load("../html_chunk/menu_modal.html"); }); </script> <!-- Header --> <header class="masthead"> <div class="textlanding"> <h1>Line plot with dropdown to select group in d3.js</h1> <hr class="short_hr"> <br> <ul class="list-inline social-buttons"> <li class="list-inline-item"> <a href="https://twitter.com/R_Graph_Gallery"> <i class="fa fa-twitter"></i> </a> </li> <li class="list-inline-item social-buttons"> <a href="https://github.com/holtzy"> <i class="fa fa-github" style="color: white"></i> </a> </li> <li class="list-inline-item social-buttons"> <a href="https://www.linkedin.com/in/yan-holtz-2477534a/"> <i class="fa fa-linkedin"></i> </a> </li> <li class="list-inline-item social-buttons"> <a href="https://www.yan-holtz.com"> <i class="fa fa-home"></i> </a> </li> </ul> <br><br> <p style="max-width: 700px; margin: auto">This post describes how to build a <a href="../line.html">line plot</a> with a dropdown button to select group in d3.js. It follows the previous <a href="line_basic.html">basic line plot</a>. Note that all groups are stored in different column of the <code>.csv</code> input file.</p> <br> <a class="btn btn-secondary btn-md text-uppercase" href="../line.html">Line chart section</a> <button class="btn btn-secondary btn-md text-uppercase" onclick="myCodeDownload('chart_example_from_d3-graph-gallery.html', 'code', 'codejs')">Download code</button> </div> </header> <section style="padding-top: 20px; padding-bottom: 20px"> <div class="container" > <div class="row"> <!-- ==================== GRAPH SECTION = WHERE THE GRAPH APPEARS ==================== --> <div class="col-lg-5 .align-middle"> <div style="position: -webkit-sticky; position: sticky; top: 120px"> <div class="bg-light" id="result" ></div> <br> <div> <h5>Steps:</h5> <ul> <br> <li>First, you need to understand how to build a <a href="line_basic.html">basic line chart</a>.</li> <br> <li>Here the <a href="https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_connectedscatter.csv">input dataset</a> is composed by several columns: one per group.</li> <br> <li>Chart is initialized using the first group.</li> <br> <li>Then a <code>update()</code> function is created. It smoothly transforms the chart with the value of another column</li> <br> <li>This function is triggered whenever the <code>select</code> button is changed.</li> </ul> </div> </div> </div> <!-- ================================================================================= --> <!-- ==================== CODE SECTION = WHERE THE CODE APPEARS ==================== --> <div class="col-lg-7 text-center .align-middle"> <!-- ========= show html code ============== --> <aside style="position: -webkit-sticky; position: sticky; top: 120px">← Edit me! </aside> <pre class="language-html"><code id="code" contenteditable="true"><xmp><!DOCTYPE html> <meta charset="utf-8"> <!-- Load d3.js --> <script src="https://d3js.org/d3.v4.js"></script> <!-- Initialize a select button --> <select id="selectButton"></select> <!-- Create a div where the graph will take place --> <div id="my_dataviz"></div> <!-- Color Scale --> <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> </xmp></code></pre> <!-- ==================================== --> <!-- ========= show JS code ============== --> <pre class="language-js"><code id="codejs" contenteditable="true"><xmp><script> // set the dimensions and margins of the graph var margin = {top: 10, right: 100, bottom: 30, left: 30}, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // append the svg object to the body of the page var svg = d3.select("#my_dataviz") .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 + ")"); //Read the data d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_connectedscatter.csv", function(data) { // List of groups (here I have one group per column) var allGroup = ["valueA", "valueB", "valueC"] // add the options to the button d3.select("#selectButton") .selectAll('myOptions') .data(allGroup) .enter() .append('option') .text(function (d) { return d; }) // text showed in the menu .attr("value", function (d) { return d; }) // corresponding value returned by the button // A color scale: one color for each group var myColor = d3.scaleOrdinal() .domain(allGroup) .range(d3.schemeSet2); // Add X axis --> it is a date format var x = d3.scaleLinear() .domain([0,10]) .range([ 0, width ]); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); // Add Y axis var y = d3.scaleLinear() .domain( [0,20]) .range([ height, 0 ]); svg.append("g") .call(d3.axisLeft(y)); // Initialize line with group a var line = svg .append('g') .append("path") .datum(data) .attr("d", d3.line() .x(function(d) { return x(+d.time) }) .y(function(d) { return y(+d.valueA) }) ) .attr("stroke", function(d){ return myColor("valueA") }) .style("stroke-width", 4) .style("fill", "none") // A function that update the chart function update(selectedGroup) { // Create new data with the selection? var dataFilter = data.map(function(d){return {time: d.time, value:d[selectedGroup]} }) // Give these new data to update line line .datum(dataFilter) .transition() .duration(1000) .attr("d", d3.line() .x(function(d) { return x(+d.time) }) .y(function(d) { return y(+d.value) }) ) .attr("stroke", function(d){ return myColor(selectedGroup) }) } // When the button is changed, run the updateChart function d3.select("#selectButton").on("change", function(d) { // recover the option that has been chosen var selectedOption = d3.select(this).property("value") // run the updateChart function with this selected option update(selectedOption) }) }) </script></xmp></code></pre> <!-- ==================================== --> <!-- ==================== JAVASCRIPT SECTION : EXECUTE THIS CODE AND MAKE IT INTERACTIVE ==================== --> <script> // At the beginning, I read the html and JS fragments myHtmlParser('code', 'result') myJSParser('codejs', 'result') // If the user change the JS fragment, I run it again: document.getElementById('codejs').addEventListener("input", function() { d3.select('#result').html(""); myHtmlParser('code', 'result'); myJSParser('codejs', 'result'); }) // If the user change the HTML fragment, I run it again: document.getElementById('code').addEventListener("input", function() { d3.select('#result').html(""); myHtmlParser('code', 'result'); myJSParser('codejs', 'result'); }) </script> </div> </div> </div> </section> <br> <!-- ============================ --> <!-- ============================ RELATED BLOCKS ============================ --> <section class="bg-light" style="padding-top: 70px; padding-bottom: 70px"> <div class="container"> <div class="row"> <div class="col-lg-5 text-center align-self-center"> <h3 class="text-uppercase">Related blocks →</h3> </div> <div class="col-lg-5"> <ul> <li><i>Line Chart - </i><a href="https://bl.ocks.org/mbostock/3883245">link</a></li> <br> <li><i>Multi Series Line Chart - </i>by <a href="https://bl.ocks.org/salvob41/df700ff6bbeed285de043955785775c5">SalvoB</a></li> <br> <li><i>Basic line plot - </i>by <a href="line_basic.html">d3 graph gallery</a></li> <br> <li><i>Scatterplot with Multiple Series - </i>by <a href="https://bl.ocks.org/mbostock/3183403">Mike Bostock</a></li> <br> <li><i>Line and Point transitions - </i>by <a href="https://bl.ocks.org/NGuernse/58e1057b7174fd1717993e3f5913d1a7">Nick Guernsey's</a></li> <br> </ul> </div> </div> </div> </section> <!-- ============================ CONTACT SECTION ============================ --> <!-- ANCHOR --> <a name="contactanchor"></a> <section id="contact" class="bg" style="background-color: white"></section> <!-- THIS ALLOWS TO INSERT THE CONTACT CHUNK THAT IS STORED IN A CONTACT.HTML FILE--> <script> $(function(){ $("#contact").load("../html_chunk/contact.html"); }); </script> <!-- ============================ FOOTER SECTION ============================ --> <footer class="bg-light" id="myFooter"></footer> <!-- THIS ALLOWS TO INSERT THE FOOTER THAT IS STORED IN A FOOTER.HTML FILE--> <script> $(function(){ $("#myFooter").load("../html_chunk/footer.html"); }); </script> <!-- ============================ --> <!-- ============================ JAVASCRIPT SECTION ============================ --> <!-- Bootstrap core JavaScript --> <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Custom scripts for this template --> <script src="../js/agency.min.js"></script> <!-- Activate the bootstrap tooltip, must be after jQuery load --> <script> $(function () { $('[data-toggle="tooltip"]').tooltip() }) </script> <!-- Function to download the content of the div --> <script> function download(){ var a = document.body.appendChild( document.createElement("a") ); a.download = "export.html"; var command = document.getElementById('code').innerHTML; command = command.replace(/<\/?span[^>]*>/g,""); a.href = "data:html" + command a.click(); // Trigger a click on the element } </script> </body> </html>