在 amcharts 4 中动态更改图表的标题

Dynamically change title of a chart in amcharts 4

如何使用 javascript 更改已加载图表的标题?以下不适用于外部数据

https://codepen.io/abdfahim/pen/zYOPvPx

var chart = am4core.createFromConfig({
    "titles": [
        {
            "text": "ABCD",
            "fontSize": 25,
            "marginBottom": 10
        }
    ],
    "dataSource": {
        "url": "https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/sample_data_serial.json"
    },
    "xAxes": [
        {
            "type": "CategoryAxis",
            "dataFields": {
                "category": "year"
            }
        }
    ],
    "yAxes": [
        {
            "type": "ValueAxis"
        }
    ],
    "series": [
        {
            "type": "ColumnSeries",
            "name": "Cars",
            "dataFields": {
                "categoryX": "year",
                "valueY": "cars"
            }
        }
    ]
}, "chartdiv", am4charts.XYChart);

function changeTitle()
{
  chart.titles[0].text = "New Title";
}

A​​mCharts v4 使用 lists 来表示其大部分类似数组的对象,因此使用下标将不起作用。推荐使用list提供的accessor方法获取你要改变的对象,比如getIndex:

chart.titles.getIndex(0).title = "New title"

Updated codepen

以防万一有人遇到我同样的问题,我发现这个解决方案对我有用

chart.titles.getIndex(0).text = "new title";

如果您要每 x 秒刷新一次图表,这将特别方便