MostlyRquestions
MostlyRquestions

Reputation: 566

time series with plotly.js fails, w/ fiddle

I'm new working with plotly.js and cannot figure time series plots. If I plot 4 or 5 dates with simple data points the plot works as expected. However, whenever I use more dates, even say 35 dates, it seems plotly can't handle it? That seems ridiculous so I'm sure doing something wrong but look at this fiddle and then this fiddle.

var x = [ "2016-10-10 12:00:03", "2016-10-11 12:00:03", "2016-10-12 12:00:03"];
var y = [-6, -7, -7];

console.log("x: ", x)
console.log("y: ", y)

var trace1 = {
  x: x,
  y: y,
  type: 'scatter'
};


var data = [ trace1 ];

var layout = {
  title:'Line and Scatter Plot'
};

Plotly.newPlot('plotly', data, layout);

Upvotes: 2

Views: 1732

Answers (2)

abalter
abalter

Reputation: 10383

So, there are two things going on here:

  1. I have learned the hard way that it's best to use datetimes with plotly. I think it stems from the underlying d3, but not sure.

  2. Your dates are out of order. You can't just sort the dates, or they will be jumbled relative to your y values. I created an array of objects with date and value fields, and then sorted on .date.

https://jsfiddle.net/qL5431r5/7/

Upvotes: 0

Maximilian Peters
Maximilian Peters

Reputation: 31679

Plotly works great with lots of dates, see the attached snippet.

In your fiddle you have a date 2016-10-10 12:30:03 which is followed by a date 2016-10-10 1:00:03 which precedes the first one. This might cause the weird output.

If you work with dates, use Date objects, they will save you a lot of headache when converting different time formats.

var startTime = new Date();
var dataPoints = 100;
var i = 0;
var y1 = 0;
var x = [];
var y = [];

for (i = 0; i < dataPoints; i += 1) {
    startTime.setTime(startTime.getTime() + (24 * 60 * 60 * 1000));
    x.push(startTime.toDateString());
}

for (i = 0; i < x.length; i += 1) {
    y1 += Math.random();
    y.push(y1)

}

var data = [{
  x: x,
  y: y,
  type: 'scatter',
}];

var layout = {
  title:'Lots of dates'
};

Plotly.newPlot('plotly', data, layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div class="graph js-plotly-plot" style="height: 70vh; width:100%" id="plotly">
</div>

Upvotes: 1

Related Questions