如何删除flot中的y轴刻度

时间:2012-02-21 09:50:18

标签: javascript jquery-mobile cordova flot

我正在使用flot生成条形图。 这是我的代码bar graph code

  1. 我需要让y轴勾选消失。
  2. 我需要在每个栏的顶部放置一些标签
  3. 怎么做?

1 个答案:

答案 0 :(得分:4)

好的,经过大量的Flot和下载源代码后,我终于找到了一个很好的起点。

jsFiddle演示是here

代码的内容是使用drawSeries的钩子来绘制标签:

function drawSeriesHook(plot, canvascontext, series) {
    var ctx = canvascontext,
        plotOffset = plot.offset(),
        labelText = 'TEST', // customise this text, maybe to series.label
        points = series.datapoints.points,
        ps = series.datapoints.pointsize,
        xaxis = series.xaxis,
        yaxis = series.yaxis,
        textWidth, textHeight, textX, textY;
    // only draw label for top yellow series
    if (series.label === 'baz') {
        ctx.save();
        ctx.translate(plotOffset.left, plotOffset.top);

        ctx.lineWidth = series.bars.lineWidth;
        ctx.fillStyle = '#000'; // customise the colour here
        for (var i = 0; i < points.length; i += ps) {
            if (points[i] == null) continue;

            textWidth = ctx.measureText(labelText).width; // measure how wide the label will be
            textHeight = parseInt(ctx.font); // extract the font size from the context.font string
            textX = xaxis.p2c(points[i] + series.bars.barWidth / 2) - textWidth / 2;
            textY = yaxis.p2c(points[i + 1]) - textHeight / 2;
            ctx.fillText(labelText, textX, textY); // draw the label
        }
        ctx.restore();
    }
}

请参阅注释,了解可以自定义标签的位置。

要删除y轴刻度,这只是一个简单的选项设置。此外,您可以计算每个条形图堆栈的最大y值,然后将其添加大约100来设置最大Y值,以允许标签占用的空间。然后,所有这些的代码变为:

// determine the max y value from the given data and add a bit to allow for the text
var maxYValue = 0;
var sums = [];
$.each(data,function(i,e) {
    $.each(this.data, function(i,e) {
        if (!sums[i]) {
            sums[i]=0;
        }        
        sums[i] += this[1]; // y-value
    });
});
$.each(sums, function() {
    maxYValue = Math.max(maxYValue, this);
});
maxYValue += 100; // to allow for the text


var plot = $.plot($("#placeholder"), data, {
    series: {
        stack: 1,
        bars: {
            show: true,
            barWidth: 0.6,
        },
        yaxis: {
            min: 0,

            tickLength: 0
        }
    },
    yaxis: {
        max: maxYValue, // set a manual maximum to allow for labels
        ticks: 0 // this line removes the y ticks
    },
    hooks: {
        drawSeries: [drawSeriesHook]
    }
});

这应该让你开始。你可以从这里拿走它,我敢肯定。

相关问题