14 Replies Latest reply: Apr 6, 2016 4:05 PM by Markus Anttila RSS

    Trying to get date from datepicker on xaxis using d3.js

    Jasmin Larochr

      Hi, I am having two datepickers on my web page and when user select from: and to: dates from both datepickers respectively it should come on x axis and so far  i have done this(attached  file). please help.

        • Re: Trying to get date from datepicker on xaxis using d3.js
          Jasmin Larochr

          This is my code..forgot to upload before

           

           

           

          <!doctype html>

          <html>

           

              <head>

                  <meta charset="UTF-8">

                  <meta content="utf-8" http-equiv="encoding">

           

                  <title>D3</title>

                  <link rel="stylesheet" type="text/css" href="mystyle1.css" />

                  <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>

               </head>

              <script src="http://d3js.org/d3.v3.min.js"></script>

              <body>

                  <div id="chart"></div>

                  <script>

                  //for datepicker

                  function processData(f1, f2){

                  var v1= document.getElementById(f1).value.toString();

                  var v2= document.getElementById(f2).value.toString();

                  alert (v1+"\n"+v2);

                  return v1, v2;

                  valPicker1=v1;   //passed values that were attained above in valpickr1 and pickr2

                   valPicker2=v2;

                  }

                      var myData = [100, 125, 320, 440];

                      var height = 300;

                      var width = 500;

           

                      var tooltip = d3.select('body').append('div')

                          .style('position', 'absolute')

                          .style('background', '#f4f4f4')

                          .style('padding', '5 15px')

                          .style('border', '1px #333 solid')

                          .style('border-radius', '5px')

                          .style('opacity', 'o')

           

           

                      var yScale = d3.scale.linear()

                          .domain([0, d3.max(myData)])

                          .range([0, height]);

                      var xScale = d3.scale.ordinal()

                          .domain(d3.range(0, myData.length))

                          .rangeBands([0, width])

                      var colors = d3.scale.linear()

                          .domain([0, myData.length])

                          .range(['#90ee90', '#30c230'])

                      d3.select('#chart').append('svg')

                          .attr('width', width)

                          .attr('height', height)

                          .style('background', '#f4f4f4')

                          .selectAll('rect')

                          .data(myData)

                          .enter().append('rect')

                          .style('fill', function (d, i) {

                              return colors(i);

                          })

                          .attr('width', xScale.rangeBand())

                          .attr('height', function (d) {

                              return yScale(d);

                          })

                          .attr('x', function (d, i) {

                              return xScale(i);

                          })

                          .attr('y', function (d) {

                              return height - yScale(d);

                          })

                          .on('mouseover', function (d) {

                              tooltip.transition()

                                  .style('opacity', 1)

           

                              tooltip.html(d)

                                  .style('left', (d3.event.pageX) + 'px')

                                  .style('top', (d3.event.pagey) + 'px')

                              d3.select(this).style('opacity', 0.5)

                          })

                          .on('mouseout', function (d) {

                              tooltip.transition()

                                  .style('opacity', 0)

                              d3.select(this).style('opacity', 1)

                          })

           

                      var vScale = d3.scale.linear()

                          .domain([0, d3.max(myData)])

                          .range([height, 0]);

                      var hScale = d3.scale.ordinal()

                          .domain(d3.range(0, myData.length))

                          .rangeBands([0, width])

           

                      //vaxis

                      var vAxis = d3.svg.axis()

                          .scale(vScale)

                          .orient('left')

                          //v guide

                      var vGuide = d3.select('svg')

                          .append('g')

                      vAxis(vGuide)

                      vGuide.attr('transform', 'translate(35,10)')

                      vGuide.selectAll('path')

                          .style('fill', 'none')

                          .style('stroke', '#000')

                      vGuide.selectAll('line')

                          .style('stroke', '#000')

           

                      //Haxis

                      var hAxis = d3.svg.axis()

                          .scale(hScale)

                          .orient('bottom')

                          //H guide

                      var hGuide = d3.select('svg')

                          .append('g')

                      hAxis(hGuide)

                      hGuide.attr('transform', 'translate(35,' + (height - 25) + ')')

                      hGuide.selectAll('path')

                          .style('fill', 'none')

                          .style('stroke', '#000')

                      hGuide.selectAll('line')

                          .style('stroke', '#000')

                  </script>

                 

                  <div align ="center">

              From : <input type="date" name="field1" id="field1" />

              To :   <input type="date" name="field2" id="field2" /><br /><br />

              <input type="button" onclick="processData('field1','field2')" value="Submit" />

             

              </div>

              </body>

              <html>

            • Re: Trying to get date from datepicker on xaxis using d3.js
              Markus Anttila

              Hi,

              Just to name a few points:

              - Why are you calling d3.js two times?

              - You've hard coded your data to four elements? Should that also be dynamic? Lets say you choose 12 day period, the values should also be for the 12 days.
              - On you process() you have to redraw the chart data and axis and rescale.

               

              Here are a couple of code snippets to get you started::::

               

               

              var v1= document.getElementById(f1).value.toString();

                          var v2= document.getElementById(f2).value.toString();

                          var diff= daydiff(parseDate(v1), parseDate(v2))

               

               

                          var date1 = new Date(parseDate(document.getElementById(f1).value));

                          var date2 = new Date(parseDate(document.getElementById(f2).value));

                          var day;

                          var DateRange = [];

                          console.log(date1.getDate())

                         

                          //Generate the dates array for x-axis

                          for(var i=0; i < diff; ++i){

                              day = date1.getDate()

                              newDate = new Date(date1.setDate(++day));

                              console.log(newDate)

                              DateRange.push(newDate)

                              console.log(DateRange)

                          }

               

               

                          //parse the input values

                          function parseDate(str) {

                              var mdy = str.split('-')

                              return new Date(mdy[0], mdy[1] -1, mdy[2]);

                              }

               

               

                          //Get the date difference count

                          function daydiff(first, second) {

                              return Math.round((second-first)/(1000*60*60*24));

                              }

                         

                          console.log(daydiff(parseDate(v1), parseDate(v2)))

                         

               

               

                          //Random data generator to mock the data for all days chosen

                          var myData = function(){

                                  var arr = [];

                                  for(var i = 0; i <= DateRange.length; ++i ){

                                      arr.push(Math.floor((Math.random() * 10) * 10));

                                  }

                                  return arr

                              };

                • Re: Trying to get date from datepicker on xaxis using d3.js
                  Jasmin Larochr

                  Hi, Now i managed to change dates dynamically but that is for 4 hardcoded values so please now tell me where should I refer to my json url and my json file has epoch date values so i have tries to get information to how to convert from epoch to readable format but don't know how should i use in my code..please suggest I will be very thankful to you.

                  <!doctype html>

                  <html>

                      <head>

                          <meta charset="UTF-8">

                          <meta content="utf-8" http-equiv="encoding">

                   

                          <title>D3</title>

                          <!-- <link rel="stylesheet" type="text/css" href="mystyle1.css" /> -->

                   

                          <style>

                   

                              body {

                                  color: #000;

                              }

                   

                              .axis {

                                font: 10px sans-serif;

                              }

                   

                              .axis path,

                              .axis line {

                                fill: none;

                                stroke: #000;

                                shape-rendering: crispEdges;

                              }

                   

                              .bar {

                                  fill: steelblue;

                              }

                   

                              .bar:hover {

                                  fill: brown;

                              }

                   

                          </style>

                   

                          <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>

                       </head>

                      <script src="http://d3js.org/d3.v3.min.js"></script>

                      <body>

                          <div id="chart"></div>

                          <div align ="center">

                              From : <input type="date" name="field1" id="field1" />

                              To :   <input type="date" name="field2" id="field2" /><br /><br />

                              <input type="button" onclick="render(true)" value="Submit" />

                          </div>

                   

                          <script>

                   

                               // converting date to readable format

                              var myDate = new Date( your epoch date );

                             document.write(myDate.toGMTString()+"<br>"+myDate.toLocaleString());

                            

                              /* var myData = [

                                  { value: 100, date: '2016-01-01'},

                                  { value: 125, date: '2016-02-02'},

                                  { value: 320, date: '2016-03-03'},

                                    { value: 440, date: '2016-04-04'}

                                ];

                       */

                                var    parseDate = d3.time.format("%Y-%m-%d").parse;

                   

                                var margin  = { top: 20, right: 0, bottom: 80, left: 40 };

                                var width     = 500 - margin.left - margin.right;

                              var height     = 300 - margin.top - margin.bottom;

                   

                              var xScale     = d3.scale.ordinal().rangeRoundBands([0, width], .1);

                              var yScale     = d3.scale.linear().range([height, 0]);

                              var hAxis     = d3.svg.axis().scale(xScale).orient('bottom').tickFormat(d3.time.format("%Y-%m-%d"));

                              var vAxis     = d3.svg.axis().scale(yScale).orient('left');

                              var tooltip = d3.select('body').append('div')

                                              .style('position', 'absolute')

                                              .style('background', '#f4f4f4')

                                              .style('padding', '5 15px')

                                              .style('border', '1px #333 solid')

                                              .style('border-radius', '5px')

                                              .style('opacity', 'o');

                   

                              myData.forEach(function(d) {

                                  d.date     = parseDate(d.date);

                                  d.value = +d.value;

                              });

                   

                              function getDates() {

                                  return [document.getElementById('field1').value, document.getElementById('field2').value];

                              }

                   

                              function render(filterByDates) {

                   

                                  d3.select('svg').remove();

                   

                                  if(filterByDates) {

                                      var date1 = parseDate(document.getElementById('field1').value);

                                      var date2 = parseDate(document.getElementById('field2').value);

                   

                                      myData = myData.filter(function(d) {

                                          return d.date >= date1 && d.date <= date2;

                                      });

                                  }

                   

                                  xScale.domain(myData.map(function(d) {

                                      return d.date;

                                  }));

                                 

                                  yScale.domain([0, d3.max(myData, function (d) { return d.value; })]);

                   

                                  var svg = d3.select('#chart').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 + ")");

                                 

                                  svg

                                      .append('g')

                                      .attr("class", "x axis")

                                      .attr("transform", "translate(0," + height + ")")

                                      .call(hAxis)

                                      .selectAll("text")

                                      .style("text-anchor", "end")

                                      .attr("dx", "-.8em")

                                      .attr("dy", "-.55em")

                                      .attr("transform", "rotate(-90)" );

                   

                                  svg

                                      .append('g')

                                      .attr("class", "y axis")

                                      // .attr('transform', 'translate(35,' + (height - 25) + ')')

                                      .call(vAxis)

                   

                                  svg

                                      .selectAll(".bar")

                                      .data(myData)

                                      .enter().append("rect")

                                      .attr("class", "bar")

                                      .style("fill", "steelblue")

                                      .attr("x", function(d) {

                                          return xScale(d.date);

                                      })

                                      .attr("width", xScale.rangeBand())

                                      .attr("y", function(d) {

                                          return yScale(d.value);

                                      })

                                      .attr("height", function(d) {

                                          return height - yScale(d.value);

                                      })

                                      .on('mouseover', function (d) {

                                          tooltip.transition()

                                              .style('opacity', 1)

                   

                                          tooltip.html(d.value)

                                              .style('left', (d3.event.pageX) + 'px')

                                              .style('top', (d3.event.pagey) + 'px')

                                          d3.select(this).style('opacity', 0.5)

                                      })

                                      .on('mouseout', function (d) {

                                          tooltip.transition()

                                              .style('opacity', 0)

                                          d3.select(this).style('opacity', 1)

                                      });

                              }

                   

                              render(false);

                   

                          </script>

                         

                      </body>

                  <html>