Plotly addTraces/relayout giving different output than newPlot

…衆ロ難τιáo~ 提交于 2019-12-12 03:39:13

问题


I have a simple plot with two traces and two yaxis specs. When I plot them at the same time using newPlot I get the desired result. When I plot the traces (and layouts) one at a time, I get a different result, which is not what I want.

With newPlot

With 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});

回答1:


The problem is with your first Plotly.newPlot call. You're passing in a empty trace object which is defaulted to a invisible scatter trace.

This implies that the trace in your first Plotly.addTraces call is in fact the graph's second trace (drawn in orange by default) and the trace in your second Plotly.addTraces call is in fact the graph's third trace (drawn in green by default).

So, by changing your first line to

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

you'll get the desired resulting plot.




回答2:


The solution turned out to be that you need to call relayout before addTraces. Ettiene (etpinard) found me this solution for a different issue.

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

And it solved this one as well.

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});


来源:https://stackoverflow.com/questions/36974231/plotly-addtraces-relayout-giving-different-output-than-newplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!