You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用dygraphs绘制块状图形而非时序折线图?

问题描述

我不需要典型的时序折线图,而是需要绘制块状图形(如下方图1到图2的转换所示)。我已通过drawCallback计算出每个点的canvas坐标,但不知道如何实际绘制这些块状图形;同时我还需要隐藏原始线条(或许可以用白色绘制来隐藏)。我之前使用过underlayCallback绘制背景块状图形,但现在需要绘制前景块状图形。我设置了循环以在y坐标变化时遍历绘制图形,但drawCallback中没有underlayCallbacks里的CTX。

提前致谢。

drawCallback: function (g, initial) {
    var newdata = [];
    var startcoord = g.toDomCoords(g.file_[0][0],g.file_[0][1]);
    var lowerlimit = g.toDomCoords(g.file_[0][0],minstage);
    console.log(lowerlimit);
    for (i=0; i<g.file_.length; i++) {
        newdata[i] = g.toDomCoords(g.file_[i][0],g.file_[i][1]);
        // when y changes, draw previous block
        if (newdata[1] != startcoord[1]) {

        }
    }
  • 原折线图版本:展示传统的时序折线样式
  • 目标块状图版本:展示由连续块状图形构成的目标样式
解决方案
function barChartPlotter(e) {
var ctx = e.drawingContext;
var points = e.points;

// calculate the height of each block
var limits1 = e.dygraph.toDomCoords(points[0][0],1);
var limits2 = e.dygraph.toDomCoords(points[0][0],2);
var height = limits2[1]-limits1[1];

var bar_width = points[2].canvasx - points[1].canvasx;

// Do the actual plotting.
for (var i = 0; i < points.length; i++) {
    var p = points[i];
    var center_x = p.canvasx;

    // set colors
    switch (points[i].yval) {
        case 1:
            ctx.fillStyle = "#CC0000";
            ctx.strokeStyle = '#CC0000';
            break;
        case 2:
            ctx.fillStyle = "#00CC00";
            ctx.strokeStyle = '#0000CC';
            break;
        case 3:
            ctx.fillStyle = "#0000CC";
            ctx.strokeStyle = '#0000CC';
            break;
        case 4:
            ctx.fillStyle = "#CC00CC";
            ctx.strokeStyle = '#CC00CC';
            break;
    }

    ctx.fillRect(center_x - bar_width / 2, p.canvasy, bar_width, height-1);
    ctx.strokeRect(center_x - bar_width / 2, p.canvasy, bar_width, height-1);
}
}
  • 渲染后的块状图:展示使用上述代码实现的完美块状图形效果

内容的提问来源于stack exchange,提问作者Doug Wolfgram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 03:45:48