如何在Rails应用程序中实现Highcharts列 - 钻取图表?

时间:2014-04-07 19:27:42

标签: javascript ruby-on-rails ruby highcharts lazy-high-charts

我正在尝试使用Column-Drilldown Chart在我的Rails应用程序中实现Highcharts lazy_high_charts。我想显示从我的数据库中提取并存储在四个数组(区域,areaScores,department和deptScores)中的数据。我将JS从高架网站上列出的example (JSFiddle)转换为ruby时遇到了麻烦。我无法找到任何有关在ruby中创建列向下钻取图表的资源。任何关于如何将钻取图表集成到我的ruby应用程序中的帮助都将受到高度赞赏。

我已经包含了Highcharts演示页面上显示的示例JavaScript和我的控制器方法,该方法用数据填充四个数组并构建高图。

Highcharts列 - 向下钻取图表示例(Javascript)

$(function () {

    Highcharts.data({
        csv: document.getElementById('tsv').innerHTML,
        itemDelimiter: '\t',
        parsed: function (columns) {

            var brands = {},
                brandsData = [],
                versions = {},
                drilldownSeries = [];

            // Parse percentage strings
            columns[1] = $.map(columns[1], function (value) {
                if (value.indexOf('%') === value.length - 1) {
                    value = parseFloat(value);
                }
                return value;
            });

            $.each(columns[0], function (i, name) {
                var brand,
                    version;

                if (i > 0) {

                    // Remove special edition notes
                    name = name.split(' -')[0];

                    // Split into brand and version
                    version = name.match(/([0-9]+[\.0-9x]*)/);
                    if (version) {
                        version = version[0];
                    }
                    brand = name.replace(version, '');

                    // Create the main data
                    if (!brands[brand]) {
                        brands[brand] = columns[1][i];
                    } else {
                        brands[brand] += columns[1][i];
                    }

                    // Create the version data
                    if (version !== null) {
                        if (!versions[brand]) {
                            versions[brand] = [];
                        }
                        versions[brand].push(['v' + version, columns[1][i]]);
                    }
                }

            });

            $.each(brands, function (name, y) {
                brandsData.push({ 
                    name: name, 
                    y: y,
                    drilldown: versions[name] ? name : null
                });
            });
            $.each(versions, function (key, value) {
                drilldownSeries.push({
                    name: key,
                    id: key,
                    data: value
                });
            });

            // Create the chart
            $('#container').highcharts({
                chart: {
                    type: 'column'
                },
                title: {
                    text: 'Browser market shares. November, 2013'
                },
                subtitle: {
                    text: 'Click the columns to view versions. Source: netmarketshare.com.'
                },
                xAxis: {
                    type: 'category'
                },
                yAxis: {
                    title: {
                        text: 'Total percent market share'
                    }
                },
                legend: {
                    enabled: false
                },
                plotOptions: {
                    series: {
                        borderWidth: 0,
                        dataLabels: {
                            enabled: true,
                            format: '{point.y:.1f}%'
                        }
                    }
                },

                tooltip: {
                    headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
                    pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
                }, 

                series: [{
                    name: 'Brands',
                    colorByPoint: true,
                    data: brandsData
                }],
                drilldown: {
                    series: drilldownSeries
                }
            })

        }
    });
});

我的控制器:

  def generateOrgBreakdownReport
    # First, query the database for the data you need for the report
    @jsonanswerBRKD = queryDatabaseForOrgProgressReport()

    # Second, process and combine data as needed for the report
    @areaBreakdown, @deptBreakdown, @employBreakdown = computeAreaAndDeptPrepareScore(@jsonanswerBRKD)

    # Third, you'll need to put the processed data into a format 
    # Highcharts will understand for the data series it uses
    # for the graph. 

    #THESE ARRAYS HOLD THE NAMES AND SCORES OF AREAS AND DEPARTMENTS
     @deptScores, @departments, @areaScores, @areas = cycleThroughProcessedDataAndCreateHighChartsDataSetsBreakdown(@areaBreakdown, @deptBreakdown, @employBreakdown) 

    # Last, we put the newly made data sets for Highcharts to work its magic.

    #DONT KNOW HOW TO IMPLEMENT DRILLDOWN FOR RUBY
    @orgBreakdown = LazyHighCharts::HighChart.new('column') do |f|
      f.chart( type: 'column' )
      f.xAxis(
        title: { text: "Areas" },
        type: 'category'
      )
      f.yAxis(
        title: { text: "Preparedness Score (%)"},
      )
      f.series(
        name: "Department Score",
        colorByPoint: true, 
        data: @deptScores
      )
      f.series(
        name: "Area Score", 
        data: @areaScores
      )
      f.title( 
        text: "Organizational Breakdown"
      )
      f.options[:xAxis][:categories] = @areas
      f.drilldown({:series=>{
        name:"Dept. Score",
        data: @deptScore
        }
        })

    end
  end

谢谢, 马特

2 个答案:

答案 0 :(得分:4)

我没有使用过Lazy Highcharts,但假设它反映了JavaScript API中的JSON,你需要按名称添加子系列,例如

  f.series(
    name: "Department Score",
    colorByPoint: true, 
    data: @deptScores,
    drilldown: "subdept"  #add this 
  )

然后你需要添加钻取数据,如果Lazy Highcharts支持它,它可能看起来像这样:

  f.drilldown(
    series: {
      id: "subdept",
      data: [
        ["One", 1],
        ["Two", 2],
        ["Three", 3]
      ]
    }
  )

请参阅此basic drilldown fiddle,了解生成的Javascript的外观。

答案 1 :(得分:0)

要在Rails中进行深入分析,您必须确保在您的JavaScript清单文件(application.js)中包含钻取模块。

我还必须下载该文件,因为它不是我的highcharts模块目录。您可以在此处找到该文件:http://code.highcharts.com/modules/drilldown.js

将此添加到application.js:

//= require highcharts/modules/drilldown

在Rails之外,你可以包括这样的钻取模块:

<script src="http://code.highcharts.com/modules/drilldown.js"></script>