Create attractive charts

    Problem
    I would like to be able to dynamically generate attractive diagrams based on application data.
    We will need

    • Binding Ruby to ImageMagick - RMagick . Installed from the rmagick gem package. Configuring ImageMagick and RMagick can sometimes be a bit confusing. Before installing RMagick, you should look into the collection of the most common questions and answers at rmagick.rubyforge.org/install-faq.html. When everything works out, you just have to rejoice.

    • Chart library for Geoffrey Grosen-bach Beautiful Gruff, which is installed from the gruff gem package .


    Solution
    Let's see how to use Gruff to create attractive diagrams and how to incorporate them into the representations of our applications. Let's get down to business right away.
    All chart logic will be placed in one controller called Graph-Controller. Although it is not necessary to keep the charting logic in a separate controller, in this case we will do just that to put together all the code related to the Gruff library.
    Gruff supports several different types of diagrams: linear, three-dimensional, with areas, circular and compound three-dimensional ( here you can see examples) We will start with a simple pie chart. Typically, a chart is built on data calculated from model objects or some other statistics related to your domain. In order not to complicate the example and make it accessible to all Rails programmers, we will use the statistics of our application as a data model for diagrams.
    Let's add the following stats () action to the new GraphController controller class:

    class GraphController <ApplicationController
       require 'gruff'
       require 'code_statistics'
      
       STATS_DIRECTORIES = [
       % w (Helpers app / helpers),
       % w (Controllers app / controllers),
       % w (APIs app / apis),
       % w (Components components),
       % w (Functional \ tests test / functional),
       % w (Model app / model),
       % w (Unit \ tests test / unit),
       % w (Libraries lib /),
       % w (Integration \ tests test / integration)
       ]. collect {| name, dir |
        [name, "# {RAILS_ROOT} / # {dir}"]
       } .select {| name, dir |
        File.directory?(dir)
       }
       
     def stats
       code_stats = CodeStatistics.new (* STATS_DIRECTORIES)
       statistics = code_stats.instance_variable_get (: @ statistics)
       g = Gruff :: Bar.new (700)
       g.font = "/ Library / Fonts / Arial"
       g.title = "Code Stats"
       g.theme_37signals
       g.legend_font_size = 10
       0xFDD84E .step (0xFF0000, 1500) do | num |
        g.colors << "#% x"% num
       end
       statistics.each do | key, values ​​|
        g.data (key, [values ​​[“codelines”]])
       end
       send_data (g.to_blob,:
            disposition => 'inline' ,:
            type => 'image / png
            ',: filename => 'code_stats.png')
     end
    end
    * This source code was highlighted with Source Code Highlighter .


    Running this action will result in the colorful diagram shown in the figure.
    Let's go through this code. The Gruff library was first requested, and then the value of the constant STATS_DIRECTORIES, borrowed from the Rake task stats (), supplied with Rails, was determined. Its function is to provide a list of directories for processing in the CodeStatistics class.
    Now let's move on to the stats () action. The first two lines set our data model, which will be passed to the chart plotter. Due to the lack of means to gain access to raw statistics, we will have to resort to a rather unsightly trick and use the instance_variable_get () method. In your application, this part should be replaced by a request to select the model that is defined for it.



    The next few lines are spent setting up the chart. The number 700 passed to the constructor determines the width of the image. The header font is set, and then one of the themes available in Gruff is selected (optional). Other themes can also be selected: theme_keynote, theme_rails_keynote, and theme_odeo. Then, since there are rather long words in our legend, the font size of the legend is set. To complete the configuration, we loop through the hexadecimal values ​​to set the range of colors for the chart. With a small data set, this is not necessary, since the default themes have a sufficient set of colors to provide each row of data.
    Finally, we will fill the chart with data, for which we will iterate over the hash containing the statistics of the code, and add to the chart one row of data for each element present in the hash. An array of actual values ​​is used as the second parameter of the data () method related to the chart. In this case, only one value is tracked for each row, but you still need to pass an array, so we use a singleton array containing the number of lines of code in this directory.
    Finally, in order not to create a file in the file system, the send_data () method built into Rails is used to stream image data to the browser.
    And if you want to convert this diagram to a linear one? Nowhere is easier! It is only necessary in the line where Gruff :: Pie is read, read Gruff :: Bar. That's all! The same applies to other chart types available in Gruff, although there are types that are not suitable for our two-dimensional dataset, such as Line and Area. Once the basics have been learned (and ImageMa-gick installed correctly!), Gruff will become a very simple and convenient library for charting. Using a virtually unchanged interface for various types of diagrams greatly simplifies research and experimentation with this tool. PS A little more about the library can be found here Krosspost from my blog








    Also popular now: