1

This question is a bit tricky. I have some example code working with the following data. It plots it on a line graph.

var dataset = [{
      y: 0.1
    },
    {
      y: 0.6
    },
        {
      y: 0.6
    },
    {
      y: 0.7
    }
  ];

D3 uses the following code to put this on the X axis:

var xScale = d3.scaleLinear()
.domain([0, n - 1]) // input
.range([0, width]); // output

However I'm really looking to get dat

var dataset = [{
      "1pm": 0.1
    },
    {
      "2pm": 0.6
    },
        {
      "3pm": 0.6
    },
    {
      "4pm": 0.7
    }
  ];

How do I put these values into the graph X axis instead of it just being based on the array numbers? When I try the code as it is above it breaks the graph it says:

Error: <path> attribute d: Expected number, "M0,NaNC17.222222222…".

This is the full code:

http://jsfiddle.net/spadez/e6hv9x8m/17/

2
  • 1
    So in your example, you're looking to have the key of the property in your dataset objects be the x value, and the value of the property in your dataset objects be the y value? Or are you just looking for a way to format the ticks? Commented Oct 6, 2018 at 11:08
  • @DannyBuonocore In my old example, it uses the key of the property as the X value, correct. However, I want to plot values against time, so I want my X axit to be time values. Therefore I replaced the "y" in the data with the value I want for the X axis, but I can't display this text on the x axis Commented Oct 6, 2018 at 11:18

1 Answer 1

2

Here is your modified fiddle.

First off, you can include an additional value in your dataset objects to represent the x value, I've called this date:

var dataset = [{
    y: 0.1,
    date: new Date(2012,0,1)
  },
  {
    y: 0.6,
    date: new Date(2012,0,2)
  }
];

Next, the x scale needs to be changed from linear to time:

var minDate = new Date(2012,0,1);
var maxDate = new Date(2012,0,2);

var xScale = d3.scaleTime()
  .domain([minDate, maxDate])
  .range([0, width]);

And finally, you must update the callback here to pull the date field from the dataset object, rather than just it's position in the array:

var line = d3.line()
  .x(function(d, i) {
    return xScale(d.date);
  }) // set the x values for the line generator
  .y(function(d) {
    return yScale(d.y);
  }) // set the y values for the line generator 
  .curve(d3.curveMonotoneX) // apply smoothing to the line
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.