【问题标题】:How to get the x axis labels in flot?如何在flot中获取x轴标签?
【发布时间】:2012-03-13 13:59:31
【问题描述】:

我正在使用 Flot 创建图表。 这是我的代码jsFiddle code

function drawSeriesHook(plot, canvascontext, series) {
var ctx = canvascontext,
    plotOffset = plot.offset(),
    labelText = 'VALUE', // 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.color === '#F8C095') {
    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();
}
}
  1. 在我的 drawseriesHook 函数中,我需要获取 x 轴标签,例如 Data1、Data2、Data3、Data4
  2. 有没有办法在不使用 series.label & series.color 的情况下唯一标识最后一个数据项。目前我已经通过修改函数中的 series.color 来标识它

【问题讨论】:

    标签: javascript jquery-mobile cordova flot bar-chart


    【解决方案1】:

    1.) 好的,我想你想为每个条设置labelText。在 for 循环中添加以下行:

    labelText = series.xaxis.ticks[i / ps].label;
    

    另见updated example

    2.) 您可以将自己的值添加到 data,例如标记最后一个:

    var data = [
        {
            label : 'Used',
            color : '#EF7816',
            data : [ [ 1, 85], [ 2, 50 ], [ 3, 18], [ 4, 8 ] ],
            last : false
        },
        ...
        {
            color : '#F8C095',
            data : [ [ 1, 12], [ 2, 10], [ 3, 3], [ 4, 2] ],
            last : true
        }
    ];
    

    在你的钩子中你可以检查标志:

    if (series.last) { ...
    

    另见下updated example

    【讨论】:

    • 这个标签变量将包含所有的刻度标签。如何单独获取标签?
    • @Coder_sLaY:你不想要全部,你只想要当前标签?
    • 是的,但是当我发出警报(标签)时,我得到了所有 4 个。我只需要第一个。
    • 我已经为你的第二个问题添加了一个可能的答案。
    • 你真棒 scessor...谢谢伙计... :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多