Flot 图表 - 打开/关闭系列

2024-04-19前端开发问题
6

本文介绍了Flot 图表 - 打开/关闭系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我成功建立了我的 flot 图表,基于 这篇上一篇文章

I was successfully established my flot chart, based on this previous post

我想让查看者通过单击来显示/隐藏该系列.我找到了一堆解决方案,包括官方的和其他的,但没有一个对我有用.我来解释一下:

I want to enable to viewer to show/hide the series with a click. I found bunch of solutions, both official and others, but none of those worked for me. I'll explain:

  1. 官方开启/关闭系列:这行得通,但看起来很混乱,因为传说最终被复制了两次(一旦系列关闭,官方传说就会消失).
  2. Hiddengraphs.js:这是一个插件,可以在插件库中找到,但它无法与 Chrome 很好地交互(尝试了不止一台机器,它只是不起作用).
  3. 这个解决方案实际上非常好(我不介意没有复选框可以检查),但是当我将它集成到我的代码中时,我得到的只是跳转"到页面顶部,没有任何反应.
  4. 最后,我找到了这个解决方案,虽然使用另一个 js,但它也有效库,称为 flot.togglelegend.js.在这个实现中,我发现了与 flot.cust.js 的一些主要冲突,并且无法让它们一起工作.
  1. Official turning series on/off: this works, but looks very messy as the legend is eventually duplicated twice (disappears from official legend once the series turned off).
  2. Hiddengraphs.js: this is a plugin which can be found at the plugin repository, but it doesn't work and interact well with Chrome (tried more than one machine, it just don't work).
  3. This solution is actually really nice (I don't mind that there are no checkboxes to check), but when I integrated it into my code, all I got was "jumping" to the top of the page, and nothing happens.
  4. Lastly, I found this solution, which also works, altough using another js library, called flot.togglelegend.js. In this implementation I found some major conflicts with flot.cust.js, and couldn't get them both to work together.

这是我当前的js(用coffeescript编写)

Here's my current js (written in coffeescript)

    colorArray = []
    colorArray.push "rgba(180, 0, 75,    0.6)"
    colorArray.push "rgba(0, 150, 100,   0.6)"
    colorArray.push "rgba(0, 0, 255,     0.6)"
    colorArray.push "rgba(140, 0, 255,   0.6)"
    colorArray.push "rgba(90, 180, 20,   0.6)"
    colorArray.push "rgba(255, 236, 0,   0.6)"
    colorArray.push "rgba(234, 170, 21,  0.6)"
    colorArray.push "rgba(95, 180, 190,  0.6)"
    colorArray.push "rgba(214, 92, 63,   0.6)"
    colorArray.push "rgba(218, 106, 234, 0.6)"
    colorArray.push "rgba(213, 128, 155, 0.6)"

    # chart colors default 
    $chrt_border_color = "#efefef"
    $chrt_grid_color = "#DDD"
    $chrt_main = "#E24913"

    # red       
    $chrt_second = "#6595b4"
    # blue      
    $chrt_third = "#FF9F01"
    # orange    
    $chrt_fourth = "#7e9d3a"
    # green     
    $chrt_fifth = "#BD362F"
    # dark red  
    $chrt_mono = "#000"

    Chart = 

    generateDataObjects: (all_series, all_series_data) ->
        plotData = []

        for series, i in all_series
            obj =
                label: series.replace /__/g, "|"
                data: all_series_data[i]
                color: colorArray[i]

            plotData.push obj

        return plotData

    togglePlot: (seriesIdx) ->
        someData = plot.getData()
        someData[seriesIdx].lines.show = not someData[seriesIdx].lines.show
        plot.setData someData
        plot.draw()
        return  

    getTooltip: (label, xval, yval, flotItem) ->
            return 'Build: <span>'+ flotItem.series.data[flotItem.dataIndex][6]+'</span>' +" |     Run ID: <strong> #{flotItem.series.data[flotItem.dataIndex][7].toString()}</strong>" + '<br> Result: <span>'+Chart.commify(yval)+'</span>'

    commify: (x) ->
        return x.toString().replace(/B(?=(d{3})+(?!d))/g, ",");

    generateChartOptions: (legend_container, ticks) ->
        return (
            series:
                lines:
                    show: true

                points:
                    show: true

            crosshair:
                mode: "x"

            legend:
                container: $("##{legend_container}")
                labelFormatter: (label, series) ->
                    "<a href="javascript:void(0);" onClick="Chart.togglePlot(" + series.idx + "); return false;">" + label + "</a>"
                noColumns: 4
                # hideable: true

            grid:
              hoverable: true
              clickable: true
              tickColor: $chrt_border_color
              borderWidth: 0
              borderColor: $chrt_border_color

            tooltip: true
            tooltipOpts: 
              content : Chart.getTooltip
              #content : "Value <b>$x</b> Value <span>$y</span>",
              defaultTheme: false

            xaxis:
                ticks: ticks
                rotateTicks: 30

            selection:
                mode: "xy"
            )



     jQuery ->
        if $("#normalized_bw_chart").length         # render only if the chart-id is present

            raw_data = $("#normalized_bw_chart").data('results')
            ticks = $("#normalized_bw_chart").data('ticks')
            all_series = $("#normalized_bw_chart").data('series')

            plot = $.plot($("#normalized_bw_chart"), Chart.generateDataObjects(all_series, raw_data), Chart.generateChartOptions('normalized_bw_legend', ticks))    

        if $("#concurrent_flows_chart").length      # render only if the chart-id is present

            raw_data = $("#concurrent_flows_chart").data('results')
            ticks = $("#concurrent_flows_chart").data('ticks')
            all_series = $("#concurrent_flows_chart").data('series')

            plot = $.plot($("#concurrent_flows_chart"), Chart.generateDataObjects(all_series, raw_data), Chart.generateChartOptions('concurrent_flows_legend', ticks))

        if $("#bandwidth_chart").length         # render only if the chart-id is present

            raw_data = $("#bandwidth_chart").data('results')
            ticks = $("#bandwidth_chart").data('ticks')
            all_series = $("#bandwidth_chart").data('series')

            plot = $.plot($("#bandwidth_chart"), Chart.generateDataObjects(all_series, raw_data), Chart.generateChartOptions('bandwidth_legend', ticks))    

        $("[data-behavior~=chart-selection]").bind "plotselected", (event, ranges) ->
                selected_chart = $(this).attr('id')[0...-6] # slicing the name of the selected item
                console.log  ("zooming in to " + selected_chart)
                plot = $.plot($("##{selected_chart}_chart"), plot.getData(), $.extend(true, {}, Chart.generateChartOptions(selected_chart+'_legend', ticks),
                  xaxis:
                    min: ranges.xaxis.from
                    max: ranges.xaxis.to

                  yaxis:
                    min: ranges.yaxis.from
                    max: ranges.yaxis.to
                ))
             return

        $("[data-behavior~=chart-selection]").bind "dblclick", (event, pos, item) ->
                selected_chart = $(this).attr('id')[0...-6] # slicing the name of the selected item
                console.log  ("zooming out to " + selected_chart)
                plot = $.plot($("##{selected_chart}_chart"), plot.getData(), $.extend(true, {}, Chart.generateChartOptions(selected_chart+'_legend', ticks),
                  xaxis:
                    min: null
                    max: null
              yaxis:
                min: null
                max: null
            ))
         return

这是一个小提琴:http://jsfiddle.net/danklein/0tn1uzs9/3/

非常感谢!

推荐答案

1) 当 Chart 对象的作用域不是全局的时,直接在 HTML 中的 onClick 是个坏主意.我将其更改为 jquery 事件处理程序:

1) The onClick directly in the HTML is a bad idea when the scope of the Chart object is not global. I changed it to a jquery event handler:

$('body').on 'click', 'a.legendtoggle', (event) ->
    Chart.togglePlot($(this).data('index'))
    return false

2)labelFormatter函数中的series对象没有idx属性,所以我在Chart<中使用了一个变量/code> 对象:

2) The series object in the labelFormatter function has no idx property, so I used a variable inside the Chart object:

labelFormatter: (label, series) ->
    "<a href="#" class="legendtoggle" data-index="" + Chart.legendindex++ + "">" + label + "</a>"

3) 我还将您的 plot 对象放在 Chart 中,以便可以在 togglePlot 函数中访问它.我将 lines 更改为 points 因为您的数据每个系列只有一个数据点:

3) I also put your plot object inside Chart so that it can be accessed inside the togglePlot function. And I changed the lines to points since your data has only one datapoint per series:

togglePlot: (seriesIdx) ->
    someData = this.plot.getData()
    someData[seriesIdx].points.show = not someData[seriesIdx].points.show
    this.plot.setData someData
    this.plot.draw()
    return

这应该是我改变的全部,但如果我得到了一切,请自己比较.
这是一个工作小提琴:http://jsfiddle.net/jhpgtxz1/2/

That should be all I changed, but compare for yourself if I got everything.
Here is a working fiddle: http://jsfiddle.net/jhpgtxz1/2/

PS:我再也不会使用 CoffeeScript 了 :-(

PS: Never again CoffeeScript for me :-(

这篇关于Flot 图表 - 打开/关闭系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui中表单会自动刷新的问题
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23 前端开发问题
262

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455