2017-03-07 35 views
0

我創建這樣變化ChartJs軸標題動態

if (userLanguageCode === "es") { 
    customTooltipFormat = 'DD/MM/YYYY, HH:mm:ss'; 

    customDisplayFormats = { 
     'millisecond': 'SSS [ms]', 
     'second': 'HH:mm:ss', // 11:20:01 AM 
     'minute': 'D/MM/YY HH:mm', // 11:20:01 AM 
     'hour': 'D/MM/YY HH[h]', // Sept 4, 5PM 
     'day': 'D/MM/YYYY', // Sep 4 2015 
     'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ? 
     'month': 'MMM YYYY', // Sept 2015 
     'quarter': '[Q]Q - YYYY', // Q3 
     'year': 'YYYY', // 2015 
    }; 
} 

Chart.defaults.global.responsive = true; 
Chart.defaults.global.animation = false; 

datosChartHistoricos = { 
    labels: [], 
    datasets: [{ 
     label: textoValor, 
     backgroundColor: "rgba(0,181,255,0.5)", 
     fill: chartWithIncrementValues? true: false, 
     borderColor: "rgba(0,192,192,1)", 
     pointBorderColor: "rgba(0,181,255,1)", 
     pointBackgroundColor: "rgba(255,255,255,1)", 
     pointBorderWidth: 1, 
     data: [] 
    }] 
}; 

var ctx = document.getElementById("grafica").getContext("2d"); 
chartHistoricos = new Chart(ctx, { 
    type: chartWithIncrementValues? "bar" : "line", 
    data: datosChartHistoricos, 
    options: { 
     responsive: true, 
     elements: { 
      rectangle: { 
       borderWidth: 1, 
       borderColor: 'rgb(0, 0, 0)', 
       borderSkipped: 'bottom' 
      } 
     }, 
     scales: { 
      xAxes: [{ 
       type: "time", 
       time: { 
        tooltipFormat: customTooltipFormat, 
        displayFormats: customDisplayFormats, 
       } 
      }, ], 
      yAxes: [{ 
       scaleLabel: { 
        display: true, 
        labelString: textoValor + " (" + unidadesValor + ")" 
       } 
      }] 
     }, 
     legend: { 
      display: false, 
     } 
    } 
}); 

這是圖表,默認的配置中,數據被動態地添加一個圖表,但用戶可以選擇不同的數據值來顯示,如溫度,distance ...爲了做到這一點,我只是改變了數據集和標籤的數據值,但我不知道如何改變yAxis標籤,當我改變數據集的值。初始化標題是可以的。

任何提示?

謝謝!

+0

使用螢火蟲調試網頁。使用console.log(chartHistoricos)我可以看到所有可以訪問的對象,但軸對象內沒有「labelString」... –

回答

2

只需更新圖表對象的options屬性中的labelString值並調用.update()原型方法即可更改比例標題。

假設我有一個名爲myBar(該實例是從Chart.js構造函數返回的實例)的圖表實例,那麼我可以使用下面的示例來更改y軸標題。

myBar.options.scales.yAxes[0].scaleLabel.labelString = "My New Title"; 
myBar.update(); 

這是一個codepen,演示了一個工作示例。只需點擊「更改標題」按鈕,看看是否工作。

+0

非常感謝,它的工作原理! –