Chart.js:图表类型的动态更改(以线到条为例) [英] Chart.js: Dynamic Changing of Chart Type (Line to Bar as Example)

查看:145
本文介绍了Chart.js:图表类型的动态更改(以线到条为例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据选择框的更改来热交换图表类型。如果需要更新数据,它就会更改。

I am trying to hot swap chart types based on select box changes. If data needs to be updated, it changes.

因此,例如,在页面加载时,我会创建一个如下所示的图表:

So for example, on page load I create a chart like this:

var config = {
     type: 'line',
     data: {
        labels: this.labels,
        datasets: [{
            label: 'Some Label',
            data: this.values
        }]
     },
     options: {
         responsive: true
     }
}
var context = document.getElementById('canvas').getContext('2d');
window.mychart = new Chart(context, config);

但是随后我将组合框更改为条形图。我已经使用条形图在页面加载中测试了数据,并且效果很好。

But then I change the combo box to a bar chart. I have tested the data with bar chart on page load, and it worked great.

这是我尝试更改图表的方式。

Here's how I am trying to change the chart.

window.mychart.destroy();

// chartType = 'bar'
config.type = chartType;

var context = document.getElementById('canvas').getContext('2d');
window.mychart = new Chart(context, config);

window.mychart.update();
window.mychart.render();

但是什么也没发生。折线图仍然存在。如何动态更改图表类型? (即使这意味着销毁并重新创建图表画布也是如此)。

But nothing happens. The line chart remains. How can I dynamically change the chart type? (Even if it means destroying & re-creating the chart canvas).

更新

请注意,看起来它实际上是在破坏图表,但即使我执行 console.log(config.type); 并保持重画折线图,返回 bar ,而不是 line

Note it looks like it is actually destroying the chart, but keeps redrawing a line chart, even though I do console.log(config.type); and it returns bar, not line

推荐答案

修复程序



  • 销毁旧图表(删除事件侦听器并清除画布)

  • 制作配置对象的深层副本

  • 更改副本的类型

  • 传递副本而不是原始对象。

  • The Fix

    • Destroy the old chart (to remove event listeners and clear the canvas)
    • Make a deep copy of the config object
    • Change the type of the copy
    • Pass the copy instead of the original object.
    • 这是一个可行的jsfiddle示例

      示例概述:

      var temp = jQuery.extend(true, {}, config);
      temp.type = 'bar'; // The new chart type
      myChart = new Chart(ctx, temp);
      

      注意:使用Chart.js 2.0.1版本

      NOTE: Using version 2.0.1 of Chart.js

      Chart.js修改您传入的配置对象。因此,您不能只更改'config.type'。您可以进入修改后的对象,然后将所有内容更改为所需的类型,但是保存原始的配置对象要容易得多。

      Chart.js modifies the config object you pass in. Because of that you can not just change 'config.type'. You could go into the modified object and change everything to the type you want, but it is much easier to just save the original config object.

      这篇关于Chart.js:图表类型的动态更改(以线到条为例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆