Yuvaraj V
Yuvaraj V

Reputation: 1212

how to plot two points on y axis for single x axis value (Maybe date) using plotly js

I have data set like the one shown below. For each date, I have one or more points to plot on the y-axis.

x axis (y axis) - 2021-07-01 (20, 30)
x axis (y axis) - 2021-07-02 (20)
x axis (y axis) - 2021-07-04 (10, 50)
x axis (y axis) - 2021-07-06 (40)

How to plot this data using Plotly js

Upvotes: 0

Views: 757

Answers (2)

Derek O
Derek O

Reputation: 19545

If you have one or more y-values for each x-value (say in the form of a 2D array), you can loop through this array to flatten it, and repeat the necessary x-values from the original x-value array. The codepen for this is here.

var x = ["2021-07-01","2021-07-02","2021-07-04","2021-07-06"]
var y = [[20, 30],[20],[10,50],[40]]
var x_plot = []
var y_plot = []

for (let i=0; i<y.length; i++) {
  for (let j=0; j<y[i].length; j++) {
    x_plot.push(x[i])
    y_plot.push(y[i][j])
  }
}
  
var trace1 = {
  x: x_plot,
  y: y_plot,
  type: 'scatter',
  mode: 'markers'
}

var data = [trace1];
Plotly.newPlot('myDiv', data);

enter image description here

Upvotes: 1

Yuvaraj V
Yuvaraj V

Reputation: 1212

I got answer from code pen. I think this may be useful for others as well. If we have two y values for each x value we can duplicate x values to match y values like the one show below.

var data = [
  {
    x: ['2013-10-04', '2013-10-04', '2014-11-04'],
    y: [1, 3, 6],
    type: 'scatter'
  }
];

Plotly.newPlot('myDiv', data);

Upvotes: 0

Related Questions