【问题标题】:Change ChartJs axis title dynamically动态更改 ChartJs 轴标题
【发布时间】:2017-03-07 09:39:01
【问题描述】:

我已经创建了一个这样的图表

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,
        }
    }
});

这是图表的默认配置,数据是动态添加的,但用户可以选择不同的数据值来显示,比如温度、距离……为此,我只需更改数据集的数据值和标签,但是当我更改数据集值时,我不知道如何使用 javascript 更改 yAxis 标签。初始化标题没问题。

有什么建议吗?

谢谢!

【问题讨论】:

  • 使用firebug调试网页。使用 console.log(chartHistoricos) 我可以看到我可以访问的所有对象,但是轴对象内没有“labelString”...

标签: javascript chart.js axis-labels


【解决方案1】:

您只需更新图表对象的options 属性中的labelString 值并调用.update() 原型方法即可更改刻度标题。

假设我有一个名为 myBar 的图表实例(该实例是 Chart.js 构造函数返回的内容),那么我可以使用以下示例更改 y 轴标题。

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

这是一个codepen,它演示了一个工作示例。只需单击“更改标题”按钮即可查看是否有效。

【讨论】:

  • 我知道这个问题已经很老了,但我完全错过了 [0] 部分。非常感谢!
【解决方案2】:

在 V3 中,音阶发生了变化,因此每个音阶都是其自己的对象,要让 jordanwillis 回答正常工作,您需要将其更改为:

myBar.options.scales.y.title.text = 'New title';
myBar.update();

但您也可以使用可编写脚本的选项,这些选项会在图表重绘时自动更新,因此您可以在选项对象本身内部执行此操作:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      },

      {
        label: '# of People',
        data: [3, 1, 9, 3, 7, 4],
        borderColor: 'lightBlue'
      }
    ]
  },
  options: {
    scales: {
      y: {
        title: {
          display: true,
          text: (ctx) => {
            const chart = ctx.scale.chart;
            const chartStatus = chart.data.datasets.map((e, i) => (!!chart.getDatasetMeta(i).hidden));

            if (chartStatus.every(e => e === false)) {
              return 'no datasets hidden'
            } else if (chartStatus.every(e => e === true)) {
              return 'all datasets hidden'
            } else {
              let ret = chartStatus.reduce((acc, curr, i) => {
                if (curr) {
                  acc += ` ${i},`
                }

                return acc;
              }, chartStatus.indexOf(true) === chartStatus.lastIndexOf(true) ? 'dataset:' : 'datasets:')

              ret = ret.substring(0, ret.length - 1)
              ret += ' hidden'
              return ret
            }
          }
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    相关资源
    最近更新 更多