如何创建带有锁定 y 轴的水平滚动 Chart.js 折线图?

IT技术 javascript ionic-framework chart.js
2021-02-22 10:33:59

我想创建一个折线图,Chart.JsY-Axis滚动时不能移动。

我假设我可以使用固定宽度,并将其放入容器 div 中overflow:auto,然后将Y-axis信息附加到画布并滚动。

我在文档中没有看到此参数或选项。有任何想法吗?

谢谢

6个回答

可滚动图表

你几乎走在正确的轨道上。如果您添加另一个包装器和 y 轴,您就完成了。


预览

在此处输入图片说明


CSS

.chartWrapper {
    position: relative;
}

.chartWrapper > canvas {
    position: absolute;
    left: 0;
    top: 0;
    pointer-events:none;
}

.chartAreaWrapper {
    width: 600px;
    overflow-x: scroll;
}

HTML

<div class="chartWrapper">
    <div class="chartAreaWrapper">
        <canvas id="myChart" height="300" width="1200"></canvas>
    </div>
    <canvas id="myChartAxis" height="300" width="0"></canvas>
</div>

脚本

...

new Chart(ctx).Line(data, {
    onAnimationComplete: function () {
        var sourceCanvas = this.chart.ctx.canvas;
        // the -5 is so that we don't copy the edges of the line
        var copyWidth = this.scale.xScalePaddingLeft - 5;
        // the +5 is so that the bottommost y axis label is not clipped off
        // we could factor this in using measureText if we wanted to be generic
        var copyHeight = this.scale.endPoint + 5;
        var targetCtx = document.getElementById("myChartAxis").getContext("2d");
        targetCtx.canvas.width = copyWidth;
        targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth, copyHeight, 0, 0, copyWidth, copyHeight);
    }
});

小提琴 - http://jsfiddle.net/mbhavfwm/

我怎样才能在 AngularJS 1 上做到这一点?
2021-04-17 10:33:59
这工作得很好,感谢@Ben 提供 2.x 版本!我刚刚在另一个问题中引用了这一点,因为我看到 Retina 显示器扭曲了固定轴标签的大小。
2021-04-30 10:33:59
这也可以应用于垂直滚动吗?我有一个水平条形图,我希望它可以滚动。
2021-05-05 10:33:59
@KameshJungi 检查此jsfiddle.net/jmpxgufu以获取 2.x 的示例实现
2021-05-08 10:33:59
此示例适用于 1.x 版本..chart.js 2.x 是否有任何解决方案?
2021-05-09 10:33:59

Chart.js 2.7.2:https ://jsfiddle.net/EmmaLouise/eb1aqpx8/3/

这种方法处理不同的 DPR 设置,并将缩放轴以匹配 Chart.js 应用于其图表的缩放比例。它还在 Chart.js 绘制的原始 Y 轴上调用 .clearRect() ,清除定义区域中的像素,这意味着没有重复的轴或重叠。

CSS:

.chartWrapper {
 position: relative;
}

.chartWrapper > canvas {
  position: absolute;
  left: 0;
  top: 0;
  pointer-events: none;
}

.chartAreaWrapper {
  width: 600px;
  overflow-x: scroll;
}

HTML

<div class="chartWrapper">
    <div class="chartAreaWrapper">
        <div class="chartAreaWrapper2">
          <canvas id="chart-Test" height="300" width="1200"></canvas>
        </div>
     </div>
     <canvas id="axis-Test" height="300" width="0"></canvas>
</div>

JS:

    $(function () {
    var rectangleSet = false;

    var canvasTest = $('#chart-Test');
    var chartTest = new Chart(canvasTest, {
        type: 'bar',
        data: chartData,
        maintainAspectRatio: false,
        responsive: true,
        options: {
            tooltips: {
                titleFontSize: 0,
                titleMarginBottom: 0,
                bodyFontSize: 12
            },
            legend: {
                display: false
            },
            scales: {
                xAxes: [{
                    ticks: {
                        fontSize: 12,
                        display: false
                    }
                }],
                yAxes: [{
                    ticks: {
                        fontSize: 12,
                        beginAtZero: true
                    }
                }]
            },
            animation: {
                onComplete: function () {
                    if (!rectangleSet) {
                        var scale = window.devicePixelRatio;                       

                        var sourceCanvas = chartTest.chart.canvas;
                        var copyWidth = chartTest.scales['y-axis-0'].width - 10;
                        var copyHeight = chartTest.scales['y-axis-0'].height + chartTest.scales['y-axis-0'].top + 10;

                        var targetCtx = document.getElementById("axis-Test").getContext("2d");

                        targetCtx.scale(scale, scale);
                        targetCtx.canvas.width = copyWidth * scale;
                        targetCtx.canvas.height = copyHeight * scale;

                        targetCtx.canvas.style.width = `${copyWidth}px`;
                        targetCtx.canvas.style.height = `${copyHeight}px`;
                        targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth * scale, copyHeight * scale, 0, 0, copyWidth * scale, copyHeight * scale);

                        var sourceCtx = sourceCanvas.getContext('2d');

                        // Normalize coordinate system to use css pixels.

                        sourceCtx.clearRect(0, 0, copyWidth * scale, copyHeight * scale);
                        rectangleSet = true;
                    }
                },
                onProgress: function () {
                    if (rectangleSet === true) {
                        var copyWidth = chartTest.scales['y-axis-0'].width;
                        var copyHeight = chartTest.scales['y-axis-0'].height + chartTest.scales['y-axis-0'].top + 10;

                        var sourceCtx = chartTest.chart.canvas.getContext('2d');
                        sourceCtx.clearRect(0, 0, copyWidth, copyHeight);
                    }
                }
            }
        }
    });
非常感谢这么酷的例子!如果在 x 轴上添加更多数据,y 比例不会改变,会怎样?如果我addData(5, chartTest);在图表中添加更多数据,Y 轴会变大
2021-04-21 10:33:59

使用最新版本(2.4.0)这对我有用:

HTML

<div style="width: 100%; overflow-x: auto; overflow-y: hidden">
  <div style="width: 3000px; height: 300px">
    <canvas id="chart1" height="300" width="0"></canvas>
  </div>
</div>

您还width可以根据数据的长度动态计算例如在 VueJS 中,您可以按如下方式进行(考虑30px每个条目):

VueJS

<div style="width: 100%; overflow-x: auto;">
  <div :style="{width: (data.length * 30) + 'px', height: '300px'}">
    <canvas id="chart1" height="300" width="0"></canvas>
  </div>
</div>
这是最简单的解决方案,据我所知,它运行良好。
2021-04-23 10:33:59

所有这些答案都相当混乱和复杂.. 这是我为我的项目所做的。每当数据集更改或容器大小更改时,我都会调用 fitChart()。

HTML:

<div class="chartWrapper">
    <div class="chartContainer">
        <canvas id="chart"></canvas>
    </div>
</div>

CSS:(将宽度和高度设置为您想要的任何值)

div.chartWrapper {
    position: relative;
    overflow: auto;
    width: 100%;
}

div.chartContainer {
    position: relative;
    height: 300px;
}

JS:

var xAxisLabelMinWidth = 15; // Replace this with whatever value you like
var myChart = new Chart(document.getElementById('chart').getContext('2d'), {
    type: 'line',
    data: {},
    options: {
        responsive: true,
        maintainAspectRatio: false
    }
});

function fitChart(){
    var chartCanvas = document.getElementById('chart');
    var maxWidth = chartCanvas.parentElement.parentElement.clientWidth;
    var width = Math.max(mayChart.data.labels.length * xAxisLabelMinWidth, maxWidth);

    chartCanvas.parentElement.style.width = width +'px';
}
您不想添加 jsfiidlle 版本并在此处添加链接。
2021-04-17 10:33:59

这是包含 5000 个数据点的完整工作示例,并根据需要添加尽可能多的数据。滚动条代码取自互联网,因此您可以根据需要对其进行修改。此示例还包含一个具有多个系列的滚动条。(代码已注释)

带滚动条的图表

    <!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
    <div style="width: 500pt;">
    <canvas id="myChart" style="display: block;width: 1333px;height: 369px;"></canvas>
    <section class="range-slider">
        <span class="rangeValues"></span>
        <input value="1" min="1" max="" type="range" />
        <input value="10" min="1" max="" type="range" />
    </section>
    </div>
</body>
<style>
    section.range-slider {
    position: relative;
    width: 700px;
    height: 300px;
    float: left;
    text-align: center;
    }
    section.range-slider input[type="range"] {
    pointer-events: none;
    position: absolute;
    -webkit-appearance: none;
    -webkit-tap-highlight-color: rgba(255, 255, 255, 0);
    border: none;
    border-radius: 14px;
    background: #f1efef;
    box-shadow: inset 0 1px 0 0 #cdc6c6, inset 0 -1px 0 0 #d9d4d4;
    -webkit-box-shadow: inset 0 1px 0 0 #cdc6c6, inset 0 -1px 0 0 #d9d4d4;
    overflow: hidden;
    left: 0;
    top: 50px;
    width: 700px;
    outline: none;
    height: 20px;
    margin: 0;
    padding: 0;
    }
    section.range-slider input[type="range"]::-webkit-slider-thumb {
    pointer-events: all;
    position: relative;
    z-index: 1;
    outline: 0;
    -webkit-appearance: none;
    width: 20px;
    height: 20px;
    border: none;
    border-radius: 14px;
    background-image: -webkit-gradient(
        linear,
        left top,
        left bottom,
        color-stop(0%, #dad8da),
        color-stop(100%, #413f41)
    );
    /* android <= 2.2 */
    background-image: -webkit-linear-gradient(top, #dad8da 0, #413f41 100%);
    /* older mobile safari and android > 2.2 */
    background-image: linear-gradient(to bottom, #dad8da 0, #413f41 100%);
    /* W3C */
    }
    section.range-slider input[type="range"]::-moz-range-thumb {
    pointer-events: all;
    position: relative;
    z-index: 10;
    -moz-appearance: none;
    width: 20px;
    height: 20px;
    border: none;
    border-radius: 14px;
    background-image: linear-gradient(to bottom, #dad8da 0, #413f41 100%);
    /* W3C */
    }
    section.range-slider input[type="range"]::-ms-thumb {
    pointer-events: all;
    position: relative;
    z-index: 10;
    -ms-appearance: none;
    width: 20px;
    height: 20px;
    border-radius: 14px;
    border: 0;
    background-image: linear-gradient(to bottom, #dad8da 0, #413f41 100%);
    /* W3C */
    }
    section.range-slider input[type="range"]::-moz-range-track {
    position: relative;
    z-index: -1;
    background-color: black;
    border: 0;
    }
    section.range-slider input[type="range"]:last-of-type::-moz-range-track {
    -moz-appearance: none;
    background: none transparent;
    border: 0;
    }
    section.range-slider input[type="range"]::-moz-focus-outer {
    border: 0;
    }
</style>
</html>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script>



var ctx = document.getElementById("myChart").getContext("2d");
    // create dummt data

    var labels = [];
    var values = [];

    for(var i=0;i<5000;i++){
        labels.push("Label"+i)
        values.push(Math.random()*30)
    }  
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: "bar",
    // The data for our dataset
    data: {
    labels: labels,
    datasets: [
        {
        label: "My First dataset",
        backgroundColor: "rgb(255, 99, 132)",
        borderColor: "rgb(255, 99, 132)",
        data: values,
        },
    ],
    },
    // Configuration options go here
    options: {},
});


function getVals() {
    // Get slider values
    var parent = this.parentNode;
    var slides = parent.getElementsByTagName("input");
    var min = parseFloat(slides[0].value);
    var max = parseFloat(slides[1].value);
    // Neither slider will clip the other, so make sure we determine which is larger
    if (min > max) {
    var tmp = max;
    max = min;
    min = tmp;}

        var label = [];
        var value = [];

        label = JSON.parse(JSON.stringify(labels)).slice(min, max);

        //var datasets = Data.datasets;
        // IF YOU HAVE MULTIPLE SERIESES

        // ChartObj.data.labels = label;
        // for (var i = 0; i < datasets.length; i++) {
        //     values = datasets[i].data.slice(min, max);
        //     ChartObj.data.datasets[i].data = values;
        // }
        // ChartObj.update();
        value = JSON.parse(JSON.stringify(values)).slice(min, max);
        chart.data.labels = label;
        chart.data.datasets[0].data = value;
        chart.update();

    var displayElement = parent.getElementsByClassName("rangeValues")[0];
    displayElement.innerHTML = "Min : " + min + " Max : " + max;
}

// Initialize Sliders
var sliderSections = document.getElementsByClassName("range-slider");
for (var x = 0; x < sliderSections.length; x++) {
    var sliders = sliderSections[x].getElementsByTagName("input");
    for (var y = 0; y < sliders.length; y++) {
    if (sliders[y].type === "range") {
        sliders[y].oninput = getVals;
        sliders[y].max=JSON.parse(JSON.stringify(labels)).length;
        // Manually trigger event first time to display values
        sliders[y].oninput();
    }
    }
}




</script>