如何动态添加 stockEvents 到 amCharts

How to dynamically add stockEvents to amCharts

我有一个函数可以用来向我的股票图表添加新的数据点。我需要创建一个条件,其中一个数据点带有一个图标。我看到 stockEvents 可以做到这一点,但它没有显示在我的图表中:

function addDataPoint(ask) {
        var dataProvider = chart.dataSets[0].dataProvider;
        var newDate = new Date(dataProvider[dataProvider.length - 1].date.getTime());
        newDate.setHours(newDate.getHours(), newDate.getMinutes() + 1, newDate.getSeconds());
        var a = Math.round(Math.random() * (40 + 1000)) + 100 + 1000;
        var b = Math.round(Math.random() * 100000000);
        dataProvider.push({
            date: newDate,
            value: ask,
            volume: ask
        });
        chart.dataSets[0].stockEvents = [{
            date: newDate,
            type: "flag",
            text: "F",
            description: "Some longer\ntext can also\n be added"
        }];
        dataProvider.shift();
    }

您需要设置股票事件的 graph property in order for it to be visible. This can be a reference to the stock graph object, or the graph's id. You also need to call validateData 才能更新图表(如果您尚未在 addDataPoint 函数之外这样做的话)。

AmCharts.makeChart("chartdiv", {
  // ...
  "panels": [{
    // ...
    "stockGraphs": [{
       // ...
       "id": "g1", //added id
       // ...
    },
    // ...
    ]
  },
  // ...
  ],
  // ...
});
// ...
function addDataPoint(ask) {
  // ...
  chart.dataSets[0].stockEvents = [{
    date: newDate,
    type: "flag",
    text: "F",
    graph: "g1", //added
    description: "Some longer\ntext can also\n be added"
  }];
  dataProvider.shift();
  chart.validateData(); //added
}

另请注意,您每次在 addDataPoint 函数中都会覆盖 stockEvents 数组。如果你想保留你以前的事件,那么你需要使用 push 因为它是一个数组。

Demo