【问题标题】:How to add an offset to a dataset in Chart js如何在 Chart js 中向数据集添加偏移量
【发布时间】:2020-11-15 00:18:23
【问题描述】:

我能够为 X 标签添加偏移量,但我想为数据集中的所有点添加偏移量。有可能吗?

这是我正在使用的代码:

var myChart = new Chart.Line(ctx, {
    type: 'line',
    data: {
        labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
        datasets: [{
            data: [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
            pointLabelFontSize : 4,
            borderWidth: 2,
            fill: false,
            lineTension: .3,
            borderColor: "#f37029",
            borderCapStyle: 'round',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'bevel',
            pointBorderColor: "#f37029",
            pointBackgroundColor: "#f37029",
            pointBorderWidth: 1,
            pointHoverRadius: 4,
            pointHoverBackgroundColor: "rgba(220,220,220,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 4,
            pointHitRadius: 10,
            spanGaps: false,
        }]
    },
    options: {
        scales: {
            xAxes: [{
                gridLines: {
                    offsetGridLines: true,
                    display: false,
                    borderDash: [6, 2],
                    tickMarkLength:5
                },
                ticks: {
                     fontSize: 8,
                     labelOffset: 10,
                     maxRotation: 0
                }}],
            yAxes: [{
                gridLines: {
                    display:false
                },
                ticks: {
                    beginAtZero: true,
                    max: 200,
                    min: 0,
                    stepSize: 20,
                    fontSize: 8
                }
            }]
        },
        legend: {
            display: false
        },
        responsive: false,
        maintainAspectRatio: true
    }
});

我想将该偏移量应用于所有点,在图像中我刚刚向 JAN/DEC 添加了一个箭头,但我想将其应用于所有点。

我尝试添加一个空数据,问题是我不想显示第一个虚线网格。

有什么想法吗?提前致谢。

【问题讨论】:

    标签: charts chart.js


    【解决方案1】:

    退房 - http://www.chartjs.org/docs/latest/axes/cartesian/

    在“通用配置”一章中,有一个布尔属性offset。默认值为falsebar 图表除外)

    如果为 true,则会在两条边上添加额外的空间,并缩放轴以适应图表区域。默认情况下,在条形图中设置为 true。

    所以你可以将它设置为 true,它应该可以工作。

    【讨论】:

    • 我添加了 xAxes: [{offset: true}] 并且它有效......它增加了额外的空间。但是当添加到 yAxes 时它不起作用......如何解决这个问题?
    【解决方案2】:

    您可以使用 Chart.js 插件来实现这一点。它们让您可以处理在图表创建期间触发的特定事件(beforeInitafterUpdateafterDraw ...)并且也很容易实现:

    Chart.pluginService.register({
        afterUpdate: function(chart) {
            // This will be triggered after every update of the chart
        }
    });
    

    现在您只需遍历您的数据集数据模型(用于绘制图表的属性)并添加您想要的偏移量:

    Chart.pluginService.register({
        afterUpdate: function(chart) {
            // We get the dataset and set the offset here
            var dataset = chart.config.data.datasets[0];
            var offset = 20;
    
            // For every data in the dataset ...
            for (var i = 0; i < dataset._meta[0].data.length; i++) {
                // We get the model linked to this data
                var model = dataset._meta[0].data[i]._model;
    
                // And add the offset to the `x` property
                model.x += offset;
    
                // .. and also to these two properties
                // to make the bezier curve fits the new graph
                model.controlPointNextX += offset;
                model.controlPointPreviousX += offset;
            }
        }
    });
    

    您可以看到您的示例正在运行 on this jsFiddle,这是它的结果:

    【讨论】:

    • 非常感谢!直到今天我才知道插件。再次感谢您为我指明了正确的方向!干杯
    【解决方案3】:

    从“tektiv”给出的答案开始,我需要一个类似的解决方案,但它适用于响应式图表。

    因此,我们首先计算数据集数组中的对象数量,而不是使用 tektiv 插件中显示的给定偏移量的固定测量值。然后,我们将 chart.width 除以数组中的对象数,得到相等的段,然后为了定义每条网格线之间的中点,我们将该总和除以 2。

    注意 1:您也可以将因子 2 替换为变量,以便用户可以选择所需的偏移部分。

    注意 2:我已将插件代码放在图表脚本中,因为我不希望通过注册全局插件将其作为全局影响。

    注 3:这是对我的解决方案的第二次重新编辑,因为我从上面的“tektiv”给出的答案中部分复制的插件代码只是第一次成功触发,但是在重新加载新实例时图表我在 dataset._meta 上遇到了一些空错误(也值得在这里查看有关此特定主题的答案,因为这有助于我修复并最终确定我的答案:Dataset._meta[0].dataset is null in ChartJS 代码示例:

    <script>
    
        var myChart;
    
        function drawChart() {
    
            var ctx = document.getElementById('myChart').getContext('2d');
            ctx.innerHTML = '';
    
            if (myChart != null) {
                myChart.destroy();
            }
    
            var datasetArray = [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null];
    
            myChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
                    datasets: [{
                        data: datasetArray,
                        borderWidth: 2,
                        borderColor: "#f37029",
                        pointBorderColor: "#f37029",
                        pointBackgroundColor: "#f37029",
                        pointHitRadius: 10,
                        spanGaps: false,
                    }]
                },
                plugins: [{
                    afterUpdate: function (chart, options) {
                        //..
                        var dataset = chart.config.data.datasets[0];
    
                        // Get the number of objects in the dataset array.
                        var noDataPoints = datasetArray.length;
    
                        //alert(noDataPoints); // testing only, you'll notice that this 
                        // alert would fire each time the responsive chart is resized.
                        var xOffset = (chart.width / noDataPoints) / 2;
    
                        for (var i = 0; i < dataset.data.length; i++) {
                            for (var key in dataset._meta) {
                                var model = dataset._meta[key].data[i]._model;
                                model.x += xOffset;
                                model.controlPointNextX += xOffset;
                                model.controlPointPreviousX += xOffset;
                            }
                        }
                    }
                }],
                options: {
                    scales: {
                        xAxes: [{
                            gridLines: {
                                offsetGridLines: false,
                                display: true,
                            },
                            ticks: {
                                fontSize: 8,
                                maxRotation: 0
                            }
                        }],
                        yAxes: [{
                            gridLines: {
                                display: true
                            },
                            ticks: {
                                beginAtZero: true,
                            }
                        }]
                    },
                    legend: {
                        display: false
                    },
                    responsive: true,
                    maintainAspectRatio: true
                }
            });
        }
    
    </script>
    

    下面的第一个屏幕截图显示了拉伸到宽屏视图的响应式图表:

    第二个屏幕截图显示了响应式图表的大小调整为更小、更传统的窗口大小:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      相关资源
      最近更新 更多