Search code examples
javascriptjqueryruby-on-rails-4flot

getting started with flot in rails4


I'd like some pointers getting a flot "hello world" equivalent running in my rails4 app. I've found lots of examples of creating lovely graphs, but I'm stuck at the basics, like,

  • Once I've downloaded and unzipped flot-0.8.2.zip file, where do I put all those .js files?
  • Do I need all those .js files?
  • What do I add to app/assets/javascripts/application.js file?
  • ...etc.

I'd prefer NOT to use a gem -- at least not yet -- because I want to learn what's going on under the hood.


Solution

  • Answering my own question after looking at some Heroku examples:

    setup:

    • go to http://www.flotcharts.org/
    • download http://www.flotcharts.org/downloads/flot-0.8.2.zip (or whatever's newest) to the directory of your choice
    • unzip it
    • copy jquery.flot.js to the /app/assets/javascripts directory
    • edit /app/assets/javascripts/application.js to include the jquery.flot.js, as in:

      //= require jquery
      //= require jquery_ujs
      //= require jquery.flot.js
      //= require turbolinks
      //= require_tree .
      

    make a graph:

    In any view file, (e.g. /app/views/myclass/index.html.erb), add the following:

    <!-- create a placeholder for the flot graph -->
    <div id="flot-placeholder" style="width:300px; height: 200px"></div>
    
    <script type="text/javascript">
    $(function() {
        var d1 = [];
        for (var i = 0; i < 14; i += 0.5) {
            d1.push([i, Math.sin(i)]);
        }
        var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];
        // A null signifies separate line segments
        var d3 = [[0, 12], [7, 12], null, [7, 2.5], [12, 2.5]];
        $.plot("#flot-placeholder", [ d1, d2, d3 ]);
    });
    </script>
    

    test it:

    Render the page. You should see something similar to http://www.flotcharts.org/flot/examples/basic-usage/index.html