EzDevInfo.com

lazy_high_charts

Make highcharts a la ruby , works in rails 4.X / 3.X, and other ruby web frameworks Suipit: Software Web de administración de proyectos y trabajo en equipo administra tus proyectos y trabaja en equipo en la web con suipit. organiza reuniones, tareas, intercambia mensajes y comparte archivos.

Race condition leading to Highcharts error #13

I have some tabs which are generated dynamically. Clicking on any of this tabs loads multiple charts(three or four) like a pie, column or a linechart simultaneously. I append this charts into dynamically generated html divs. All works good if i had to click a tab and wait for all the charts to be loaded. Problem happens when i keep on clicking tabs one after the other and not wait till all the charts are loaded. i get a javascript error inside highcharts.js file which logs Highcharts error #13. As far as i know i am doing proper document ready checks and then loading my charts into the divs. What seems to be the problem ? Is there a race condition happening or due to my code running asynchronously leading to problems? Here is the code:

//Function called on tablick:
function GetPod(podObj) {

        savedPortletsObj = [];
        var objtab = new Array();
        var htmlMarkup = '';
        $('#podHolder').empty();

        for (v = 0, pCount = podObj.length; v < pCount; v++) {
            htmlMarkup = "";
            // htmlMarkup = htmlMarkup + " <div  class='table-cell'>";
            htmlMarkup = htmlMarkup + " <article class='db-box bigFont' id='" + podObj[v].id + "_art' style='height: 100%;'>";
            htmlMarkup = htmlMarkup + " <div class='box-head' ><span> <strong>" + podObj[v].title.toString() + "</strong></span></div>";
            htmlMarkup = htmlMarkup + " <div class='dashboard-container'>";
            htmlMarkup = htmlMarkup + " <div class='tableContentDiv height250 fadeInBox' id='" + podObj[v].id + "'> "; // Charts are appended into this div
            htmlMarkup = htmlMarkup + " </div>";
            htmlMarkup = htmlMarkup + " </div>";
            htmlMarkup = htmlMarkup + " </article>";
            // htmlMarkup = htmlMarkup + " </div>";
            $(htmlMarkup).appendTo($('#podHolder')); // Finally appending the chart div to the parent div
            buildChart(podObj[v]);
            savedPortletsObj[v] = podObj[v];
        }

// Then i call buildChart

function buildChart(podObj) {
        switch (podObj.PodAttributes.type) {
            case "ColumnChart":
                // chartTypes[podObj.id] = podObj.PodAttributes.type;
              //  requirejs(["HTML5SpendDashboard/includes/js/views/column.chart.js"], function () {
                    var objChart = ColumnChart.getInstance();
                    onSuccessLoadChart(podObj, objChart);
              //  });
                break;
            case "dataGrid":
                //  chartTypes[podObj.id] = podObj.PodAttributes.type;
               // requirejs(["HTML5SpendDashboard/includes/js/views/grid.js"], function () {
                    var objChart = DataGrid.getInstance();
                    onSuccessLoadChart(podObj, objChart);
               // });

                break;
            case "lineChart":
               // //  chartTypes[podObj.id] = podObj.PodAttributes.type;
                //requirejs(["HTML5SpendDashboard/includes/js/views/line.chart.js"], function () {
                    var objChart = LineChart.getInstance();
                    onSuccessLoadChart(podObj, objChart);
               // });
                break;
            case "pieChart":
                //  chartTypes[podObj.id] = podObj.PodAttributes.type;
               // requirejs(["HTML5SpendDashboard/includes/js/views/pie.chart.js"], function () {
                    var objChart = PieChart.getInstance();
                    onSuccessLoadChart(podObj, objChart);
              //  });
                break;
        }
    }
    function onSuccessLoadChart(podObj, objChart) {

        objChart.BaseViewRef.Variables.ViewProperties = podObj;
        objChart.Build();

    }

// FInally Build is called after the instance was created for it , For eg: Column chart will be (Have created a separate js files for each chart)

var ColumnChart = (function () {
var instantiated;
var chart;
function init() {
    return {
        "ResultMethodName": "onResultHttpService",
        "Message": "ColumnChartdemo",
        "Build": function () {
            var objServiceLayer = $SL.getInstance();
            var param = {};
            param["QueryID"] = this.BaseViewRef.Variables.ViewProperties.InputParams;
            objServiceLayer.executeMethod("GetPodFilterData", param, "onResultHttpService", this, this.BaseViewRef.Variables.ViewProperties);

        },
        "BaseViewRef": $BV.getInstance(),
        "onResultHttpService": function (result, properties) {
            var json_str = Sys.Serialization.JavaScriptSerializer.deserialize(result);
            var data = [];
            var cat = [];
            var categoryField = properties.PodAttributes.categoryField;
            var valueField = properties.PodAttributes.valueField;
            for (var i in json_str) {
                var serie = new Array(json_str[i][categoryField], json_str[i][valueField]);
                var tmpCat = new Array(json_str[i][categoryField]);
                data.push(serie);
                cat.push(tmpCat);
            }

            $(document).ready(function () {
                chart = new Highcharts.Chart({
                    chart: {
                        renderTo: properties.id,
                        type: 'column'
                    },
                    credits: {
                        enabled: false
                    },
                    title: {
                        text: ''
                    },
                    subtitle: {
                        text: ''
                    },
                    xAxis: {
                        categories: cat
                    },
                    yAxis: {
                        labels: {
                            formatter: function () {
                                return this.value / properties.PodAttributes.divideBy
                            + properties.PodAttributes.dataTipUnitLabel.split('*')[1].toUpperCase();
                            }
                        },
                        min: 0,
                        title: {
                            text: ''
                        }
                    },
                    legend: {
                        layout: 'vertical',
                        backgroundColor: '#FFFFFF',
                        align: 'left',
                        verticalAlign: 'top',
                        x: 100,
                        y: 70,
                        floating: true,
                        shadow: true
                    },
                    tooltip: {
                        formatter: function () {
                            return '' +
                        this.x + ':' + '</br>' + properties.PodAttributes.dataTipUnitLabel.split('*')[0] +
                        Highcharts.numberFormat(this.y / properties.PodAttributes.divideBy, properties.PodAttributes.dPoint) +
                        properties.PodAttributes.dataTipUnitLabel.split('*')[1].toUpperCase();
                        }
                    },
                    plotOptions: {
                        series: {
                            allowPointSelect: true,
                            point: {
                                events: { click: function () {
                                    //                                    alert(this.category + ' : ' + Highcharts.numberFormat(this.y / properties.PodAttributes.divideBy, properties.PodAttributes.dPoint) +
                                    //                            properties.PodAttributes.dataTipUnitLabel.split('*')[1].toUpperCase());
                                    podsToRefresh = html5SpendDashboard.getInstance().getSavedPodObj();
                                    var objBuildChart = html5SpendDashboard.getInstance();
                                    for (var p = 0, pLen = podsToRefresh.length; p < pLen; p++) {
                                        objBuildChart.buildChart(podsToRefresh[p]);
                                    }
                                }
                                }
                            }
                        },
                        column: {
                            pointPadding: 0.2,
                            borderWidth: 0
                        }
                    },
                    series: [{
                        showInLegend: false,
                        data: data
                    }]
                });
            });         
        }

    };
};

return {
    getInstance: function () {
        return instantiated = init();
    }
};

})();


Source: (StackOverflow)

Columns HighChart remove spacing for empty data series

Consider the following high chart

enter image description here

At 15 jun, category II has no data, what if I dont want that spacing left for it, Is there anyway to remove such spaces.

for code reference

`http://jsfiddle.net/G5S9L/8/`

Source: (StackOverflow)

Advertisements

lazy_high_charts and foundation conflict loading javascript

I'm using lazy_high_charts and foundation 4.

In my view I have <%= high_chart("my_id", @chart) %>, which generates the following:

<section>
  <script type="text/javascript">
    (function() {
      var onload = window.onload;                      # I think
      window.onload = function(){                      # the issue
        if (typeof onload == "function") onload();     # is here
          var options = { "title": { "text": "Combination chart" },"legend": { "layout": "vertical","style": {  } },"xAxis": {  },"yAxis": { "title": { "text": null },"labels": {  } },"tooltip": { "enabled": true },"credits": { "enabled": false },"plotOptions": { "areaspline": {  } },"chart": { "defaultSeriesType": "line","renderTo": "my_id" },"subtitle": {  },"series": [{ "type": "spline","name": "Average","data": [ 3,2.67,3,6.33,3.33 ] }] };

    window.chart_my_id = new Highcharts.Chart(options);

      };
    })()
  </script>
<div id="my_id"></div>
</section>

However, it is not displaying because of the following lines generated by foundation 4 in my application.js

$(document).foundation();
$(function(){ $(document).foundation(); });

If I delete those lines the chart loads.

How can I use foundation and lazy_high_charts together?


Source: (StackOverflow)

afterSetExtremes callback for highcharts

I'm creating a highchart using the lazy_highcharts gem. I'd like to make use of the afterSetExtremes callback to regenerate some other data on the page on zooming. I've tried several ways, currently trying:

 @chart = LazyHighCharts::HighChart.new('graph') do |f|
                    f.chart(:zoomType =>'x', :defaultSeriesType => 'spline')
                    f.x_axis(:type=> 'datetime', :events => {:afterSetExtremes => "functon(event){alert('something')}"} )
end

But that gives me the error

Uncaught TypeError: Object functon(event){alert('something')} has no method 'apply'

in the javascript console when I zoom the chart. I assume this has something to do with the generator not correctly setting up the callback function, setting it as a string instead of interpreting it as a function.

I've also tried to set it on my chart object via javascript after creation, but so far have had no luck with that. A few attempts below

chart_my_id4.xAxis.events = {setExtremes: function(event) {
      alert('set extremes');
    }};
chart_my_id4.xAxis[1].events = {setExtremes: function(event) {
      alert('set extremes');
    }};

No luck there either.

Any insight appreciated, thank you.


Source: (StackOverflow)

How to correct mouse event in Highcharts

I am trying to plot xy line in which y axis is reversed and I am getting plot but mouse event I am unable to correct it it is showing reverse event, and I want to find min and mix of axis automatically how this can be done? And how to bring x axis on top?

This is my code:

JS

$(function () {
var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        zoomType: 'xy',
        marginLeft: 50,
        marginBottom: 90
    },

   // How to get minmax automatically zooming is a issue
   // reverse is true
    yAxis: {
        reversed: true,
        min:0,max:50
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },

   series: [
           {
                   name: '01-Jan-2014',
                   data: [[30,0],[28,10]]
           }
           ]
});
});

HTML

  <script src="http://code.highcharts.com/highcharts.js"></script>
  <div id="container" style="height: 400px"></div>

Here is a JS Fiddle.

Whether its possible to pass string inside series ? may be my question is silly please tell me whether its possible, like below I am interested

   string mystring = "{
                 name: '01-Jan-2014',
                 data: [[28, 10],[30, 0]]
               },
               {
                 name: '01-Jan-2014',
                 data: [[28, 10],[30, 0]]
               }"

In series part of code I would like to do like below

                 series: [ 
                             mystring
                         ]

Expected output from this array, sorted y axis GOOD PATTERN - Fiddle but mouse movement is not working

data:[
[ 25.290,1.000 ],
[ 25.240,2.000 ],
[ 25.210,3.000 ],
[ 25.190,4.000 ],
[ 25.180,5.000 ],
[ 25.170,6.000 ],
[ 25.160,7.000 ],
[ 25.310,8.000 ],
[ 25.210,9.000 ],
[ 25.170,10.000 ],
[ 25.160,11.000 ],
[ 25.160,12.000 ],
[ 25.150,13.000 ],
  ]

here I sorted xaxis - mouse event is alright but plot pattern (line) is not the one which I expect BAD PATTERN - Fiddle

   data:[
[ 25.150,13.000 ],
[ 25.160,12.000 ],
[ 25.160,11.000 ],
[ 25.160,7.000 ],
[ 25.170,6.000 ],
[ 25.170,10.000 ],
[ 25.180,5.000 ],
[ 25.190,4.000 ],
[ 25.210,9.000 ],
[ 25.210,3.000 ],
[ 25.240,2.000 ],
[ 25.290,1.000 ],
[ 25.310,8.000 ],
  ]

Source: (StackOverflow)

Undefined method `year' with Rails / Lazy_High_Charts

I'm fairly new to rails and I'm trying to set the pointStart date in lazy_high_charts to pull the created_at date from my database table. I get the following error when trying to format the date and I'm not sure why:

undefined method 'year' for "Nov 13, 2012":String

Here's my controller#index:

def index
authorize! :index, @user, :message => 'Not authorized as an administrator.'

@date = User.pluck(:created_at).first

@count = User.pluck(:sign_in_count)

@h = LazyHighCharts::HighChart.new('graph') do |f|
f.options[:title][:text] = "Number of Logins"
f.options[:chart][:defaultSeriesType] = "area"
f.options[:chart][:inverted] = false
f.options[:chart][:zoomType] = 'x'
f.options[:legend][:layout] = "horizontal"
f.options[:legend][:borderWidth] = "0"
f.series(:pointInterval => 1.day, :pointStart => @date.strftime("%b %d, %Y"), :name => 'Logins', :color => "#b00000", :data => @count)
f.options[:xAxis] = { :minTickInterval => 24 * 3600 * 1000, :type => "datetime", :dateTimeLabelFormats => { day: "%b %e"}, :title => { :text => nil }, :labels => { :enabled => true } }
  end
end

I've been messing with it for a while and this is the closest I could get.


Source: (StackOverflow)

Highchart - highstock scroll out of sync with zoom

I have a chart on which I am showing very small interval time data (close to 2 minutes), when I zoom In using drag at the centre of chart, the call to server gets the zoomed data but the at x-axis the navigator(horizontal scroll) moves the zoomed in data to extreme left it should have been in centre of time line.

Say for example timeline has interval in seconds as below

0---30---60---90---120
and I zoom in at 30 to 90
The navigator or scroll axis should have stayed at 0---120 and the focus part should be 30---90
but In my case it changing the navigator to 30 to 120 and focus area moves to extreme left.

Note: with bigger time intervals it works fine

Source: (StackOverflow)

How to implement Highcharts column-drilldown chart in Rails application?

I'm trying to implement a Highcharts Column-Drilldown Chart in my Rails application using lazy_high_charts. I want to display data that's being pulled from my database and stored in four arrays (areas, areaScores, departments, and deptScores). I'm having trouble converting the JS from the example (JSFiddle) listed on the highchart site into ruby. I have not been able to find any resources on creating a column-drilldown chart in ruby. Any help on how to integrate the drilldown chart into my ruby application would be highly appreciated.

I have included the sample JavaScript shown on the Highcharts demo page and my controller method that populates the four arrays with data and builds the highchart.

Highcharts Column-Drilldown Chart Example (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
                }
            })

        }
    });
});

My Controller:

  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

Thanks, Matt


Source: (StackOverflow)

HighCharts: Reduce size of chart

Does anyone know how to reduce the size of this pie chart? I am using Lazy High Charts gem.

return LazyHighCharts::HighChart.new('pie') do |f|
      f.chart({:defaultSeriesType=>"pie" , :margin=> [0, 0, 0, 0],  backgroundColor: "#F5F5F5", renderTo: "mediamix#{akid.to_s}"} )
      f.series({:type=> 'pie', :name=> "Count",:data=> data_val, borderWidth: 0})
      f.title({ :text=> nil})
      f.plot_options({:pie=>{:allowPointSelect=>true, :cursor=>"pointer" , dataLabels: {enabled: true}, showInLegend: false}})
    end

enter image description here


Source: (StackOverflow)

My Highcharts graph with multiple axis ignores the max value I set for the first yaxis

I have this chart with multiple axis.

It's coded with the Ruby gem lazy_high_charts, but only difference from Highcharts is the Ruby syntax.

My problem is that I've set the first yAxis to have a :max => 10, as no values will ever be higher than 10. For some reason though, this is being ignored. Any ideas?

@rating_development = LazyHighCharts::HighChart.new('graph') do |f|
  f.title(:text => "Some title")
  f.xAxis(:categories => categories, :tickInterval => categories.size / 10, :labels => {:y => 27})
  f.series(:name => "1st thing", :color => "#000000", :lineWidth => 4, :yAxis => 0, :data => first_data_set, :marker => { :enabled => false })
  f.series(:name => "2nd thing", :color => "#0030ff", :yAxis => 1, :data => second_data_set, :marker => { :enabled => false }, :dash_style => 'shortdot')
  f.series(:name => "3rd thing", :color => "#ff0006", :yAxis => 2, :data => third_data_set, :marker => { :enabled => false }, :dash_style => 'shortdot')

  f.yAxis [
    {:title => {:text => "1st thing", :style => {:color => "#000000"}}, :tickInterval => 1, :max => 10, :plotBands => [{:color => '#af0000', :from => 0, :to => 3}, {:color => '#df7000', :from => 3, :to => 5}, {:color => '#f4d600', :from => 5, :to => 7}, {:color => '#87b014', :from => 7, :to => 9}, {:color => '#5aa417', :from => 9, :to => 10}], :labels => {:style => {:color => "#000000"}}},
    {:title => {:text => "2nd thing", :style => {:color => "#0030ff"}}, :opposite => true, :min => 0, :labels => {:style => {:color => "#0030ff"}}},
    {:title => {:text => "3rd thing", :style => {:color => "#ff0006"}}, :opposite => true, :min => 0, :labels => {:style => {:color => "#ff0006"}}}
  ]
  f.legend(:enabled => false)
end

Source: (StackOverflow)

Rails App Plotting Zeros in Highchart Graph via Lazy_High_Charts Gem

I'm still very new to Rails but moving along fairly smoothly I would say. So for practice I'm working on what's supposed to be a simple application where a user can input their weight and that info, over a 30 day period, is displayed to them via a Highcharts line graph using the Lazy Highcharts gem. I followed Ryan Bates' Railscast #223 to get started.

My Issue:
Ok, so the inputs are showing up except that on the days that a user doesn't input a value it gets displayed on the chart as '0' (the line drops to bottom of the graph), instead of connecting to the next point on any given day. Not sure if all that makes sense so here's a screenshot:

Screenshot

I found this solution: Highcharts - Rails Array Includes Empty Date Entries

However, when I implement the first option found on that page (convert 0 to null):

(30.days.ago.to_date..Date.today).map { |date| wt = Weight.pounds_on(date).to_f; wt.zero? ? "null" : wt }

the points show up but the line does not, nor do the tooltips...this leads me to think that something is breaking the js. Nothing is apparently wrong in the console though..? From here I thought it might be a matter of using Highchart's 'connectNulls' option but that didn't work either. When implementing the second option (reject method):

(30.days.ago.to_date..Date.today).map { |date| Weight.pounds_on(date).to_f}.reject(&:zero?)

it completely removes all dates that are null from the chart, which messes up the structure completely because the values are supposed to be displayed based on their created_at date.

So back to square one, this is what I'm left with (chart plotting zeros for days without inputs).

Model:

class Weight < ActiveRecord::Base
  attr_accessible :notes, :weight_input

  validates :weight_input, presence: true
  validates :user_id, presence: true

  belongs_to :user

  def self.pounds_on(date)
    where("date(created_at) = ?", date).pluck(:weight_input).last
  end
end

Controller:

def index
  @weights = current_user.weights.all

  @startdate = 30.days.ago.to_date
  @pounds = (30.days.ago.to_date..Date.today).map { |date| Weight.pounds_on(date).to_f }

  @h = LazyHighCharts::HighChart.new('graph') do |f|
    f.options[:title][:text] = " "
    f.options[:chart][:defaultSeriesType] = "area"
    f.options[:chart][:inverted] = false
    f.options[:chart][:zoomType] = 'x'
    f.options[:legend][:layout] = "horizontal"
    f.options[:legend][:borderWidth] = "0"
    f.series(:pointInterval => 1.day, :pointStart => @startdate, :name => 'Weight (lbs)', :color => "#2cc9c5", :data => @pounds )
    f.options[:xAxis] = {:minTickInterval => 1, :type => "datetime", :dateTimeLabelFormats => { day: "%b %e"}, :title => { :text => nil }, :labels => { :enabled => true } }
  end

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @weights }
  end
end

Does anyone have a solution for this? I guess I could be going about this all wrong so any help is much appreciated.


Source: (StackOverflow)

BUG In Highchart's Mouse Event With Plot Type : Line / Spline

It looks like there is some bug in mouse event tracking in highcharts line plot, I am not sure whether its bug or not, I have one more post on same matter here few days ago, How to correct mouse event in Highcharts, in which one of the engineers of highcharts support, suggested to sort x axis, I did the same as he suggested, but result is one which I can't accept in practical

Here is link to Fiddle, please look into it

1 ) Good pattern yaxis sorted mouse event not working ---> Good

    <script src="http://code.highcharts.com/highcharts.js"></script>
    <div id="container" style="height: 400px"></div>
    $(function () {
$('#container').highcharts({
    title: {
        text: 'Y axes reversed'
    },

    yAxis: {
        reversed: true  
    },        
    series: [{
         data:[
[ 25.290,1.000 ],
[ 25.240,2.000 ],
[ 25.210,3.000 ],
[ 25.190,4.000 ],
[ 25.180,5.000 ],
[ 25.170,6.000 ],
[ 25.160,7.000 ],
[ 25.310,8.000 ],
[ 25.210,9.000 ],
[ 25.170,10.000 ],
[ 25.160,11.000 ],
[ 25.160,12.000 ],
[ 25.150,13.000 ],
  ]      
    }]
});
});

2 ) Bad pattern xaxis sorted mouse event is working --->Bad

 <script src="http://code.highcharts.com/highcharts.js"></script>
 <div id="container" style="height: 400px"></div>
$(function () {

$('#container').highcharts({
    title: {
        text: 'Y axes reversed'
    },
    xAxis :{opposite: true, },
    yAxis: {
        reversed: true  
    },        
    series: [{
        data:[
[ 25.150,13.000 ],
[ 25.160,12.000 ],
[ 25.160,11.000 ],
[ 25.160,7.000 ],
[ 25.170,6.000 ],
[ 25.170,10.000 ],
[ 25.180,5.000 ],
[ 25.190,4.000 ],
[ 25.210,9.000 ],
[ 25.210,3.000 ],
[ 25.240,2.000 ],
[ 25.290,1.000 ],
[ 25.310,8.000 ],
  ]
    }]
});
});

Please someone help me to solve issue, This is what I have tried so far My Try on fiddle ,here you can see with same data y axis sorted with scatter plot mouse event is working but not working with line plot.

<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px"></div>

var chart = new Highcharts.Chart({
chart: {
        renderTo: 'container',
        defaultSeriesType: 'scatter'
       },
title :{ 
        text:'overlap, scatter points on line for mouse events, trying to keep same color and legend so that mouse event might work, do not know how to do it'
        },

xAxis : { opposite : true },
yAxis : { reversed : true },
series: [{
name: '07-Jan-2006 07:30:00 AM' ,
data:[
[ 25.290,1.000 ],
[ 25.240,2.000 ],
[ 25.210,3.000 ],
[ 25.190,4.000 ],
[ 25.180,5.000 ],
[ 25.170,6.000 ],
[ 25.160,7.000 ],
[ 25.310,8.000 ],
[ 25.210,9.000 ],
[ 25.170,10.000 ],
[ 25.160,11.000 ],
[ 25.160,12.000 ],
[ 25.150,13.000 ],
  ]
  },{
 name: '07-Jan-2006 07:30:00 AM' ,
 type : 'line',
 marker: {enabled:false},
 enableMouseTracking: false,

 data:[
[ 25.290,1.000 ],
[ 25.240,2.000 ],
[ 25.210,3.000 ],
[ 25.190,4.000 ],
[ 25.180,5.000 ],
[ 25.170,6.000 ],
[ 25.160,7.000 ],
[ 25.310,8.000 ],
[ 25.210,9.000 ],
[ 25.170,10.000 ],
[ 25.160,11.000 ],
[ 25.160,12.000 ],
[ 25.150,13.000 ],
  ]
  }]
  });

Source: (StackOverflow)

LazyHighchart and dated Data

Got a problem with highcharts. I have series with dated data (debit, month) and want to graph it. I can graph data (debit only), but when i want to add datetimes, there are 2 problems :

  • x_axis data are bad displayed (00:00:00.00)(00:00:00.00), expecting month-year (08/2012)
  • Tooltip told me "Invalid date"
def index
    @ops = getConstantOps()
    @js_data = []
    @ops.each { |f|
      tmp = [f.date_operation,f.debit]
      @js_data.push(tmp)
    }
    @h = LazyHighCharts::HighChart.new('graph') do |f|
        f.options[:chart][:defaultSeriesType] = "area"
        f.x_axis({:type =>'datetime'} )
        f.series( :name=>'Ops', :data=>@js_data)
end

Ruby debug(@js_data) says

{--- !ruby/object:LazyHighCharts::HighChart
collection_filter: 
data:
- :name: Ops
  :data:
  - - 2010-07-08
    - 387.0
  - - 2010-08-09
    - 476.0
  - - 2010-09-08
    - 443.0}

So I need not to use "pointInterval" and "pointStart" because for some months I don't have any Ops. That's why I need a 2-dimension array as data param. I'm testing ruby/highcharts combination to build a company app, but quite a new on theese two tools.

Any ideas on how to make this work?

EDIT 11/11/2012 : After a fiw hours of work, it works! I've done a helper to do the crap cast.

Solution :

def getTimestamp(dateTime)
    return (DateTime.parse(dateTime.year.to_s + '-' + dateTime.month.to_s + '-01')).to_i * 1000
end

It look dirty for me (2 casts, dans hard day param). But didn't find cleaner way. If you have one, plz suggest ;).


Source: (StackOverflow)

Highcharts area chart with lazy_chart ruby gem

I am trying to use https://github.com/michelson/lazy_high_charts to render a simple area chart with dates on the x-axis and scores on the y-axis. I used the following snippet from lazy_high_charts. Graph is rendered but x-axis is not dates.

@h = LazyHighCharts::HighChart.new('graph', style: '') do |f|
  f.options[:chart][:defaultSeriesType] = "area"
  f.options[:plotOptions] = {areaspline: {pointInterval: 1.day, pointStart: 10.days.ago}}
  f.series(:name=>'John', :data=>[3, 20, 3, 5, 4, 10, 12 ,3, 5,6,7,7,80,9,9])
  f.series(:name=>'Jane', :data=> [1, 3, 4, 3, 3, 5, 4,-46,7,8,8,9,9,0,0,9])
  f.xAxis(type: :datetime)
end

I would like to have time series with a day interval, something like this http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-pointstart-datetime/.

Above code produces the following html (http://jsfiddle.net/nUxvA/)

I tried to compare both and the plot options is different. How can I have day interval scale on x-axis?


Source: (StackOverflow)

Lazy High Charts: cannot get pie chart to show up

Following the directions here (and correcting for the tag issues in the code sample) I am attempting to implement a pie chart in my app. I load the initial page but the pie chart does not load on the partial (I make it into the html.erb file). A lot of things are hard coded right now so for instance Chart Type, etc do not get passed back to the controller yet.

Can someone help point out where I went awry?

Controller:

  def dynamic_chart
    @chart_types = ChartType.all
    @user_visible_models = ["Asset","Asset Manufacturer","Asset Model", "Map","Campus","Tag","Room", "Room Monitor"]
    @date_ranges = ["Day", "Week", "Month"]
  end

  def gen_chart
    @rooms = Array.new
    Room.all.each do |room|
      @rooms << [room.name, room.asset_count]
    end

    @chart = LazyHighCharts::HighChart.new('pie') do |f|
      f.chart({:defaultSeriesType=>"pie" , :margin=> [50, 200, 60, 170]} )
      series = {
          :type=> 'pie',
          :name=> 'Asset by Rooms',
          :data=> @rooms
      }
      f.series(series)
      f.options[:title][:text] = "THA PIE"
      f.legend(:layout=> 'vertical',:style=> {:left=> 'auto', :bottom=> 'auto',:right=> '50px',:top=> '100px'})
      f.plot_options(:pie=>{
          :allowPointSelect=>true,
          :cursor=>"pointer" ,
          :dataLabels=>{
              :enabled=>true,
              :color=>"white",
              :style=>{
                  :font=>"13px Trebuchet MS, Verdana, sans-serif"
              }
          }
      })
    end

dynamic_chart.html.erb

<%  javascript 'dynamic_chart'  %>

<div id="graph_controls">
  <%= form_tag('activate_reports/dynamic_chart', :class => "well form-inline") do %>
    <%= text_field_tag(:name, nil, :class => "input-small", :placeholder => "Report Name") %>
    <%= collection_select(:activate_report, :chart_type_id, @chart_types, :id, :name, :prompt => "Select chart") %>
    <%= label_tag :x_axis, "X:", :class => "control-label" %>
    <%= select :x_axis, nil, @user_visible_models, :prompt => true %>
    <%= label_tag :y_axis, "Y:", :class => "control-label" %>
    <%= select :y_axis, nil, @user_visible_models, :prompt => true %>
    <%= select :date_range, nil, @date_ranges, :prompt => "Select a day" %>
    <%= link_to("Chart!", "#", :remote => true, :class => "btn", :onclick => 'gen_chart()') %>
  <% end %>

</div>

<div id="chart_area"></div>

_gen_chart.html.erb Partial:

<%= high_chart("chart_area", @chart) %>

gen_chart js function used to initiate the new chart

function gen_chart(){
    jQuery.ajax({
        url: "/activate_reports/gen_chart",
        type: "GET",
        data: {},
        dataType: "html"
    });
}

Source: (StackOverflow)