Class SVG::Graph::Line
In: lib/SVG/Graph/Line.rb
Parent: SVG::Graph::Graph
Graph Pie Plot BarBase Schedule Line TimeSeries Bar BarHorizontal REXML Graph SVG dot/f_0.png

Create presentation quality SVG line graphs easily

Synopsis

  require 'SVG/Graph/Line'

  fields = %w(Jan Feb Mar);
  data_sales_02 = [12, 45, 21]
  data_sales_03 = [15, 30, 40]

  graph = SVG::Graph::Line.new({
          :height => 500,
          :width => 300,
    :fields => fields,
  })

  graph.add_data({
          :data => data_sales_02,
    :title => 'Sales 2002',
  })

  graph.add_data({
          :data => data_sales_03,
    :title => 'Sales 2003',
  })

  print "Content-type: image/svg+xml\r\n\r\n";
  print graph.burn();

Description

This object aims to allow you to easily create high quality SVG line graphs. You can either use the default style sheet or supply your own. Either way there are many options which can be configured to give you control over how the graph is generated - with or without a key, data elements at each point, title, subtitle etc.

Examples

www.germane-software/repositories/public/SVG/test/single.rb

Notes

The default stylesheet handles upto 10 data sets, if you use more you must create your own stylesheet and add the additional settings for the extra data sets. You will know if you go over 10 data sets as they will have no style and be in black.

See also

Author

Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>

Copyright 2004 Sean E. Russell This software is available under the Ruby license

Methods

Attributes

area_fill  [RW]  Fill in the area under the plot if true
show_data_points  [RW]  Show a small circle on the graph where the line goes from one point to the next.
stacked  [RW] 
 Accumulates each data set. (i.e. Each point increased by sum of
all previous series at same point). Default is 0, set to ‘1’ to show.

Public Class methods

The constructor takes a hash reference, fields (the names for each field on the X axis) MUST be set, all other values are defaulted to those shown above - with the exception of style_sheet which defaults to using the internal style sheet.

[Source]

# File lib/SVG/Graph/Line.rb, line 85
      def initialize config
        raise "fields was not supplied or is empty" unless config[:fields] &&
        config[:fields].kind_of?(Array) &&
        config[:fields].length > 0
                                super
                        end

Public Instance methods

In addition to the defaults set in Graph::initialize, sets

show_data_points
true
show_data_values
true
stacked
false
area_fill
false

[Source]

# File lib/SVG/Graph/Line.rb, line 97
                        def set_defaults
        init_with(
          :show_data_points   => true,
          :show_data_values   => true,
          :stacked            => false,
          :area_fill          => false
        )

        self.top_align = self.top_font = self.right_align = self.right_font = 1
      end

Protected Instance methods

[Source]

# File lib/SVG/Graph/Line.rb, line 174
      def calc_coords(field, value, width = field_width, height = field_height)
        coords = {:x => 0, :y => 0}
        coords[:x] = width * field
        coords[:y] = @graph_height - value * height
      
        return coords
      end

[Source]

# File lib/SVG/Graph/Line.rb, line 148
      def calculate_left_margin
        super
        label_left = @config[:fields][0].length / 2 * font_size * 0.6
        @border_left = label_left if label_left > @border_left
      end

[Source]

# File lib/SVG/Graph/Line.rb, line 182
      def draw_data
        minvalue = min_value
        fieldheight = (@graph_height.to_f - font_size*2*top_font) / 
                         (get_y_labels.max - get_y_labels.min)
        fieldwidth = field_width
        line = @data.length

        prev_sum = Array.new(@config[:fields].length).fill(0)
        cum_sum = Array.new(@config[:fields].length).fill(-minvalue)

        for data in @data.reverse
          lpath = ""
          apath = ""

          if not stacked then cum_sum.fill(-minvalue) end
          
          data[:data].each_index do |i|
            cum_sum[i] += data[:data][i]
            
            c = calc_coords(i, cum_sum[i], fieldwidth, fieldheight)
            
            lpath << "#{c[:x]} #{c[:y]} "
          end
        
          if area_fill
            if stacked then
              (prev_sum.length - 1).downto 0 do |i|
                c = calc_coords(i, prev_sum[i], fieldwidth, fieldheight)
                
                apath << "#{c[:x]} #{c[:y]} "
              end
          
              c = calc_coords(0, prev_sum[0], fieldwidth, fieldheight)
            else
              apath = "V#@graph_height"
              c = calc_coords(0, 0, fieldwidth, fieldheight)
            end
              
            @graph.add_element("path", {
              "d" => "M#{c[:x]} #{c[:y]} L" + lpath + apath + "Z",
              "class" => "fill#{line}"
            })
          end
        
          @graph.add_element("path", {
            "d" => "M0 #@graph_height L" + lpath,
            "class" => "line#{line}"
          })
          
          if show_data_points || show_data_values
            cum_sum.each_index do |i|
              if show_data_points
                @graph.add_element( "circle", {
                  "cx" => (fieldwidth * i).to_s,
                  "cy" => (@graph_height - cum_sum[i] * fieldheight).to_s,
                  "r" => "2.5",
                  "class" => "dataPoint#{line}"
                })
              end
              make_datapoint_text( 
                fieldwidth * i, 
                @graph_height - cum_sum[i] * fieldheight - 6,
                cum_sum[i] + minvalue
              )
            end
          end

          prev_sum = cum_sum.dup
          line -= 1
        end
      end

[Source]

# File lib/SVG/Graph/Line.rb, line 255
      def get_css
        return "/* default line styles */\n.line1{\n        fill: none;\n        stroke: #ff0000;\n        stroke-width: 1px;     \n}\n.line2{\n        fill: none;\n        stroke: #0000ff;\n        stroke-width: 1px;     \n}\n.line3{\n        fill: none;\n        stroke: #00ff00;\n        stroke-width: 1px;     \n}\n.line4{\n        fill: none;\n        stroke: #ffcc00;\n        stroke-width: 1px;     \n}\n.line5{\n        fill: none;\n        stroke: #00ccff;\n        stroke-width: 1px;     \n}\n.line6{\n        fill: none;\n        stroke: #ff00ff;\n        stroke-width: 1px;     \n}\n.line7{\n        fill: none;\n        stroke: #00ffff;\n        stroke-width: 1px;     \n}\n.line8{\n        fill: none;\n        stroke: #ffff00;\n        stroke-width: 1px;     \n}\n.line9{\n        fill: none;\n        stroke: #ccc6666;\n        stroke-width: 1px;     \n}\n.line10{\n        fill: none;\n        stroke: #663399;\n        stroke-width: 1px;     \n}\n.line11{\n        fill: none;\n        stroke: #339900;\n        stroke-width: 1px;     \n}\n.line12{\n        fill: none;\n        stroke: #9966FF;\n        stroke-width: 1px;     \n}\n/* default fill styles */\n.fill1{\n        fill: #cc0000;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill2{\n        fill: #0000cc;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill3{\n        fill: #00cc00;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill4{\n        fill: #ffcc00;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill5{\n        fill: #00ccff;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill6{\n        fill: #ff00ff;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill7{\n        fill: #00ffff;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill8{\n        fill: #ffff00;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill9{\n        fill: #cc6666;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill10{\n        fill: #663399;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill11{\n        fill: #339900;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n.fill12{\n        fill: #9966FF;\n        fill-opacity: 0.2;\n        stroke: none;\n}\n/* default line styles */\n.key1,.dataPoint1{\n        fill: #ff0000;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key2,.dataPoint2{\n        fill: #0000ff;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key3,.dataPoint3{\n        fill: #00ff00;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key4,.dataPoint4{\n        fill: #ffcc00;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key5,.dataPoint5{\n        fill: #00ccff;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key6,.dataPoint6{\n        fill: #ff00ff;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key7,.dataPoint7{\n        fill: #00ffff;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key8,.dataPoint8{\n        fill: #ffff00;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key9,.dataPoint9{\n        fill: #cc6666;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key10,.dataPoint10{\n        fill: #663399;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key11,.dataPoint11{\n        fill: #339900;\n        stroke: none;\n        stroke-width: 1px;     \n}\n.key12,.dataPoint12{\n        fill: #9966FF;\n        stroke: none;\n        stroke-width: 1px;     \n}\n"
      end

[Source]

# File lib/SVG/Graph/Line.rb, line 144
      def get_x_labels
        @config[:fields]
      end

[Source]

# File lib/SVG/Graph/Line.rb, line 154
      def get_y_labels
        maxvalue = max_value
        minvalue = min_value
        range = maxvalue - minvalue
        top_pad = range == 0 ? 10 : range / 20.0
        scale_range = (maxvalue + top_pad) - minvalue

        scale_division = scale_divisions || (scale_range / 10.0)

        if scale_integers
          scale_division = scale_division < 1 ? 1 : scale_division.round
        end

        rv = []
        maxvalue = maxvalue%scale_division == 0 ? 
          maxvalue : maxvalue + scale_division
        minvalue.step( maxvalue, scale_division ) {|v| rv << v}
        return rv
      end

[Source]

# File lib/SVG/Graph/Line.rb, line 110
      def max_value
        max = 0
        
        if (stacked == true) then
          sums = Array.new(@config[:fields].length).fill(0)

          @data.each do |data|
            sums.each_index do |i|
              sums[i] += data[:data][i].to_f
            end
          end
          
          max = sums.max
        else
          max = @data.collect{|x| x[:data].max}.max
        end

        return max
      end

[Source]

# File lib/SVG/Graph/Line.rb, line 130
      def min_value
        min = 0
        
        if (min_scale_value.nil? == false) then
          min = min_scale_value
        elsif (stacked == true) then
          min = @data[-1][:data].min
        else
          min = @data.collect{|x| x[:data].min}.min
        end

        return min
      end

[Validate]