Updating candlestick data point using restyle in Plotly.js

£可爱£侵袭症+ 提交于 2019-12-24 21:06:24

问题


I am using a WebSocket connection to update a candlestick chart with live data.

Creating the initial candlestick chart is relatively easy:

var candleDiv = document.getElementById('candle-chart');
var data = {
    x: x, //Each of these is a single dimension array of the same length
    open: open,
    close: close,
    high: high,
    low: low,
    type: 'candlestick',
};
var layout = {
    datarevision: candleCount,
    dragmode: 'zoom',
    showlegend: false,
    xaxis: {
        type: 'date',
        range: [x[x.length - 26], x[x.length - 1]], //Only show the last 25 entries so it's not zoomed out too far.
        rangeslider: {
            visible: false
        },
        yaxis: {
            autorange: true,
        }
    }
}
data.xaxis = 'x';
data.yaxis = 'y';
data = [data];
Plotly.plot(candleDiv, data, layout);

However, the documentation for the restyle method doesn't talk much to the update of data. More about how the data is displayed. After much tinkering, I found a reasonable workaround of updating the data variable directly:

candleDiv.data[0].open[candleDiv.data[0].open.length - 1] = updatedOpenValue;
candleDiv.data[0].close[candleDiv.data[0].close.length - 1] = updatedCloseValue;
candleDiv.data[0].high[candleDiv.data[0].high.length - 1] = updatedHighValue;
candleDiv.data[0].low[candleDiv.data[0].low.length - 1] = updatedLowValue;
Plotly.restyle(candleDiv, 'data[0]', candleDiv.data[0], [0]);

This works, except that it appears to draw the new candle on the old candle. This becomes particularly distracting when the stick changes from a green (increasing) stick to a red (decreasing) stick.

Is there a correct syntax to achieve what I am attempting to do such that I don't get display issues?

I checked out this link from this post but I couldn't get the method used to work in the context of a candlestick chart.


回答1:


You may want to look at the Plotly.react method instead of Plotly.restyle: https://plot.ly/javascript/plotlyjs-function-reference/#plotlyreact



来源:https://stackoverflow.com/questions/49837984/updating-candlestick-data-point-using-restyle-in-plotly-js

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