Advertisement
dhshin

line_chart_2

Mar 25th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 2.25 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.   <meta charset="utf-8">
  5.   <meta name="viewport" content="width=device-width">
  6.   <title>JS Bin</title>
  7. </head>
  8. <body>
  9.   <svg width="960" height="500"></svg>
  10.   <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.3/d3.min.js"></script>
  11.   <script>
  12.    
  13.     function ready(fn) {
  14.       if (document.readyState != 'loading'){
  15.         fn();
  16.       } else {
  17.         document.addEventListener('DOMContentLoaded', fn);
  18.       }
  19.     }
  20.    
  21.     ready(init);
  22.    
  23.     function init() {
  24.      
  25.       let parseDate = d3.timeParse("%b-%y");
  26.      
  27.       function parsing(d) {
  28.         d.date = parseDate(d.date);
  29.         return d;
  30.       }
  31.      
  32.       data = data.map(parsing);
  33.      
  34.       let svg = d3.select("svg");
  35.       let margin = {top: 20, right: 20, bottom: 20, left: 40};
  36.       let width = +svg.attr("width") - margin.left - margin.right;
  37.       let height = +svg.attr("height") - margin.top - margin.bottom;
  38.      
  39.       let chart = svg
  40.       .append('g')
  41.         .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');
  42.      
  43.       let x = d3
  44.       .scaleTime()
  45.       .domain(d3.extent(data, d => d.date))
  46.       .range([0, width]);
  47.      
  48.       let y = d3
  49.       .scaleLinear()
  50.       .domain([0, d3.max(data, d => d.price)])
  51.       .range([height, 0]);
  52.      
  53.       let xAxis = d3.axisBottom(x);
  54.       let yAxis = d3.axisLeft(y);
  55.      
  56.       chart
  57.         .append('g')
  58.           .attr('transform', 'translate(0, ' + height + ')')
  59.           .call(xAxis);
  60.      
  61.       chart
  62.         .append('g')
  63.           .call(yAxis);
  64.      
  65.       let priceLine = d3.line()
  66.       .x(d => x(d.date))
  67.       .y(d => y(d.price));
  68.      
  69.       let costLine = d3.line()
  70.       .x(d => x(d.date))
  71.       .y(d => y(d.cost))
  72.       .curve(d3.curveMonotoneX);
  73.      
  74.       chart
  75.       .append('path')
  76.         .data([data])
  77.         .attr('fill', 'none')
  78.         .attr('stroke', 'darkred')
  79.         .attr('stroke-width', 2)
  80.         .attr('d', priceLine);
  81.      
  82.       chart
  83.       .append('path')
  84.         .datum(data)
  85.         .attr('fill', 'none')
  86.         .attr('stroke', 'steelblue')
  87.         .attr('stroke-width', 2)
  88.         .attr('d', costLine);
  89.      
  90.     }
  91.        
  92.   </script>
  93. </body>
  94. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement