Plotly addTraces/relayout 给出与 newPlot 不同的输出

Plotly addTraces/relayout giving different output than newPlot

我有一个简单的绘图,其中包含两条轨迹和两个 yaxis 规格。当我使用 newPlot 同时绘制它们时,我得到了想要的结果。当我一次绘制一个轨迹(和布局)时,我得到了不同的结果,这不是我想要的。

newPlot

addTraces/relayout

https://jsfiddle.net/abalter/eatszatj/

Javascript:

Plotly.newPlot("graph",[{}],{title: "Plot"});

trace1 = {y: [1,2,1]};
trace2 = {
    y: [0,0,0], 
  yaxis: "y2", 
  mode: "markers", 
  marker: {symbol: 6, size: 12}
};
yaxis1 = {domain: [0, 0.8], title: "one"};
yaxis2 = {
    domain: [0.85, 1.0],
  showgrid: false,
  showticklabels: false,
  title: "two",
  zeroline: false
};

Plotly.addTraces('graph', [trace1]);
Plotly.relayout('graph', {yaxis1});

Plotly.addTraces('graph', [trace2]);
Plotly.relayout('graph', {yaxis2});

//Plotly.newPlot('graph',[trace1, trace2],{yaxis1, yaxis2});

问题出在您的第一个 Plotly.newPlot 电话上。您正在传递一个空的跟踪对象,该对象默认为不可见的散点跟踪。

这意味着您的第一个 Plotly.addTraces 调用中的轨迹实际上是图形的第二个轨迹(默认情况下以橙色绘制),而第二个 Plotly.addTraces 调用中的轨迹实际上是图形的第三条轨迹(默认情况下以绿色绘制)。

因此,将第一行更改为

Plotly.newPlot("graph",[],{title: "Plot"});

你会得到想要的结果图。

解决方案原来是你需要在addTraces之前调用relayout。 Ettiene (etpinard) 为另一个问题找到了这个解决方案。

http://community.plot.ly/t/no-2nd-y-axis-with-addtraces-and-relayout/963

它也解决了这个问题。

Plotly.newPlot("graph",[],{title: "Plot"});

trace1 = {y: [1,2,1]};
trace2 = {
    y: [0,0,0], 
  yaxis: "y2", 
  mode: "markers", 
  marker: {symbol: 6, size: 12}
};
yaxis1 = {domain: [0, 0.8], title: "one"};
yaxis2 = {
    domain: [0.85, 1.0],
  showgrid: false,
  showticklabels: false,
  title: "two",
  zeroline: false
};

Plotly.relayout('graph', {yaxis1});
Plotly.addTraces('graph', [trace1]);

Plotly.relayout('graph', {yaxis2});
Plotly.addTraces('graph', [trace2]);

//Plotly.newPlot('graph',[trace1, trace2],{yaxis1, yaxis2});