No 2nd Y Axis with addTraces and relayout

I created a slightly altered version of

Where I tried to use addTraces and relayout to add the two traces individually. I’m not getting the 2nd y axis.

https://jsfiddle.net/abalter/473z6Lbx/

// start out with empty plot
Plotly.newPlot("myDiv",[],{title: "Multiple Y-Axis Plot"});

var trace1 =
{
  x: [1, 2, 3],
  y: [40, 50, 60],
  name: 'yaxis data',
  type: 'scatter'
};

var trace2 =
{
  x: [2, 3, 4],
  y: [4, 5, 6],
  name: 'yaxis2 data',
  yaxis: 'y2',
  type: 'scatter'
};

var yaxis1 =
{
	title: 'yaxis1',
  //position: 0,
  side: "left"
};

var layout1 =
{
	yaxis1: yaxis1,
};

var yaxis2 =
{
  title: 'yaxis2 title',
  titlefont: {color: 'rgb(148, 103, 189)'},
  tickfont: {color: 'rgb(148, 103, 189)'},
  overlaying: 'y1',
  side: 'right',
  //position: 1,
};

var layout2 =
{
	yaxs2: yaxis2
};

Plotly.addTraces("myDiv", [trace1]);
Plotly.relayout("myDiv", layout1);

Plotly.addTraces("myDiv", [trace2]);
Plotly.relayout("myDiv", layout2);

In your code, you have:

var layout2 =
{
	yaxs2: yaxis2
};

which should be

var layout2 =
{
	yaxis2: yaxis2
};

Here it is with that fix: https://jsfiddle.net/abalter/473z6Lbx/

Oh right.

To make sure that the autorange routine is called with all the data present on the graph, you should call Plotly.addTraces after Plotly.relayout.

1 Like

That did indeed fix it! Seems counter intuitive though. Seems like you want to add the data, and then format the display rather than the other way around.

https://jsfiddle.net/abalter/473z6Lbx/

I agreed, it’s not ideal. But, in order to properly compute the auto-range, one needs all the data present on the graph.

If you had set xaxis.range, yaxis.range and yaxis2.range, the addTraces and relayout order would not have mattered.

We are planning on adding a general Plotly.update method that would expose a way to update the data and layout at the same time in plotly.js v2.0.0 - which would solve the ordering issue you pointed out here. I recommend subscribing to wishlist for potential breaking changes since v1 · Issue #420 · plotly/plotly.js · GitHub for the latest development info.

Incidentally, that also fixed the issue in

See https://jsfiddle.net/abalter/28qfz523/