abdfahim
abdfahim

Reputation: 2553

Dynamically change title of a chart in amcharts 4

How can I change the title of a loaded chart using javascript? The following doesn't work with external data

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

Upvotes: 1

Views: 1537

Answers (2)

d3javu999
d3javu999

Reputation: 323

Just in case some one will hit my same issue, I found this solution working for me

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

this is particularly handy if you are going to refresh the chart each x seconds

Upvotes: 0

xorspark
xorspark

Reputation: 16012

AmCharts v4 uses lists for the majority of its array-like objects, so using subscripts will not work. It's recommended to use the accessor methods provided by the list to get at the object you want to change, such as getIndex:

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

Updated codepen

Upvotes: 1

Related Questions