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

查看:74
本文介绍了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,而不是<代码>行

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

  • 销毁旧图表(以移除事件侦听器并清除画布)
  • 制作配置对象的深层副本
  • 更改副本类型
  • 传递副本而不是原始对象.
  • 这是一个有效的 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天全站免登陆