Monday, 1 July 2019

Create an Ordinal Scale using Line Graph using D3 version 3 Javascript

For this, I can only use D3.js version 3. I have this data and I am trying to create two line graphs. The x scale should contain Month Number ( Jan-1) and while the y scale contains the range of the Years in decimal.

“Data”: [
    {
      "month": "1",
      "Month": "Jan",
      "Years": [
        “2”,
        "15”
      ]
    },
    {
      "month": "2",
      "Month": "Feb",
      "Years": [
        “1”,
        “3”
      ]
    },
    {
      "month": "3",
      "Month": "Mar",
      "Years": [
        “5”,
        “2”
      ]
    },
    {
      "month": "4",
      "Month": "Apr",
      "Years": [
        "11”,
        "19”
      ]
    },
    {
      "month": "5",
      "Month": "May",
      "Years": [
        "1",
        "16"
      ]
    },
    {
      "month": "6",
      "Month": "Jun",
      "Years": [
        “9”,
        "11”
      ]
    },
    {
      "month": "7",
      "Month": "Jul",
      "Years": [
        “78”,
        "11”
      ]
    },
    {
      "month": "8",
      "Month": "Aug",
      "Years": [
        "17",
        "26"
      ]
    },
    {
      "month": "9",
      "Month": "Sep",
      "Years": [
        "9",
        "12"
      ]
    },
    {
      "month": "10",
      "Month": "Oct",
      "Years": [
        "13",
        "16"
      ]
    },
    {
      "month": "11",
      "Month": "Nov",
      "Years": [
        "12",
        "10"
      ]
    },
    {
      "month": "12",
      "Month": "Dec",
      "Years": [
        "12",
        "9"
      ]
    }
  ]

How can I add 2016 and 2017 to the data? Such that I would look like this

   "Years": [
    2016: “3”,
    2017: "1”
  ]

Trying to display the data but it won't work using the code below

    data.forEach((d) => 
        d.month = d.Month;
        d.firstYear = d.Years[0];
        d.secondYear = d.Years[1];
    });


    var yScale = d3.scale.linear()
             .domain([0, d3.max(data, d => years)])
             .range([height, 0])

  var xScale = d3.scale.ordinal()
                 .domain(data.map(d => d.name))
                 .rangeRoundBands([0, width], 0.1)

Used forEach to group the years into 2016 and 2017 and also set the range for each of the scales. But this didn't work and the scale goes on a zigzag. I am new to d3 can you please show me how I can display the data above ?



from Create an Ordinal Scale using Line Graph using D3 version 3 Javascript

No comments:

Post a Comment