-require 'rexml/document'
-require 'SVG/Graph/Graph'
-require 'SVG/Graph/BarBase'
-
-module SVG
- module Graph
- # === Create presentation quality SVG bar graphs easily
- #
- # = Synopsis
- #
- # require 'SVG/Graph/Bar'
- #
- # fields = %w(Jan Feb Mar);
- # data_sales_02 = [12, 45, 21]
- #
- # graph = SVG::Graph::Bar.new(
- # :height => 500,
- # :width => 300,
- # :fields => fields
- # )
- #
- # graph.add_data(
- # :data => data_sales_02,
- # :title => 'Sales 2002'
- # )
- #
- # 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[http://www.w3c.org/tr/svg bar 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.
- #
- # = Notes
- #
- # The default stylesheet handles upto 12 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 12 data sets as they will have no style and
- # be in black.
- #
- # = Examples
- #
- # * http://germane-software.com/repositories/public/SVG/test/test.rb
- #
- # = See also
- #
- # * SVG::Graph::Graph
- # * SVG::Graph::BarHorizontal
- # * SVG::Graph::Line
- # * SVG::Graph::Pie
- # * SVG::Graph::Plot
- # * SVG::Graph::TimeSeries
- class Bar < BarBase
- include REXML
-
- # See Graph::initialize and BarBase::set_defaults
- def set_defaults
- super
- self.top_align = self.top_font = 1
- end
-
- protected
-
- def get_x_labels
- @config[:fields]
- end
-
- 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
-
- def x_label_offset( width )
- width / 2.0
- end
-
- def draw_data
- fieldwidth = field_width
- maxvalue = max_value
- minvalue = min_value
-
- fieldheight = (@graph_height.to_f - font_size*2*top_font) /
- (get_y_labels.max - get_y_labels.min)
- bargap = bar_gap ? (fieldwidth < 10 ? fieldwidth / 2 : 10) : 0
-
- subbar_width = fieldwidth - bargap
- subbar_width /= @data.length if stack == :side
- x_mod = (@graph_width-bargap)/2 - (stack==:side ? subbar_width/2 : 0)
- # Y1
- p2 = @graph_height
- # to X2
- field_count = 0
- @config[:fields].each_index { |i|
- dataset_count = 0
- for dataset in @data
- # X1
- p1 = (fieldwidth * field_count)
- # to Y2
- p3 = @graph_height - ((dataset[:data][i] - minvalue) * fieldheight)
- p1 += subbar_width * dataset_count if stack == :side
- @graph.add_element( "path", {
- "class" => "fill#{dataset_count+1}",
- "d" => "M#{p1} #{p2} V#{p3} h#{subbar_width} V#{p2} Z"
- })
- make_datapoint_text(
- p1 + subbar_width/2.0,
- p3 - 6,
- dataset[:data][i].to_s)
- dataset_count += 1
- end
- field_count += 1
- }
- end
- end
- end
-end
+require 'rexml/document'\r
+require 'SVG/Graph/Graph'\r
+require 'SVG/Graph/BarBase'\r
+\r
+module SVG\r
+ module Graph\r
+ # === Create presentation quality SVG bar graphs easily\r
+ #\r
+ # = Synopsis\r
+ #\r
+ # require 'SVG/Graph/Bar'\r
+ #\r
+ # fields = %w(Jan Feb Mar);\r
+ # data_sales_02 = [12, 45, 21]\r
+ #\r
+ # graph = SVG::Graph::Bar.new(\r
+ # :height => 500,\r
+ # :width => 300,\r
+ # :fields => fields\r
+ # )\r
+ #\r
+ # graph.add_data(\r
+ # :data => data_sales_02,\r
+ # :title => 'Sales 2002'\r
+ # )\r
+ #\r
+ # print "Content-type: image/svg+xml\r\n\r\n"\r
+ # print graph.burn\r
+ #\r
+ # = Description\r
+ #\r
+ # This object aims to allow you to easily create high quality\r
+ # SVG[http://www.w3c.org/tr/svg bar graphs. You can either use the default\r
+ # style sheet or supply your own. Either way there are many options which\r
+ # can be configured to give you control over how the graph is generated -\r
+ # with or without a key, data elements at each point, title, subtitle etc.\r
+ #\r
+ # = Notes\r
+ #\r
+ # The default stylesheet handles upto 12 data sets, if you\r
+ # use more you must create your own stylesheet and add the\r
+ # additional settings for the extra data sets. You will know\r
+ # if you go over 12 data sets as they will have no style and\r
+ # be in black.\r
+ #\r
+ # = Examples\r
+ #\r
+ # * http://germane-software.com/repositories/public/SVG/test/test.rb\r
+ #\r
+ # = See also\r
+ #\r
+ # * SVG::Graph::Graph\r
+ # * SVG::Graph::BarHorizontal\r
+ # * SVG::Graph::Line\r
+ # * SVG::Graph::Pie\r
+ # * SVG::Graph::Plot\r
+ # * SVG::Graph::TimeSeries\r
+ class Bar < BarBase\r
+ include REXML\r
+\r
+ # See Graph::initialize and BarBase::set_defaults\r
+ def set_defaults \r
+ super\r
+ self.top_align = self.top_font = 1\r
+ end\r
+\r
+ protected\r
+\r
+ def get_x_labels\r
+ @config[:fields]\r
+ end\r
+\r
+ def get_y_labels\r
+ maxvalue = max_value\r
+ minvalue = min_value\r
+ range = maxvalue - minvalue\r
+\r
+ top_pad = range == 0 ? 10 : range / 20.0\r
+ scale_range = (maxvalue + top_pad) - minvalue\r
+\r
+ scale_division = scale_divisions || (scale_range / 10.0)\r
+\r
+ if scale_integers\r
+ scale_division = scale_division < 1 ? 1 : scale_division.round\r
+ end\r
+\r
+ rv = []\r
+ maxvalue = maxvalue%scale_division == 0 ? \r
+ maxvalue : maxvalue + scale_division\r
+ minvalue.step( maxvalue, scale_division ) {|v| rv << v}\r
+ return rv\r
+ end\r
+\r
+ def x_label_offset( width )\r
+ width / 2.0\r
+ end\r
+\r
+ def draw_data\r
+ minvalue = min_value\r
+ fieldwidth = field_width\r
+\r
+ unit_size = (@graph_height.to_f - font_size*2*top_font) / \r
+ (get_y_labels.max - get_y_labels.min)\r
+ bargap = bar_gap ? (fieldwidth < 10 ? fieldwidth / 2 : 10) : 0\r
+\r
+ bar_width = fieldwidth - bargap\r
+ bar_width /= @data.length if stack == :side\r
+ x_mod = (@graph_width-bargap)/2 - (stack==:side ? bar_width/2 : 0)\r
+ \r
+ bottom = @graph_height\r
+\r
+ field_count = 0\r
+ @config[:fields].each_index { |i|\r
+ dataset_count = 0\r
+ for dataset in @data\r
+ \r
+ # cases (assume 0 = +ve):\r
+ # value min length\r
+ # +ve +ve value - min\r
+ # +ve -ve value - 0\r
+ # -ve -ve value.abs - 0\r
+ \r
+ value = dataset[:data][i]\r
+ \r
+ left = (fieldwidth * field_count)\r
+ \r
+ length = (value.abs - (minvalue > 0 ? minvalue : 0)) * unit_size\r
+ # top is 0 if value is negative\r
+ top = bottom - (((value < 0 ? 0 : value) - minvalue) * unit_size)\r
+ left += bar_width * dataset_count if stack == :side\r
+ \r
+ @graph.add_element( "rect", {\r
+ "x" => left.to_s,\r
+ "y" => top.to_s,\r
+ "width" => bar_width.to_s,\r
+ "height" => length.to_s,\r
+ "class" => "fill#{dataset_count+1}"\r
+ })\r
+\r
+ make_datapoint_text(left + bar_width/2.0, top - 6, value.to_s)\r
+ dataset_count += 1\r
+ end\r
+ field_count += 1\r
+ }\r
+ end\r
+ end\r
+ end\r
+end\r
-require 'rexml/document'
-require 'SVG/Graph/Graph'
-
-module SVG
- module Graph
- # = Synopsis
- #
- # A superclass for bar-style graphs. Do not attempt to instantiate
- # directly; use one of the subclasses instead.
- #
- # = Author
- #
- # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
- #
- # Copyright 2004 Sean E. Russell
- # This software is available under the Ruby license[LICENSE.txt]
- #
- class BarBase < SVG::Graph::Graph
- # Ensures that :fields are provided in the configuration.
- 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
-
- # In addition to the defaults set in Graph::initialize, sets
- # [bar_gap] true
- # [stack] :overlap
- def set_defaults
- init_with( :bar_gap => true, :stack => :overlap )
- end
-
- # Whether to have a gap between the bars or not, default
- # is true, set to false if you don't want gaps.
- attr_accessor :bar_gap
- # How to stack data sets. :overlap overlaps bars with
- # transparent colors, :top stacks bars on top of one another,
- # :side stacks the bars side-by-side. Defaults to :overlap.
- attr_accessor :stack
-
-
- protected
-
- def max_value
- return @data.collect{|x| x[:data].max}.max
- end
-
- def min_value
- min = 0
-
- if (min_scale_value.nil? == false) then
- min = min_scale_value
- else
- min = @data.collect{|x| x[:data].min}.min
- end
-
- return min
- end
-
- def get_css
- return <<EOL
-/* default fill styles for multiple datasets (probably only use a single dataset on this graph though) */
-.key1,.fill1{
- fill: #ff0000;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 0.5px;
-}
-.key2,.fill2{
- fill: #0000ff;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key3,.fill3{
- fill: #00ff00;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key4,.fill4{
- fill: #ffcc00;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key5,.fill5{
- fill: #00ccff;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key6,.fill6{
- fill: #ff00ff;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key7,.fill7{
- fill: #00ffff;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key8,.fill8{
- fill: #ffff00;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key9,.fill9{
- fill: #cc6666;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key10,.fill10{
- fill: #663399;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key11,.fill11{
- fill: #339900;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-.key12,.fill12{
- fill: #9966FF;
- fill-opacity: 0.5;
- stroke: none;
- stroke-width: 1px;
-}
-EOL
- end
- end
- end
-end
+require 'rexml/document'\r
+require 'SVG/Graph/Graph'\r
+\r
+module SVG\r
+ module Graph\r
+ # = Synopsis\r
+ #\r
+ # A superclass for bar-style graphs. Do not attempt to instantiate\r
+ # directly; use one of the subclasses instead.\r
+ #\r
+ # = Author\r
+ #\r
+ # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>\r
+ #\r
+ # Copyright 2004 Sean E. Russell\r
+ # This software is available under the Ruby license[LICENSE.txt]\r
+ #\r
+ class BarBase < SVG::Graph::Graph\r
+ # Ensures that :fields are provided in the configuration.\r
+ def initialize config\r
+ raise "fields was not supplied or is empty" unless config[:fields] &&\r
+ config[:fields].kind_of?(Array) &&\r
+ config[:fields].length > 0\r
+ super\r
+ end\r
+\r
+ # In addition to the defaults set in Graph::initialize, sets\r
+ # [bar_gap] true\r
+ # [stack] :overlap\r
+ def set_defaults\r
+ init_with( :bar_gap => true, :stack => :overlap )\r
+ end\r
+\r
+ # Whether to have a gap between the bars or not, default\r
+ # is true, set to false if you don't want gaps.\r
+ attr_accessor :bar_gap\r
+ # How to stack data sets. :overlap overlaps bars with\r
+ # transparent colors, :top stacks bars on top of one another,\r
+ # :side stacks the bars side-by-side. Defaults to :overlap.\r
+ attr_accessor :stack\r
+\r
+\r
+ protected\r
+\r
+ def max_value\r
+ @data.collect{|x| x[:data].max}.max\r
+ end\r
+\r
+ def min_value\r
+ min = 0\r
+ if min_scale_value.nil? \r
+ min = @data.collect{|x| x[:data].min}.min\r
+ min = min > 0 ? 0 : min\r
+ else\r
+ min = min_scale_value\r
+ end\r
+ return min\r
+ end\r
+\r
+ def get_css\r
+ return <<EOL\r
+/* default fill styles for multiple datasets (probably only use a single dataset on this graph though) */\r
+.key1,.fill1{\r
+ fill: #ff0000;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 0.5px; \r
+}\r
+.key2,.fill2{\r
+ fill: #0000ff;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key3,.fill3{\r
+ fill: #00ff00;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key4,.fill4{\r
+ fill: #ffcc00;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key5,.fill5{\r
+ fill: #00ccff;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key6,.fill6{\r
+ fill: #ff00ff;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key7,.fill7{\r
+ fill: #00ffff;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key8,.fill8{\r
+ fill: #ffff00;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key9,.fill9{\r
+ fill: #cc6666;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key10,.fill10{\r
+ fill: #663399;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key11,.fill11{\r
+ fill: #339900;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key12,.fill12{\r
+ fill: #9966FF;\r
+ fill-opacity: 0.5;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+EOL\r
+ end\r
+ end\r
+ end\r
+end\r
-require 'rexml/document'
-require 'SVG/Graph/BarBase'
-
-module SVG
- module Graph
- # === Create presentation quality SVG horitonzal bar graphs easily
- #
- # = Synopsis
- #
- # require 'SVG/Graph/BarHorizontal'
- #
- # fields = %w(Jan Feb Mar)
- # data_sales_02 = [12, 45, 21]
- #
- # graph = SVG::Graph::BarHorizontal.new({
- # :height => 500,
- # :width => 300,
- # :fields => fields,
- # })
- #
- # graph.add_data({
- # :data => data_sales_02,
- # :title => 'Sales 2002',
- # })
- #
- # 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 horitonzal bar 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
- #
- # * http://germane-software.com/repositories/public/SVG/test/test.rb
- #
- # = See also
- #
- # * SVG::Graph::Graph
- # * SVG::Graph::Bar
- # * SVG::Graph::Line
- # * SVG::Graph::Pie
- # * SVG::Graph::Plot
- # * SVG::Graph::TimeSeries
- #
- # == Author
- #
- # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
- #
- # Copyright 2004 Sean E. Russell
- # This software is available under the Ruby license[LICENSE.txt]
- #
- class BarHorizontal < BarBase
- # In addition to the defaults set in BarBase::set_defaults, sets
- # [rotate_y_labels] true
- # [show_x_guidelines] true
- # [show_y_guidelines] false
- def set_defaults
- super
- init_with(
- :rotate_y_labels => true,
- :show_x_guidelines => true,
- :show_y_guidelines => false
- )
- self.right_align = self.right_font = 1
- end
-
- protected
-
- def get_x_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
-
- def get_y_labels
- @config[:fields]
- end
-
- def y_label_offset( height )
- height / -2.0
- end
-
- def draw_data
- minvalue = min_value
- fieldheight = field_height
- fieldwidth = (@graph_width.to_f - font_size*2*right_font ) /
- (get_x_labels.max - get_x_labels.min )
- bargap = bar_gap ? (fieldheight < 10 ? fieldheight / 2 : 10) : 0
-
- subbar_height = fieldheight - bargap
- subbar_height /= @data.length if stack == :side
-
- field_count = 1
- y_mod = (subbar_height / 2) + (font_size / 2)
- @config[:fields].each_index { |i|
- dataset_count = 0
- for dataset in @data
- y = @graph_height - (fieldheight * field_count)
- y += (subbar_height * dataset_count) if stack == :side
- x = (dataset[:data][i] - minvalue) * fieldwidth
-
- @graph.add_element( "path", {
- "d" => "M0 #{y} H#{x} v#{subbar_height} H0 Z",
- "class" => "fill#{dataset_count+1}"
- })
- make_datapoint_text(
- x+5, y+y_mod, dataset[:data][i], "text-anchor: start; "
- )
- dataset_count += 1
- end
- field_count += 1
- }
- end
- end
- end
-end
+require 'rexml/document'\r
+require 'SVG/Graph/BarBase'\r
+\r
+module SVG\r
+ module Graph\r
+ # === Create presentation quality SVG horitonzal bar graphs easily\r
+ # \r
+ # = Synopsis\r
+ # \r
+ # require 'SVG/Graph/BarHorizontal'\r
+ # \r
+ # fields = %w(Jan Feb Mar)\r
+ # data_sales_02 = [12, 45, 21]\r
+ # \r
+ # graph = SVG::Graph::BarHorizontal.new({\r
+ # :height => 500,\r
+ # :width => 300,\r
+ # :fields => fields,\r
+ # })\r
+ # \r
+ # graph.add_data({\r
+ # :data => data_sales_02,\r
+ # :title => 'Sales 2002',\r
+ # })\r
+ # \r
+ # print "Content-type: image/svg+xml\r\n\r\n"\r
+ # print graph.burn\r
+ # \r
+ # = Description\r
+ # \r
+ # This object aims to allow you to easily create high quality\r
+ # SVG horitonzal bar graphs. You can either use the default style sheet\r
+ # or supply your own. Either way there are many options which can\r
+ # be configured to give you control over how the graph is\r
+ # generated - with or without a key, data elements at each point,\r
+ # title, subtitle etc.\r
+ # \r
+ # = Examples\r
+ # \r
+ # * http://germane-software.com/repositories/public/SVG/test/test.rb\r
+ # \r
+ # = See also\r
+ # \r
+ # * SVG::Graph::Graph\r
+ # * SVG::Graph::Bar\r
+ # * SVG::Graph::Line\r
+ # * SVG::Graph::Pie\r
+ # * SVG::Graph::Plot\r
+ # * SVG::Graph::TimeSeries\r
+ #\r
+ # == Author\r
+ #\r
+ # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>\r
+ #\r
+ # Copyright 2004 Sean E. Russell\r
+ # This software is available under the Ruby license[LICENSE.txt]\r
+ #\r
+ class BarHorizontal < BarBase\r
+ # In addition to the defaults set in BarBase::set_defaults, sets\r
+ # [rotate_y_labels] true\r
+ # [show_x_guidelines] true\r
+ # [show_y_guidelines] false\r
+ def set_defaults\r
+ super\r
+ init_with( \r
+ :rotate_y_labels => true,\r
+ :show_x_guidelines => true,\r
+ :show_y_guidelines => false\r
+ )\r
+ self.right_align = self.right_font = 1\r
+ end\r
+ \r
+ protected\r
+\r
+ def get_x_labels\r
+ maxvalue = max_value\r
+ minvalue = min_value\r
+ range = maxvalue - minvalue\r
+ top_pad = range == 0 ? 10 : range / 20.0\r
+ scale_range = (maxvalue + top_pad) - minvalue\r
+\r
+ scale_division = scale_divisions || (scale_range / 10.0)\r
+\r
+ if scale_integers\r
+ scale_division = scale_division < 1 ? 1 : scale_division.round\r
+ end\r
+\r
+ rv = []\r
+ maxvalue = maxvalue%scale_division == 0 ? \r
+ maxvalue : maxvalue + scale_division\r
+ minvalue.step( maxvalue, scale_division ) {|v| rv << v}\r
+ return rv\r
+ end\r
+\r
+ def get_y_labels\r
+ @config[:fields]\r
+ end\r
+\r
+ def y_label_offset( height )\r
+ height / -2.0\r
+ end\r
+\r
+ def draw_data\r
+ minvalue = min_value\r
+ fieldheight = field_height\r
+\r
+ unit_size = (@graph_width.to_f - font_size*2*right_font ) /\r
+ (get_x_labels.max - get_x_labels.min )\r
+ bargap = bar_gap ? (fieldheight < 10 ? fieldheight / 2 : 10) : 0\r
+\r
+ bar_height = fieldheight - bargap\r
+ bar_height /= @data.length if stack == :side\r
+ y_mod = (bar_height / 2) + (font_size / 2)\r
+ \r
+ field_count = 1\r
+ @config[:fields].each_index { |i|\r
+ dataset_count = 0\r
+ for dataset in @data\r
+ value = dataset[:data][i]\r
+ \r
+ top = @graph_height - (fieldheight * field_count)\r
+ top += (bar_height * dataset_count) if stack == :side\r
+ # cases (assume 0 = +ve):\r
+ # value min length left\r
+ # +ve +ve value.abs - min minvalue.abs\r
+ # +ve -ve value.abs - 0 minvalue.abs\r
+ # -ve -ve value.abs - 0 minvalue.abs + value\r
+ length = (value.abs - (minvalue > 0 ? minvalue : 0)) * unit_size\r
+ left = (minvalue.abs + (value < 0 ? value : 0)) * unit_size\r
+\r
+ @graph.add_element( "rect", {\r
+ "x" => left.to_s,\r
+ "y" => top.to_s,\r
+ "width" => length.to_s,\r
+ "height" => bar_height.to_s,\r
+ "class" => "fill#{dataset_count+1}"\r
+ })\r
+\r
+ make_datapoint_text( \r
+ left+length+5, top+y_mod, value, "text-anchor: start; "\r
+ )\r
+ dataset_count += 1\r
+ end\r
+ field_count += 1\r
+ }\r
+ end\r
+ end\r
+ end\r
+end\r
-begin
- require 'zlib'
- @@__have_zlib = true
-rescue
- @@__have_zlib = false
-end
-
-require 'rexml/document'
-
-module SVG
- module Graph
- VERSION = '@ANT_VERSION@'
-
- # === Base object for generating SVG Graphs
- #
- # == Synopsis
- #
- # This class is only used as a superclass of specialized charts. Do not
- # attempt to use this class directly, unless creating a new chart type.
- #
- # For examples of how to subclass this class, see the existing specific
- # subclasses, such as SVG::Graph::Pie.
- #
- # == Examples
- #
- # For examples of how to use this package, see either the test files, or
- # the documentation for the specific class you want to use.
- #
- # * file:test/plot.rb
- # * file:test/single.rb
- # * file:test/test.rb
- # * file:test/timeseries.rb
- #
- # == Description
- #
- # This package should be used as a base for creating SVG graphs.
- #
- # == Acknowledgements
- #
- # Leo Lapworth for creating the SVG::TT::Graph package which this Ruby
- # port is based on.
- #
- # Stephen Morgan for creating the TT template and SVG.
- #
- # == See
- #
- # * SVG::Graph::BarHorizontal
- # * SVG::Graph::Bar
- # * SVG::Graph::Line
- # * SVG::Graph::Pie
- # * SVG::Graph::Plot
- # * SVG::Graph::TimeSeries
- #
- # == Author
- #
- # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
- #
- # Copyright 2004 Sean E. Russell
- # This software is available under the Ruby license[LICENSE.txt]
- #
- class Graph
- include REXML
-
- # Initialize the graph object with the graph settings. You won't
- # instantiate this class directly; see the subclass for options.
- # [width] 500
- # [height] 300
- # [show_x_guidelines] false
- # [show_y_guidelines] true
- # [show_data_values] true
- # [min_scale_value] 0
- # [show_x_labels] true
- # [stagger_x_labels] false
- # [rotate_x_labels] false
- # [step_x_labels] 1
- # [step_include_first_x_label] true
- # [show_y_labels] true
- # [rotate_y_labels] false
- # [scale_integers] false
- # [show_x_title] false
- # [x_title] 'X Field names'
- # [show_y_title] false
- # [y_title_text_direction] :bt
- # [y_title] 'Y Scale'
- # [show_graph_title] false
- # [graph_title] 'Graph Title'
- # [show_graph_subtitle] false
- # [graph_subtitle] 'Graph Sub Title'
- # [key] true,
- # [key_position] :right, # bottom or righ
- # [font_size] 12
- # [title_font_size] 16
- # [subtitle_font_size] 14
- # [x_label_font_size] 12
- # [x_title_font_size] 14
- # [y_label_font_size] 12
- # [y_title_font_size] 14
- # [key_font_size] 10
- # [no_css] false
- # [add_popups] false
- def initialize( config )
- @config = config
-
- self.top_align = self.top_font = self.right_align = self.right_font = 0
-
- init_with({
- :width => 500,
- :height => 300,
- :show_x_guidelines => false,
- :show_y_guidelines => true,
- :show_data_values => true,
-
- :min_scale_value => 0,
-
- :show_x_labels => true,
- :stagger_x_labels => false,
- :rotate_x_labels => false,
- :step_x_labels => 1,
- :step_include_first_x_label => true,
-
- :show_y_labels => true,
- :rotate_y_labels => false,
- :stagger_y_labels => false,
- :scale_integers => false,
-
- :show_x_title => false,
- :x_title => 'X Field names',
-
- :show_y_title => false,
- :y_title_text_direction => :bt,
- :y_title => 'Y Scale',
-
- :show_graph_title => false,
- :graph_title => 'Graph Title',
- :show_graph_subtitle => false,
- :graph_subtitle => 'Graph Sub Title',
- :key => true,
- :key_position => :right, # bottom or right
-
- :font_size =>10,
- :title_font_size =>12,
- :subtitle_font_size =>14,
- :x_label_font_size =>11,
- :x_title_font_size =>14,
- :y_label_font_size =>11,
- :y_title_font_size =>14,
- :key_font_size => 9,
-
- :no_css =>false,
- :add_popups =>false,
- })
-
- set_defaults if methods.include? "set_defaults"
-
- init_with config
- end
-
-
- # This method allows you do add data to the graph object.
- # It can be called several times to add more data sets in.
- #
- # data_sales_02 = [12, 45, 21];
- #
- # graph.add_data({
- # :data => data_sales_02,
- # :title => 'Sales 2002'
- # })
- def add_data conf
- @data = [] unless defined? @data
-
- if conf[:data] and conf[:data].kind_of? Array
- @data << conf
- else
- raise "No data provided by #{conf.inspect}"
- end
- end
-
-
- # This method removes all data from the object so that you can
- # reuse it to create a new graph but with the same config options.
- #
- # graph.clear_data
- def clear_data
- @data = []
- end
-
-
- # This method processes the template with the data and
- # config which has been set and returns the resulting SVG.
- #
- # This method will croak unless at least one data set has
- # been added to the graph object.
- #
- # print graph.burn
- def burn
- raise "No data available" unless @data.size > 0
-
- calculations if methods.include? 'calculations'
-
- start_svg
- calculate_graph_dimensions
- @foreground = Element.new( "g" )
- draw_graph
- draw_titles
- draw_legend
- draw_data
- @graph.add_element( @foreground )
- style
-
- data = ""
- @doc.write( data, 0 )
-
- if @config[:compress]
- if @@__have_zlib
- inp, out = IO.pipe
- gz = Zlib::GzipWriter.new( out )
- gz.write data
- gz.close
- data = inp.read
- else
- data << "<!-- Ruby Zlib not available for SVGZ -->";
- end
- end
-
- return data
- end
-
-
- # Set the height of the graph box, this is the total height
- # of the SVG box created - not the graph it self which auto
- # scales to fix the space.
- attr_accessor :height
- # Set the width of the graph box, this is the total width
- # of the SVG box created - not the graph it self which auto
- # scales to fix the space.
- attr_accessor :width
- # Set the path to an external stylesheet, set to '' if
- # you want to revert back to using the defaut internal version.
- #
- # To create an external stylesheet create a graph using the
- # default internal version and copy the stylesheet section to
- # an external file and edit from there.
- attr_accessor :style_sheet
- # (Bool) Show the value of each element of data on the graph
- attr_accessor :show_data_values
- # The point at which the Y axis starts, defaults to '0',
- # if set to nil it will default to the minimum data value.
- attr_accessor :min_scale_value
- # Whether to show labels on the X axis or not, defaults
- # to true, set to false if you want to turn them off.
- attr_accessor :show_x_labels
- # This puts the X labels at alternative levels so if they
- # are long field names they will not overlap so easily.
- # Default it false, to turn on set to true.
- attr_accessor :stagger_x_labels
- # This puts the Y labels at alternative levels so if they
- # are long field names they will not overlap so easily.
- # Default it false, to turn on set to true.
- attr_accessor :stagger_y_labels
- # This turns the X axis labels by 90 degrees.
- # Default it false, to turn on set to true.
- attr_accessor :rotate_x_labels
- # This turns the Y axis labels by 90 degrees.
- # Default it false, to turn on set to true.
- attr_accessor :rotate_y_labels
- # How many "steps" to use between displayed X axis labels,
- # a step of one means display every label, a step of two results
- # in every other label being displayed (label <gap> label <gap> label),
- # a step of three results in every third label being displayed
- # (label <gap> <gap> label <gap> <gap> label) and so on.
- attr_accessor :step_x_labels
- # Whether to (when taking "steps" between X axis labels) step from
- # the first label (i.e. always include the first label) or step from
- # the X axis origin (i.e. start with a gap if step_x_labels is greater
- # than one).
- attr_accessor :step_include_first_x_label
- # Whether to show labels on the Y axis or not, defaults
- # to true, set to false if you want to turn them off.
- attr_accessor :show_y_labels
- # Ensures only whole numbers are used as the scale divisions.
- # Default it false, to turn on set to true. This has no effect if
- # scale divisions are less than 1.
- attr_accessor :scale_integers
- # This defines the gap between markers on the Y axis,
- # default is a 10th of the max_value, e.g. you will have
- # 10 markers on the Y axis. NOTE: do not set this too
- # low - you are limited to 999 markers, after that the
- # graph won't generate.
- attr_accessor :scale_divisions
- # Whether to show the title under the X axis labels,
- # default is false, set to true to show.
- attr_accessor :show_x_title
- # What the title under X axis should be, e.g. 'Months'.
- attr_accessor :x_title
- # Whether to show the title under the Y axis labels,
- # default is false, set to true to show.
- attr_accessor :show_y_title
- # Aligns writing mode for Y axis label.
- # Defaults to :bt (Bottom to Top).
- # Change to :tb (Top to Bottom) to reverse.
- attr_accessor :y_title_text_direction
- # What the title under Y axis should be, e.g. 'Sales in thousands'.
- attr_accessor :y_title
- # Whether to show a title on the graph, defaults
- # to false, set to true to show.
- attr_accessor :show_graph_title
- # What the title on the graph should be.
- attr_accessor :graph_title
- # Whether to show a subtitle on the graph, defaults
- # to false, set to true to show.
- attr_accessor :show_graph_subtitle
- # What the subtitle on the graph should be.
- attr_accessor :graph_subtitle
- # Whether to show a key, defaults to false, set to
- # true if you want to show it.
- attr_accessor :key
- # Where the key should be positioned, defaults to
- # :right, set to :bottom if you want to move it.
- attr_accessor :key_position
- # Set the font size (in points) of the data point labels
- attr_accessor :font_size
- # Set the font size of the X axis labels
- attr_accessor :x_label_font_size
- # Set the font size of the X axis title
- attr_accessor :x_title_font_size
- # Set the font size of the Y axis labels
- attr_accessor :y_label_font_size
- # Set the font size of the Y axis title
- attr_accessor :y_title_font_size
- # Set the title font size
- attr_accessor :title_font_size
- # Set the subtitle font size
- attr_accessor :subtitle_font_size
- # Set the key font size
- attr_accessor :key_font_size
- # Show guidelines for the X axis
- attr_accessor :show_x_guidelines
- # Show guidelines for the Y axis
- attr_accessor :show_y_guidelines
- # Do not use CSS if set to true. Many SVG viewers do not support CSS, but
- # not using CSS can result in larger SVGs as well as making it impossible to
- # change colors after the chart is generated. Defaults to false.
- attr_accessor :no_css
- # Add popups for the data points on some graphs
- attr_accessor :add_popups
-
-
- protected
-
- def sort( *arrys )
- sort_multiple( arrys )
- end
-
- # Overwrite configuration options with supplied options. Used
- # by subclasses.
- def init_with config
- config.each { |key, value|
- self.send( key.to_s+"=", value ) if methods.include? key.to_s
- }
- end
-
- attr_accessor :top_align, :top_font, :right_align, :right_font
-
- KEY_BOX_SIZE = 12
-
- # Override this (and call super) to change the margin to the left
- # of the plot area. Results in @border_left being set.
- def calculate_left_margin
- @border_left = 7
- # Check for Y labels
- max_y_label_height_px = rotate_y_labels ?
- y_label_font_size :
- get_y_labels.max{|a,b|
- a.to_s.length<=>b.to_s.length
- }.to_s.length * y_label_font_size * 0.6
- @border_left += max_y_label_height_px if show_y_labels
- @border_left += max_y_label_height_px + 10 if stagger_y_labels
- @border_left += y_title_font_size + 5 if show_y_title
- end
-
-
- # Calculates the width of the widest Y label. This will be the
- # character height if the Y labels are rotated
- def max_y_label_width_px
- return font_size if rotate_y_labels
- end
-
-
- # Override this (and call super) to change the margin to the right
- # of the plot area. Results in @border_right being set.
- def calculate_right_margin
- @border_right = 7
- if key and key_position == :right
- val = keys.max { |a,b| a.length <=> b.length }
- @border_right += val.length * key_font_size * 0.7
- @border_right += KEY_BOX_SIZE
- @border_right += 10 # Some padding around the box
- end
- end
-
-
- # Override this (and call super) to change the margin to the top
- # of the plot area. Results in @border_top being set.
- def calculate_top_margin
- @border_top = 5
- @border_top += title_font_size if show_graph_title
- @border_top += 5
- @border_top += subtitle_font_size if show_graph_subtitle
- end
-
-
- # Adds pop-up point information to a graph.
- def add_popup( x, y, label )
- txt_width = label.length * font_size * 0.6 + 10
- tx = (x+txt_width > width ? x-5 : x+5)
- t = @foreground.add_element( "text", {
- "x" => tx.to_s,
- "y" => (y - font_size).to_s,
- "visibility" => "hidden",
- })
- t.attributes["style"] = "fill: #000; "+
- (x+txt_width > width ? "text-anchor: end;" : "text-anchor: start;")
- t.text = label.to_s
- t.attributes["id"] = t.id.to_s
-
- @foreground.add_element( "circle", {
- "cx" => x.to_s,
- "cy" => y.to_s,
- "r" => "10",
- "style" => "opacity: 0",
- "onmouseover" =>
- "document.getElementById(#{t.id}).setAttribute('visibility', 'visible' )",
- "onmouseout" =>
- "document.getElementById(#{t.id}).setAttribute('visibility', 'hidden' )",
- })
-
- end
-
-
- # Override this (and call super) to change the margin to the bottom
- # of the plot area. Results in @border_bottom being set.
- def calculate_bottom_margin
- @border_bottom = 7
- if key and key_position == :bottom
- @border_bottom += @data.size * (font_size + 5)
- @border_bottom += 10
- end
- if show_x_labels
- max_x_label_height_px = rotate_x_labels ?
- get_x_labels.max{|a,b|
- a.length<=>b.length
- }.length * x_label_font_size * 0.6 :
- x_label_font_size
- @border_bottom += max_x_label_height_px
- @border_bottom += max_x_label_height_px + 10 if stagger_x_labels
- end
- @border_bottom += x_title_font_size + 5 if show_x_title
- end
-
-
- # Draws the background, axis, and labels.
- def draw_graph
- @graph = @root.add_element( "g", {
- "transform" => "translate( #@border_left #@border_top )"
- })
-
- # Background
- @graph.add_element( "rect", {
- "x" => "0",
- "y" => "0",
- "width" => @graph_width.to_s,
- "height" => @graph_height.to_s,
- "class" => "graphBackground"
- })
-
- # Axis
- @graph.add_element( "path", {
- "d" => "M 0 0 v#@graph_height",
- "class" => "axis",
- "id" => "xAxis"
- })
- @graph.add_element( "path", {
- "d" => "M 0 #@graph_height h#@graph_width",
- "class" => "axis",
- "id" => "yAxis"
- })
-
- draw_x_labels
- draw_y_labels
- end
-
-
- # Where in the X area the label is drawn
- # Centered in the field, should be width/2. Start, 0.
- def x_label_offset( width )
- 0
- end
-
- def make_datapoint_text( x, y, value, style="" )
- if show_data_values
- @foreground.add_element( "text", {
- "x" => x.to_s,
- "y" => y.to_s,
- "class" => "dataPointLabel",
- "style" => "#{style} stroke: #fff; stroke-width: 2;"
- }).text = value.to_s
- text = @foreground.add_element( "text", {
- "x" => x.to_s,
- "y" => y.to_s,
- "class" => "dataPointLabel"
- })
- text.text = value.to_s
- text.attributes["style"] = style if style.length > 0
- end
- end
-
-
- # Draws the X axis labels
- def draw_x_labels
- stagger = x_label_font_size + 5
- if show_x_labels
- label_width = field_width
-
- count = 0
- for label in get_x_labels
- if step_include_first_x_label == true then
- step = count % step_x_labels
- else
- step = (count + 1) % step_x_labels
- end
-
- if step == 0 then
- text = @graph.add_element( "text" )
- text.attributes["class"] = "xAxisLabels"
- text.text = label.to_s
-
- x = count * label_width + x_label_offset( label_width )
- y = @graph_height + x_label_font_size + 3
- t = 0 - (font_size / 2)
-
- if stagger_x_labels and count % 2 == 1
- y += stagger
- @graph.add_element( "path", {
- "d" => "M#{x} #@graph_height v#{stagger}",
- "class" => "staggerGuideLine"
- })
- end
-
- text.attributes["x"] = x.to_s
- text.attributes["y"] = y.to_s
- if rotate_x_labels
- text.attributes["transform"] =
- "rotate( 90 #{x} #{y-x_label_font_size} )"+
- " translate( 0 -#{x_label_font_size/4} )"
- text.attributes["style"] = "text-anchor: start"
- else
- text.attributes["style"] = "text-anchor: middle"
- end
- end
-
- draw_x_guidelines( label_width, count ) if show_x_guidelines
- count += 1
- end
- end
- end
-
-
- # Where in the Y area the label is drawn
- # Centered in the field, should be width/2. Start, 0.
- def y_label_offset( height )
- 0
- end
-
-
- def field_width
- (@graph_width.to_f - font_size*2*right_font) /
- (get_x_labels.length - right_align)
- end
-
-
- def field_height
- (@graph_height.to_f - font_size*2*top_font) /
- (get_y_labels.length - top_align)
- end
-
-
- # Draws the Y axis labels
- def draw_y_labels
- stagger = y_label_font_size + 5
- if show_y_labels
- label_height = field_height
-
- count = 0
- y_offset = @graph_height + y_label_offset( label_height )
- y_offset += font_size/1.2 unless rotate_y_labels
- for label in get_y_labels
- y = y_offset - (label_height * count)
- x = rotate_y_labels ? 0 : -3
-
- if stagger_y_labels and count % 2 == 1
- x -= stagger
- @graph.add_element( "path", {
- "d" => "M#{x} #{y} h#{stagger}",
- "class" => "staggerGuideLine"
- })
- end
-
- text = @graph.add_element( "text", {
- "x" => x.to_s,
- "y" => y.to_s,
- "class" => "yAxisLabels"
- })
- text.text = label.to_s
- if rotate_y_labels
- text.attributes["transform"] = "translate( -#{font_size} 0 ) "+
- "rotate( 90 #{x} #{y} ) "
- text.attributes["style"] = "text-anchor: middle"
- else
- text.attributes["y"] = (y - (y_label_font_size/2)).to_s
- text.attributes["style"] = "text-anchor: end"
- end
- draw_y_guidelines( label_height, count ) if show_y_guidelines
- count += 1
- end
- end
- end
-
-
- # Draws the X axis guidelines
- def draw_x_guidelines( label_height, count )
- if count != 0
- @graph.add_element( "path", {
- "d" => "M#{label_height*count} 0 v#@graph_height",
- "class" => "guideLines"
- })
- end
- end
-
-
- # Draws the Y axis guidelines
- def draw_y_guidelines( label_height, count )
- if count != 0
- @graph.add_element( "path", {
- "d" => "M0 #{@graph_height-(label_height*count)} h#@graph_width",
- "class" => "guideLines"
- })
- end
- end
-
-
- # Draws the graph title and subtitle
- def draw_titles
- if show_graph_title
- @root.add_element( "text", {
- "x" => (width / 2).to_s,
- "y" => (title_font_size).to_s,
- "class" => "mainTitle"
- }).text = graph_title.to_s
- end
-
- if show_graph_subtitle
- y_subtitle = show_graph_title ?
- title_font_size + 10 :
- subtitle_font_size
- @root.add_element("text", {
- "x" => (width / 2).to_s,
- "y" => (y_subtitle).to_s,
- "class" => "subTitle"
- }).text = graph_subtitle.to_s
- end
-
- if show_x_title
- y = @graph_height + @border_top + x_title_font_size
- if show_x_labels
- y += x_label_font_size + 5 if stagger_x_labels
- y += x_label_font_size + 5
- end
- x = width / 2
-
- @root.add_element("text", {
- "x" => x.to_s,
- "y" => y.to_s,
- "class" => "xAxisTitle",
- }).text = x_title.to_s
- end
-
- if show_y_title
- x = y_title_font_size + (y_title_text_direction==:bt ? 3 : -3)
- y = height / 2
-
- text = @root.add_element("text", {
- "x" => x.to_s,
- "y" => y.to_s,
- "class" => "yAxisTitle",
- })
- text.text = y_title.to_s
- if y_title_text_direction == :bt
- text.attributes["transform"] = "rotate( -90, #{x}, #{y} )"
- else
- text.attributes["transform"] = "rotate( 90, #{x}, #{y} )"
- end
- end
- end
-
- def keys
- return @data.collect{ |d| d[:title] }
- end
-
- # Draws the legend on the graph
- def draw_legend
- if key
- group = @root.add_element( "g" )
-
- key_count = 0
- for key_name in keys
- y_offset = (KEY_BOX_SIZE * key_count) + (key_count * 5)
- group.add_element( "rect", {
- "x" => 0.to_s,
- "y" => y_offset.to_s,
- "width" => KEY_BOX_SIZE.to_s,
- "height" => KEY_BOX_SIZE.to_s,
- "class" => "key#{key_count+1}"
- })
- group.add_element( "text", {
- "x" => (KEY_BOX_SIZE + 5).to_s,
- "y" => (y_offset + KEY_BOX_SIZE - 2).to_s,
- "class" => "keyText"
- }).text = key_name.to_s
- key_count += 1
- end
-
- case key_position
- when :right
- x_offset = @graph_width + @border_left + 10
- y_offset = @border_top + 20
- when :bottom
- x_offset = @border_left + 20
- y_offset = @border_top + @graph_height + 5
- if show_x_labels
- max_x_label_height_px = rotate_x_labels ?
- get_x_labels.max{|a,b|
- a.length<=>b.length
- }.length * x_label_font_size :
- x_label_font_size
- y_offset += max_x_label_height_px
- y_offset += max_x_label_height_px + 5 if stagger_x_labels
- end
- y_offset += x_title_font_size + 5 if show_x_title
- end
- group.attributes["transform"] = "translate(#{x_offset} #{y_offset})"
- end
- end
-
-
- private
-
- def sort_multiple( arrys, lo=0, hi=arrys[0].length-1 )
- if lo < hi
- p = partition(arrys,lo,hi)
- sort_multiple(arrys, lo, p-1)
- sort_multiple(arrys, p+1, hi)
- end
- arrys
- end
-
- def partition( arrys, lo, hi )
- p = arrys[0][lo]
- l = lo
- z = lo+1
- while z <= hi
- if arrys[0][z] < p
- l += 1
- arrys.each { |arry| arry[z], arry[l] = arry[l], arry[z] }
- end
- z += 1
- end
- arrys.each { |arry| arry[lo], arry[l] = arry[l], arry[lo] }
- l
- end
-
- def style
- if no_css
- styles = parse_css
- @root.elements.each("//*[@class]") { |el|
- cl = el.attributes["class"]
- style = styles[cl]
- style += el.attributes["style"] if el.attributes["style"]
- el.attributes["style"] = style
- }
- end
- end
-
- def parse_css
- css = get_style
- rv = {}
- while css =~ /^(\.(\w+)(?:\s*,\s*\.\w+)*)\s*\{/m
- names_orig = names = $1
- css = $'
- css =~ /([^}]+)\}/m
- content = $1
- css = $'
-
- nms = []
- while names =~ /^\s*,?\s*\.(\w+)/
- nms << $1
- names = $'
- end
-
- content = content.tr( "\n\t", " ")
- for name in nms
- current = rv[name]
- current = current ? current+"; "+content : content
- rv[name] = current.strip.squeeze(" ")
- end
- end
- return rv
- end
-
-
- # Override and place code to add defs here
- def add_defs defs
- end
-
-
- def start_svg
- # Base document
- @doc = Document.new
- @doc << XMLDecl.new
- @doc << DocType.new( %q{svg PUBLIC "-//W3C//DTD SVG 1.0//EN" } +
- %q{"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"} )
- if style_sheet && style_sheet != ''
- @doc << Instruction.new( "xml-stylesheet",
- %Q{href="#{style_sheet}" type="text/css"} )
- end
- @root = @doc.add_element( "svg", {
- "width" => width.to_s,
- "height" => height.to_s,
- "viewBox" => "0 0 #{width} #{height}",
- "xmlns" => "http://www.w3.org/2000/svg",
- "xmlns:xlink" => "http://www.w3.org/1999/xlink",
- "xmlns:a3" => "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/",
- "a3:scriptImplementation" => "Adobe"
- })
- @root << Comment.new( " "+"\\"*66 )
- @root << Comment.new( " Created with SVG::Graph " )
- @root << Comment.new( " SVG::Graph by Sean E. Russell " )
- @root << Comment.new( " Losely based on SVG::TT::Graph for Perl by"+
- " Leo Lapworth & Stephan Morgan " )
- @root << Comment.new( " "+"/"*66 )
-
- defs = @root.add_element( "defs" )
- add_defs defs
- if not(style_sheet && style_sheet != '') and !no_css
- @root << Comment.new(" include default stylesheet if none specified ")
- style = defs.add_element( "style", {"type"=>"text/css"} )
- style << CData.new( get_style )
- end
-
- @root << Comment.new( "SVG Background" )
- @root.add_element( "rect", {
- "width" => width.to_s,
- "height" => height.to_s,
- "x" => "0",
- "y" => "0",
- "class" => "svgBackground"
- })
- end
-
-
- def calculate_graph_dimensions
- calculate_left_margin
- calculate_right_margin
- calculate_bottom_margin
- calculate_top_margin
- @graph_width = width - @border_left - @border_right
- @graph_height = height - @border_top - @border_bottom
- end
-
- def get_style
- return <<EOL
-/* Copy from here for external style sheet */
-.svgBackground{
- fill:#ffffff;
-}
-.graphBackground{
- fill:#f5f5f5;
-}
-
-/* graphs titles */
-.mainTitle{
- text-anchor: middle;
- fill: #555555;
- font-size: #{title_font_size}px;
- font-family: "Verdana", sans-serif;
- font-weight: bold;
-}
-.subTitle{
- text-anchor: middle;
- fill: #999999;
- font-size: #{subtitle_font_size}px;
- font-family: "Verdana", sans-serif;
- font-weight: normal;
-}
-
-.axis{
- stroke: #666666;
- stroke-width: 1px;
-}
-
-.guideLines{
- stroke: #666666;
- stroke-width: 1px;
- stroke-dasharray:2,2,2;
-}
-
-.xAxisLabels{
- text-anchor: middle;
- fill: #000000;
- font-size: #{x_label_font_size}px;
- font-family: "Verdana", sans-serif;
- font-weight: normal;
-}
-
-.yAxisLabels{
- text-anchor: end;
- fill: #000000;
- font-size: #{y_label_font_size}px;
- font-family: "Verdana", sans-serif;
- font-weight: normal;
-}
-
-.xAxisTitle{
- text-anchor: middle;
- fill: #ff0000;
- font-size: #{x_title_font_size}px;
- font-family: "Verdana", sans-serif;
- font-weight: normal;
-}
-
-.yAxisTitle{
- fill: #ff0000;
- text-anchor: middle;
- font-size: #{y_title_font_size}px;
- font-family: "Verdana", sans-serif;
- font-weight: normal;
-}
-
-.dataPointLabel{
- fill: #000000;
- text-anchor:middle;
- font-size: 10px;
- font-family: "Verdana", sans-serif;
- font-weight: normal;
-}
-
-.staggerGuideLine{
- fill: none;
- stroke: #000000;
- stroke-width: 0.5px;
-}
-
-#{get_css}
-
-.keyText{
- fill: #000000;
- text-anchor:start;
- font-size: #{key_font_size}px;
- font-family: "Verdana", sans-serif;
- font-weight: normal;
-}
-/* End copy for external style sheet */
-EOL
- end
-
- end
- end
-end
+begin\r
+ require 'zlib'\r
+ @@__have_zlib = true\r
+rescue\r
+ @@__have_zlib = false\r
+end\r
+\r
+require 'rexml/document'\r
+\r
+module SVG\r
+ module Graph\r
+ VERSION = '@ANT_VERSION@'\r
+\r
+ # === Base object for generating SVG Graphs\r
+ # \r
+ # == Synopsis\r
+ #\r
+ # This class is only used as a superclass of specialized charts. Do not\r
+ # attempt to use this class directly, unless creating a new chart type.\r
+ #\r
+ # For examples of how to subclass this class, see the existing specific\r
+ # subclasses, such as SVG::Graph::Pie.\r
+ #\r
+ # == Examples\r
+ #\r
+ # For examples of how to use this package, see either the test files, or\r
+ # the documentation for the specific class you want to use.\r
+ #\r
+ # * file:test/plot.rb\r
+ # * file:test/single.rb\r
+ # * file:test/test.rb\r
+ # * file:test/timeseries.rb\r
+ # \r
+ # == Description\r
+ # \r
+ # This package should be used as a base for creating SVG graphs.\r
+ #\r
+ # == Acknowledgements\r
+ #\r
+ # Leo Lapworth for creating the SVG::TT::Graph package which this Ruby\r
+ # port is based on.\r
+ #\r
+ # Stephen Morgan for creating the TT template and SVG.\r
+ # \r
+ # == See\r
+ #\r
+ # * SVG::Graph::BarHorizontal\r
+ # * SVG::Graph::Bar\r
+ # * SVG::Graph::Line\r
+ # * SVG::Graph::Pie\r
+ # * SVG::Graph::Plot\r
+ # * SVG::Graph::TimeSeries\r
+ #\r
+ # == Author\r
+ #\r
+ # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>\r
+ #\r
+ # Copyright 2004 Sean E. Russell\r
+ # This software is available under the Ruby license[LICENSE.txt]\r
+ #\r
+ class Graph\r
+ include REXML\r
+\r
+ # Initialize the graph object with the graph settings. You won't\r
+ # instantiate this class directly; see the subclass for options.\r
+ # [width] 500\r
+ # [height] 300\r
+ # [show_x_guidelines] false\r
+ # [show_y_guidelines] true\r
+ # [show_data_values] true\r
+ # [min_scale_value] 0\r
+ # [show_x_labels] true\r
+ # [stagger_x_labels] false\r
+ # [rotate_x_labels] false\r
+ # [step_x_labels] 1\r
+ # [step_include_first_x_label] true\r
+ # [show_y_labels] true\r
+ # [rotate_y_labels] false\r
+ # [scale_integers] false\r
+ # [show_x_title] false\r
+ # [x_title] 'X Field names'\r
+ # [show_y_title] false\r
+ # [y_title_text_direction] :bt\r
+ # [y_title] 'Y Scale'\r
+ # [show_graph_title] false\r
+ # [graph_title] 'Graph Title'\r
+ # [show_graph_subtitle] false\r
+ # [graph_subtitle] 'Graph Sub Title'\r
+ # [key] true,\r
+ # [key_position] :right, # bottom or righ\r
+ # [font_size] 12\r
+ # [title_font_size] 16\r
+ # [subtitle_font_size] 14\r
+ # [x_label_font_size] 12\r
+ # [x_title_font_size] 14\r
+ # [y_label_font_size] 12\r
+ # [y_title_font_size] 14\r
+ # [key_font_size] 10\r
+ # [no_css] false\r
+ # [add_popups] false\r
+ def initialize( config )\r
+ @config = config\r
+\r
+ self.top_align = self.top_font = self.right_align = self.right_font = 0\r
+\r
+ init_with({\r
+ :width => 500,\r
+ :height => 300,\r
+ :show_x_guidelines => false,\r
+ :show_y_guidelines => true,\r
+ :show_data_values => true,\r
+\r
+# :min_scale_value => 0,\r
+\r
+ :show_x_labels => true,\r
+ :stagger_x_labels => false,\r
+ :rotate_x_labels => false,\r
+ :step_x_labels => 1,\r
+ :step_include_first_x_label => true,\r
+\r
+ :show_y_labels => true,\r
+ :rotate_y_labels => false,\r
+ :stagger_y_labels => false,\r
+ :scale_integers => false,\r
+\r
+ :show_x_title => false,\r
+ :x_title => 'X Field names',\r
+\r
+ :show_y_title => false,\r
+ :y_title_text_direction => :bt,\r
+ :y_title => 'Y Scale',\r
+\r
+ :show_graph_title => false,\r
+ :graph_title => 'Graph Title',\r
+ :show_graph_subtitle => false,\r
+ :graph_subtitle => 'Graph Sub Title',\r
+ :key => true, \r
+ :key_position => :right, # bottom or right\r
+\r
+ :font_size =>12,\r
+ :title_font_size =>16,\r
+ :subtitle_font_size =>14,\r
+ :x_label_font_size =>12,\r
+ :x_title_font_size =>14,\r
+ :y_label_font_size =>12,\r
+ :y_title_font_size =>14,\r
+ :key_font_size =>10,\r
+ \r
+ :no_css =>false,\r
+ :add_popups =>false,\r
+ })\r
+\r
+ set_defaults if methods.include? "set_defaults"\r
+\r
+ init_with config\r
+ end\r
+\r
+ \r
+ # This method allows you do add data to the graph object.\r
+ # It can be called several times to add more data sets in.\r
+ #\r
+ # data_sales_02 = [12, 45, 21];\r
+ # \r
+ # graph.add_data({\r
+ # :data => data_sales_02,\r
+ # :title => 'Sales 2002'\r
+ # })\r
+ def add_data conf\r
+ @data = [] unless defined? @data\r
+\r
+ if conf[:data] and conf[:data].kind_of? Array\r
+ @data << conf\r
+ else\r
+ raise "No data provided by #{conf.inspect}"\r
+ end\r
+ end\r
+\r
+\r
+ # This method removes all data from the object so that you can\r
+ # reuse it to create a new graph but with the same config options.\r
+ #\r
+ # graph.clear_data\r
+ def clear_data \r
+ @data = []\r
+ end\r
+\r
+\r
+ # This method processes the template with the data and\r
+ # config which has been set and returns the resulting SVG.\r
+ #\r
+ # This method will croak unless at least one data set has\r
+ # been added to the graph object.\r
+ #\r
+ # print graph.burn\r
+ def burn\r
+ raise "No data available" unless @data.size > 0\r
+ \r
+ calculations if methods.include? 'calculations'\r
+\r
+ start_svg\r
+ calculate_graph_dimensions\r
+ @foreground = Element.new( "g" )\r
+ draw_graph\r
+ draw_titles\r
+ draw_legend\r
+ draw_data\r
+ @graph.add_element( @foreground )\r
+ style\r
+\r
+ data = ""\r
+ @doc.write( data, 0 )\r
+\r
+ if @config[:compress]\r
+ if @@__have_zlib\r
+ inp, out = IO.pipe\r
+ gz = Zlib::GzipWriter.new( out )\r
+ gz.write data\r
+ gz.close\r
+ data = inp.read\r
+ else\r
+ data << "<!-- Ruby Zlib not available for SVGZ -->";\r
+ end\r
+ end\r
+ \r
+ return data\r
+ end\r
+\r
+\r
+ # Set the height of the graph box, this is the total height\r
+ # of the SVG box created - not the graph it self which auto\r
+ # scales to fix the space.\r
+ attr_accessor :height\r
+ # Set the width of the graph box, this is the total width\r
+ # of the SVG box created - not the graph it self which auto\r
+ # scales to fix the space.\r
+ attr_accessor :width\r
+ # Set the path to an external stylesheet, set to '' if\r
+ # you want to revert back to using the defaut internal version.\r
+ #\r
+ # To create an external stylesheet create a graph using the\r
+ # default internal version and copy the stylesheet section to\r
+ # an external file and edit from there.\r
+ attr_accessor :style_sheet\r
+ # (Bool) Show the value of each element of data on the graph\r
+ attr_accessor :show_data_values\r
+ # The point at which the Y axis starts, defaults to '0',\r
+ # if set to nil it will default to the minimum data value.\r
+ attr_accessor :min_scale_value\r
+ # Whether to show labels on the X axis or not, defaults\r
+ # to true, set to false if you want to turn them off.\r
+ attr_accessor :show_x_labels\r
+ # This puts the X labels at alternative levels so if they\r
+ # are long field names they will not overlap so easily.\r
+ # Default it false, to turn on set to true.\r
+ attr_accessor :stagger_x_labels\r
+ # This puts the Y labels at alternative levels so if they\r
+ # are long field names they will not overlap so easily.\r
+ # Default it false, to turn on set to true.\r
+ attr_accessor :stagger_y_labels\r
+ # This turns the X axis labels by 90 degrees.\r
+ # Default it false, to turn on set to true.\r
+ attr_accessor :rotate_x_labels\r
+ # This turns the Y axis labels by 90 degrees.\r
+ # Default it false, to turn on set to true.\r
+ attr_accessor :rotate_y_labels\r
+ # How many "steps" to use between displayed X axis labels,\r
+ # a step of one means display every label, a step of two results\r
+ # in every other label being displayed (label <gap> label <gap> label),\r
+ # a step of three results in every third label being displayed\r
+ # (label <gap> <gap> label <gap> <gap> label) and so on.\r
+ attr_accessor :step_x_labels\r
+ # Whether to (when taking "steps" between X axis labels) step from \r
+ # the first label (i.e. always include the first label) or step from\r
+ # the X axis origin (i.e. start with a gap if step_x_labels is greater\r
+ # than one).\r
+ attr_accessor :step_include_first_x_label\r
+ # Whether to show labels on the Y axis or not, defaults\r
+ # to true, set to false if you want to turn them off.\r
+ attr_accessor :show_y_labels\r
+ # Ensures only whole numbers are used as the scale divisions.\r
+ # Default it false, to turn on set to true. This has no effect if \r
+ # scale divisions are less than 1.\r
+ attr_accessor :scale_integers\r
+ # This defines the gap between markers on the Y axis,\r
+ # default is a 10th of the max_value, e.g. you will have\r
+ # 10 markers on the Y axis. NOTE: do not set this too\r
+ # low - you are limited to 999 markers, after that the\r
+ # graph won't generate.\r
+ attr_accessor :scale_divisions\r
+ # Whether to show the title under the X axis labels,\r
+ # default is false, set to true to show.\r
+ attr_accessor :show_x_title\r
+ # What the title under X axis should be, e.g. 'Months'.\r
+ attr_accessor :x_title\r
+ # Whether to show the title under the Y axis labels,\r
+ # default is false, set to true to show.\r
+ attr_accessor :show_y_title\r
+ # Aligns writing mode for Y axis label. \r
+ # Defaults to :bt (Bottom to Top).\r
+ # Change to :tb (Top to Bottom) to reverse.\r
+ attr_accessor :y_title_text_direction\r
+ # What the title under Y axis should be, e.g. 'Sales in thousands'.\r
+ attr_accessor :y_title\r
+ # Whether to show a title on the graph, defaults\r
+ # to false, set to true to show.\r
+ attr_accessor :show_graph_title\r
+ # What the title on the graph should be.\r
+ attr_accessor :graph_title\r
+ # Whether to show a subtitle on the graph, defaults\r
+ # to false, set to true to show.\r
+ attr_accessor :show_graph_subtitle\r
+ # What the subtitle on the graph should be.\r
+ attr_accessor :graph_subtitle\r
+ # Whether to show a key, defaults to false, set to\r
+ # true if you want to show it.\r
+ attr_accessor :key\r
+ # Where the key should be positioned, defaults to\r
+ # :right, set to :bottom if you want to move it.\r
+ attr_accessor :key_position\r
+ # Set the font size (in points) of the data point labels\r
+ attr_accessor :font_size\r
+ # Set the font size of the X axis labels\r
+ attr_accessor :x_label_font_size\r
+ # Set the font size of the X axis title\r
+ attr_accessor :x_title_font_size\r
+ # Set the font size of the Y axis labels\r
+ attr_accessor :y_label_font_size\r
+ # Set the font size of the Y axis title\r
+ attr_accessor :y_title_font_size\r
+ # Set the title font size\r
+ attr_accessor :title_font_size\r
+ # Set the subtitle font size\r
+ attr_accessor :subtitle_font_size\r
+ # Set the key font size\r
+ attr_accessor :key_font_size\r
+ # Show guidelines for the X axis\r
+ attr_accessor :show_x_guidelines\r
+ # Show guidelines for the Y axis\r
+ attr_accessor :show_y_guidelines\r
+ # Do not use CSS if set to true. Many SVG viewers do not support CSS, but\r
+ # not using CSS can result in larger SVGs as well as making it impossible to\r
+ # change colors after the chart is generated. Defaults to false.\r
+ attr_accessor :no_css\r
+ # Add popups for the data points on some graphs\r
+ attr_accessor :add_popups\r
+\r
+\r
+ protected\r
+\r
+ def sort( *arrys )\r
+ sort_multiple( arrys )\r
+ end\r
+\r
+ # Overwrite configuration options with supplied options. Used\r
+ # by subclasses.\r
+ def init_with config\r
+ config.each { |key, value|\r
+ self.send( key.to_s+"=", value ) if methods.include? key.to_s\r
+ }\r
+ end\r
+\r
+ attr_accessor :top_align, :top_font, :right_align, :right_font\r
+\r
+ KEY_BOX_SIZE = 12\r
+\r
+ # Override this (and call super) to change the margin to the left\r
+ # of the plot area. Results in @border_left being set.\r
+ def calculate_left_margin\r
+ @border_left = 7\r
+ # Check for Y labels\r
+ max_y_label_height_px = rotate_y_labels ? \r
+ y_label_font_size :\r
+ get_y_labels.max{|a,b| \r
+ a.to_s.length<=>b.to_s.length\r
+ }.to_s.length * y_label_font_size * 0.6\r
+ @border_left += max_y_label_height_px if show_y_labels\r
+ @border_left += max_y_label_height_px + 10 if stagger_y_labels\r
+ @border_left += y_title_font_size + 5 if show_y_title\r
+ end\r
+\r
+\r
+ # Calculates the width of the widest Y label. This will be the\r
+ # character height if the Y labels are rotated\r
+ def max_y_label_width_px\r
+ return font_size if rotate_y_labels\r
+ end\r
+\r
+\r
+ # Override this (and call super) to change the margin to the right\r
+ # of the plot area. Results in @border_right being set.\r
+ def calculate_right_margin\r
+ @border_right = 7\r
+ if key and key_position == :right\r
+ val = keys.max { |a,b| a.length <=> b.length }\r
+ @border_right += val.length * key_font_size * 0.6 \r
+ @border_right += KEY_BOX_SIZE\r
+ @border_right += 10 # Some padding around the box\r
+ end\r
+ end\r
+\r
+\r
+ # Override this (and call super) to change the margin to the top\r
+ # of the plot area. Results in @border_top being set.\r
+ def calculate_top_margin\r
+ @border_top = 5\r
+ @border_top += title_font_size if show_graph_title\r
+ @border_top += 5\r
+ @border_top += subtitle_font_size if show_graph_subtitle\r
+ end\r
+\r
+\r
+ # Adds pop-up point information to a graph.\r
+ def add_popup( x, y, label )\r
+ txt_width = label.length * font_size * 0.6 + 10\r
+ tx = (x+txt_width > width ? x-5 : x+5)\r
+ t = @foreground.add_element( "text", {\r
+ "x" => tx.to_s,\r
+ "y" => (y - font_size).to_s,\r
+ "visibility" => "hidden",\r
+ })\r
+ t.attributes["style"] = "fill: #000; "+\r
+ (x+txt_width > width ? "text-anchor: end;" : "text-anchor: start;")\r
+ t.text = label.to_s\r
+ t.attributes["id"] = t.object_id.to_s\r
+\r
+ @foreground.add_element( "circle", {\r
+ "cx" => x.to_s,\r
+ "cy" => y.to_s,\r
+ "r" => "10",\r
+ "style" => "opacity: 0",\r
+ "onmouseover" => \r
+ "document.getElementById(#{t.object_id}).setAttribute('visibility', 'visible' )",\r
+ "onmouseout" => \r
+ "document.getElementById(#{t.object_id}).setAttribute('visibility', 'hidden' )",\r
+ })\r
+\r
+ end\r
+\r
+ \r
+ # Override this (and call super) to change the margin to the bottom\r
+ # of the plot area. Results in @border_bottom being set.\r
+ def calculate_bottom_margin\r
+ @border_bottom = 7\r
+ if key and key_position == :bottom\r
+ @border_bottom += @data.size * (font_size + 5)\r
+ @border_bottom += 10\r
+ end\r
+ if show_x_labels\r
+ max_x_label_height_px = (not rotate_x_labels) ? \r
+ x_label_font_size :\r
+ get_x_labels.max{|a,b| \r
+ a.to_s.length<=>b.to_s.length\r
+ }.to_s.length * x_label_font_size * 0.6\r
+ @border_bottom += max_x_label_height_px\r
+ @border_bottom += max_x_label_height_px + 10 if stagger_x_labels\r
+ end\r
+ @border_bottom += x_title_font_size + 5 if show_x_title\r
+ end\r
+\r
+\r
+ # Draws the background, axis, and labels.\r
+ def draw_graph\r
+ @graph = @root.add_element( "g", {\r
+ "transform" => "translate( #@border_left #@border_top )"\r
+ })\r
+\r
+ # Background\r
+ @graph.add_element( "rect", {\r
+ "x" => "0",\r
+ "y" => "0",\r
+ "width" => @graph_width.to_s,\r
+ "height" => @graph_height.to_s,\r
+ "class" => "graphBackground"\r
+ })\r
+\r
+ # Axis\r
+ @graph.add_element( "path", {\r
+ "d" => "M 0 0 v#@graph_height",\r
+ "class" => "axis",\r
+ "id" => "xAxis"\r
+ })\r
+ @graph.add_element( "path", {\r
+ "d" => "M 0 #@graph_height h#@graph_width",\r
+ "class" => "axis",\r
+ "id" => "yAxis"\r
+ })\r
+\r
+ draw_x_labels\r
+ draw_y_labels\r
+ end\r
+\r
+\r
+ # Where in the X area the label is drawn\r
+ # Centered in the field, should be width/2. Start, 0.\r
+ def x_label_offset( width )\r
+ 0\r
+ end\r
+\r
+ def make_datapoint_text( x, y, value, style="" )\r
+ if show_data_values\r
+ @foreground.add_element( "text", {\r
+ "x" => x.to_s,\r
+ "y" => y.to_s,\r
+ "class" => "dataPointLabel",\r
+ "style" => "#{style} stroke: #fff; stroke-width: 2;"\r
+ }).text = value.to_s\r
+ text = @foreground.add_element( "text", {\r
+ "x" => x.to_s,\r
+ "y" => y.to_s,\r
+ "class" => "dataPointLabel"\r
+ })\r
+ text.text = value.to_s\r
+ text.attributes["style"] = style if style.length > 0\r
+ end\r
+ end\r
+\r
+\r
+ # Draws the X axis labels\r
+ def draw_x_labels\r
+ stagger = x_label_font_size + 5\r
+ if show_x_labels\r
+ label_width = field_width\r
+\r
+ count = 0\r
+ for label in get_x_labels\r
+ if step_include_first_x_label == true then\r
+ step = count % step_x_labels\r
+ else\r
+ step = (count + 1) % step_x_labels\r
+ end\r
+\r
+ if step == 0 then\r
+ text = @graph.add_element( "text" )\r
+ text.attributes["class"] = "xAxisLabels"\r
+ text.text = label.to_s\r
+\r
+ x = count * label_width + x_label_offset( label_width )\r
+ y = @graph_height + x_label_font_size + 3\r
+ t = 0 - (font_size / 2)\r
+\r
+ if stagger_x_labels and count % 2 == 1\r
+ y += stagger\r
+ @graph.add_element( "path", {\r
+ "d" => "M#{x} #@graph_height v#{stagger}",\r
+ "class" => "staggerGuideLine"\r
+ })\r
+ end\r
+\r
+ text.attributes["x"] = x.to_s\r
+ text.attributes["y"] = y.to_s\r
+ if rotate_x_labels\r
+ text.attributes["transform"] = \r
+ "rotate( 90 #{x} #{y-x_label_font_size} )"+\r
+ " translate( 0 -#{x_label_font_size/4} )"\r
+ text.attributes["style"] = "text-anchor: start"\r
+ else\r
+ text.attributes["style"] = "text-anchor: middle"\r
+ end\r
+ end\r
+\r
+ draw_x_guidelines( label_width, count ) if show_x_guidelines\r
+ count += 1\r
+ end\r
+ end\r
+ end\r
+\r
+\r
+ # Where in the Y area the label is drawn\r
+ # Centered in the field, should be width/2. Start, 0.\r
+ def y_label_offset( height )\r
+ 0\r
+ end\r
+\r
+\r
+ def field_width\r
+ (@graph_width.to_f - font_size*2*right_font) /\r
+ (get_x_labels.length - right_align)\r
+ end\r
+\r
+\r
+ def field_height\r
+ (@graph_height.to_f - font_size*2*top_font) /\r
+ (get_y_labels.length - top_align)\r
+ end\r
+\r
+\r
+ # Draws the Y axis labels\r
+ def draw_y_labels\r
+ stagger = y_label_font_size + 5\r
+ if show_y_labels\r
+ label_height = field_height\r
+\r
+ count = 0\r
+ y_offset = @graph_height + y_label_offset( label_height )\r
+ y_offset += font_size/1.2 unless rotate_y_labels\r
+ for label in get_y_labels\r
+ y = y_offset - (label_height * count)\r
+ x = rotate_y_labels ? 0 : -3\r
+\r
+ if stagger_y_labels and count % 2 == 1\r
+ x -= stagger\r
+ @graph.add_element( "path", {\r
+ "d" => "M#{x} #{y} h#{stagger}",\r
+ "class" => "staggerGuideLine"\r
+ })\r
+ end\r
+\r
+ text = @graph.add_element( "text", {\r
+ "x" => x.to_s,\r
+ "y" => y.to_s,\r
+ "class" => "yAxisLabels"\r
+ })\r
+ text.text = label.to_s\r
+ if rotate_y_labels\r
+ text.attributes["transform"] = "translate( -#{font_size} 0 ) "+\r
+ "rotate( 90 #{x} #{y} ) "\r
+ text.attributes["style"] = "text-anchor: middle"\r
+ else\r
+ text.attributes["y"] = (y - (y_label_font_size/2)).to_s\r
+ text.attributes["style"] = "text-anchor: end"\r
+ end\r
+ draw_y_guidelines( label_height, count ) if show_y_guidelines\r
+ count += 1\r
+ end\r
+ end\r
+ end\r
+\r
+\r
+ # Draws the X axis guidelines\r
+ def draw_x_guidelines( label_height, count )\r
+ if count != 0\r
+ @graph.add_element( "path", {\r
+ "d" => "M#{label_height*count} 0 v#@graph_height",\r
+ "class" => "guideLines"\r
+ })\r
+ end\r
+ end\r
+\r
+\r
+ # Draws the Y axis guidelines\r
+ def draw_y_guidelines( label_height, count )\r
+ if count != 0\r
+ @graph.add_element( "path", {\r
+ "d" => "M0 #{@graph_height-(label_height*count)} h#@graph_width",\r
+ "class" => "guideLines"\r
+ })\r
+ end\r
+ end\r
+\r
+\r
+ # Draws the graph title and subtitle\r
+ def draw_titles\r
+ if show_graph_title\r
+ @root.add_element( "text", {\r
+ "x" => (width / 2).to_s,\r
+ "y" => (title_font_size).to_s,\r
+ "class" => "mainTitle"\r
+ }).text = graph_title.to_s\r
+ end\r
+\r
+ if show_graph_subtitle\r
+ y_subtitle = show_graph_title ? \r
+ title_font_size + 10 :\r
+ subtitle_font_size\r
+ @root.add_element("text", {\r
+ "x" => (width / 2).to_s,\r
+ "y" => (y_subtitle).to_s,\r
+ "class" => "subTitle"\r
+ }).text = graph_subtitle.to_s\r
+ end\r
+\r
+ if show_x_title\r
+ y = @graph_height + @border_top + x_title_font_size\r
+ if show_x_labels\r
+ y += x_label_font_size + 5 if stagger_x_labels\r
+ y += x_label_font_size + 5\r
+ end\r
+ x = width / 2\r
+\r
+ @root.add_element("text", {\r
+ "x" => x.to_s,\r
+ "y" => y.to_s,\r
+ "class" => "xAxisTitle",\r
+ }).text = x_title.to_s\r
+ end\r
+\r
+ if show_y_title\r
+ x = y_title_font_size + (y_title_text_direction==:bt ? 3 : -3)\r
+ y = height / 2\r
+\r
+ text = @root.add_element("text", {\r
+ "x" => x.to_s,\r
+ "y" => y.to_s,\r
+ "class" => "yAxisTitle",\r
+ })\r
+ text.text = y_title.to_s\r
+ if y_title_text_direction == :bt\r
+ text.attributes["transform"] = "rotate( -90, #{x}, #{y} )"\r
+ else\r
+ text.attributes["transform"] = "rotate( 90, #{x}, #{y} )"\r
+ end\r
+ end\r
+ end\r
+\r
+ def keys \r
+ return @data.collect{ |d| d[:title] }\r
+ end\r
+\r
+ # Draws the legend on the graph\r
+ def draw_legend\r
+ if key\r
+ group = @root.add_element( "g" )\r
+\r
+ key_count = 0\r
+ for key_name in keys\r
+ y_offset = (KEY_BOX_SIZE * key_count) + (key_count * 5)\r
+ group.add_element( "rect", {\r
+ "x" => 0.to_s,\r
+ "y" => y_offset.to_s,\r
+ "width" => KEY_BOX_SIZE.to_s,\r
+ "height" => KEY_BOX_SIZE.to_s,\r
+ "class" => "key#{key_count+1}"\r
+ })\r
+ group.add_element( "text", {\r
+ "x" => (KEY_BOX_SIZE + 5).to_s,\r
+ "y" => (y_offset + KEY_BOX_SIZE).to_s,\r
+ "class" => "keyText"\r
+ }).text = key_name.to_s\r
+ key_count += 1\r
+ end\r
+\r
+ case key_position\r
+ when :right\r
+ x_offset = @graph_width + @border_left + 10\r
+ y_offset = @border_top + 20\r
+ when :bottom\r
+ x_offset = @border_left + 20\r
+ y_offset = @border_top + @graph_height + 5\r
+ if show_x_labels\r
+ max_x_label_height_px = (not rotate_x_labels) ? \r
+ x_label_font_size :\r
+ get_x_labels.max{|a,b| \r
+ a.to_s.length<=>b.to_s.length\r
+ }.to_s.length * x_label_font_size * 0.6\r
+ x_label_font_size\r
+ y_offset += max_x_label_height_px\r
+ y_offset += max_x_label_height_px + 5 if stagger_x_labels\r
+ end\r
+ y_offset += x_title_font_size + 5 if show_x_title\r
+ end\r
+ group.attributes["transform"] = "translate(#{x_offset} #{y_offset})"\r
+ end\r
+ end\r
+\r
+\r
+ private\r
+\r
+ def sort_multiple( arrys, lo=0, hi=arrys[0].length-1 )\r
+ if lo < hi\r
+ p = partition(arrys,lo,hi)\r
+ sort_multiple(arrys, lo, p-1)\r
+ sort_multiple(arrys, p+1, hi)\r
+ end\r
+ arrys \r
+ end\r
+\r
+ def partition( arrys, lo, hi )\r
+ p = arrys[0][lo]\r
+ l = lo\r
+ z = lo+1\r
+ while z <= hi\r
+ if arrys[0][z] < p\r
+ l += 1\r
+ arrys.each { |arry| arry[z], arry[l] = arry[l], arry[z] }\r
+ end\r
+ z += 1\r
+ end\r
+ arrys.each { |arry| arry[lo], arry[l] = arry[l], arry[lo] }\r
+ l\r
+ end\r
+\r
+ def style\r
+ if no_css\r
+ styles = parse_css\r
+ @root.elements.each("//*[@class]") { |el|\r
+ cl = el.attributes["class"]\r
+ style = styles[cl]\r
+ style += el.attributes["style"] if el.attributes["style"]\r
+ el.attributes["style"] = style\r
+ }\r
+ end\r
+ end\r
+\r
+ def parse_css\r
+ css = get_style\r
+ rv = {}\r
+ while css =~ /^(\.(\w+)(?:\s*,\s*\.\w+)*)\s*\{/m\r
+ names_orig = names = $1\r
+ css = $'\r
+ css =~ /([^}]+)\}/m\r
+ content = $1\r
+ css = $'\r
+\r
+ nms = []\r
+ while names =~ /^\s*,?\s*\.(\w+)/\r
+ nms << $1\r
+ names = $'\r
+ end\r
+\r
+ content = content.tr( "\n\t", " ")\r
+ for name in nms\r
+ current = rv[name]\r
+ current = current ? current+"; "+content : content\r
+ rv[name] = current.strip.squeeze(" ")\r
+ end\r
+ end\r
+ return rv\r
+ end\r
+\r
+\r
+ # Override and place code to add defs here\r
+ def add_defs defs\r
+ end\r
+\r
+\r
+ def start_svg\r
+ # Base document\r
+ @doc = Document.new\r
+ @doc << XMLDecl.new\r
+ @doc << DocType.new( %q{svg PUBLIC "-//W3C//DTD SVG 1.0//EN" } +\r
+ %q{"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"} )\r
+ if style_sheet && style_sheet != ''\r
+ @doc << Instruction.new( "xml-stylesheet",\r
+ %Q{href="#{style_sheet}" type="text/css"} )\r
+ end\r
+ @root = @doc.add_element( "svg", {\r
+ "width" => width.to_s,\r
+ "height" => height.to_s,\r
+ "viewBox" => "0 0 #{width} #{height}",\r
+ "xmlns" => "http://www.w3.org/2000/svg",\r
+ "xmlns:xlink" => "http://www.w3.org/1999/xlink",\r
+ "xmlns:a3" => "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/",\r
+ "a3:scriptImplementation" => "Adobe"\r
+ })\r
+ @root << Comment.new( " "+"\\"*66 )\r
+ @root << Comment.new( " Created with SVG::Graph " )\r
+ @root << Comment.new( " SVG::Graph by Sean E. Russell " )\r
+ @root << Comment.new( " Losely based on SVG::TT::Graph for Perl by"+\r
+ " Leo Lapworth & Stephan Morgan " )\r
+ @root << Comment.new( " "+"/"*66 )\r
+\r
+ defs = @root.add_element( "defs" )\r
+ add_defs defs\r
+ if not(style_sheet && style_sheet != '') and !no_css\r
+ @root << Comment.new(" include default stylesheet if none specified ")\r
+ style = defs.add_element( "style", {"type"=>"text/css"} )\r
+ style << CData.new( get_style )\r
+ end\r
+\r
+ @root << Comment.new( "SVG Background" )\r
+ @root.add_element( "rect", {\r
+ "width" => width.to_s,\r
+ "height" => height.to_s,\r
+ "x" => "0",\r
+ "y" => "0",\r
+ "class" => "svgBackground"\r
+ })\r
+ end\r
+\r
+\r
+ def calculate_graph_dimensions\r
+ calculate_left_margin\r
+ calculate_right_margin\r
+ calculate_bottom_margin\r
+ calculate_top_margin\r
+ @graph_width = width - @border_left - @border_right\r
+ @graph_height = height - @border_top - @border_bottom\r
+ end\r
+\r
+ def get_style\r
+ return <<EOL\r
+/* Copy from here for external style sheet */\r
+.svgBackground{\r
+ fill:#ffffff;\r
+}\r
+.graphBackground{\r
+ fill:#f0f0f0;\r
+}\r
+\r
+/* graphs titles */\r
+.mainTitle{\r
+ text-anchor: middle;\r
+ fill: #000000;\r
+ font-size: #{title_font_size}px;\r
+ font-family: "Arial", sans-serif;\r
+ font-weight: normal;\r
+}\r
+.subTitle{\r
+ text-anchor: middle;\r
+ fill: #999999;\r
+ font-size: #{subtitle_font_size}px;\r
+ font-family: "Arial", sans-serif;\r
+ font-weight: normal;\r
+}\r
+\r
+.axis{\r
+ stroke: #000000;\r
+ stroke-width: 1px;\r
+}\r
+\r
+.guideLines{\r
+ stroke: #666666;\r
+ stroke-width: 1px;\r
+ stroke-dasharray: 5 5;\r
+}\r
+\r
+.xAxisLabels{\r
+ text-anchor: middle;\r
+ fill: #000000;\r
+ font-size: #{x_label_font_size}px;\r
+ font-family: "Arial", sans-serif;\r
+ font-weight: normal;\r
+}\r
+\r
+.yAxisLabels{\r
+ text-anchor: end;\r
+ fill: #000000;\r
+ font-size: #{y_label_font_size}px;\r
+ font-family: "Arial", sans-serif;\r
+ font-weight: normal;\r
+}\r
+\r
+.xAxisTitle{\r
+ text-anchor: middle;\r
+ fill: #ff0000;\r
+ font-size: #{x_title_font_size}px;\r
+ font-family: "Arial", sans-serif;\r
+ font-weight: normal;\r
+}\r
+\r
+.yAxisTitle{\r
+ fill: #ff0000;\r
+ text-anchor: middle;\r
+ font-size: #{y_title_font_size}px;\r
+ font-family: "Arial", sans-serif;\r
+ font-weight: normal;\r
+}\r
+\r
+.dataPointLabel{\r
+ fill: #000000;\r
+ text-anchor:middle;\r
+ font-size: 10px;\r
+ font-family: "Arial", sans-serif;\r
+ font-weight: normal;\r
+}\r
+\r
+.staggerGuideLine{\r
+ fill: none;\r
+ stroke: #000000;\r
+ stroke-width: 0.5px; \r
+}\r
+\r
+#{get_css}\r
+\r
+.keyText{\r
+ fill: #000000;\r
+ text-anchor:start;\r
+ font-size: #{key_font_size}px;\r
+ font-family: "Arial", sans-serif;\r
+ font-weight: normal;\r
+}\r
+/* End copy for external style sheet */\r
+EOL\r
+ end\r
+\r
+ end\r
+ end\r
+end\r
-require 'SVG/Graph/Graph'
-
-module SVG
- module Graph
- # === Create presentation quality SVG pie graphs easily
- #
- # == Synopsis
- #
- # require 'SVG/Graph/Pie'
- #
- # fields = %w(Jan Feb Mar)
- # data_sales_02 = [12, 45, 21]
- #
- # graph = SVG::Graph::Pie.new({
- # :height => 500,
- # :width => 300,
- # :fields => fields,
- # })
- #
- # graph.add_data({
- # :data => data_sales_02,
- # :title => 'Sales 2002',
- # })
- #
- # 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 pie 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, display percent on pie chart,
- # title, subtitle etc.
- #
- # = Examples
- #
- # http://www.germane-software/repositories/public/SVG/test/single.rb
- #
- # == See also
- #
- # * SVG::Graph::Graph
- # * SVG::Graph::BarHorizontal
- # * SVG::Graph::Bar
- # * SVG::Graph::Line
- # * SVG::Graph::Plot
- # * SVG::Graph::TimeSeries
- #
- # == Author
- #
- # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
- #
- # Copyright 2004 Sean E. Russell
- # This software is available under the Ruby license[LICENSE.txt]
- #
- class Pie < Graph
- # Defaults are those set by Graph::initialize, and
- # [show_shadow] true
- # [shadow_offset] 10
- # [show_data_labels] false
- # [show_actual_values] false
- # [show_percent] true
- # [show_key_data_labels] true
- # [show_key_actual_values] true
- # [show_key_percent] false
- # [expanded] false
- # [expand_greatest] false
- # [expand_gap] 10
- # [show_x_labels] false
- # [show_y_labels] false
- # [datapoint_font_size] 12
- def set_defaults
- init_with(
- :show_shadow => true,
- :shadow_offset => 10,
-
- :show_data_labels => false,
- :show_actual_values => false,
- :show_percent => true,
-
- :show_key_data_labels => true,
- :show_key_actual_values => true,
- :show_key_percent => false,
-
- :expanded => false,
- :expand_greatest => false,
- :expand_gap => 10,
-
- :show_x_labels => false,
- :show_y_labels => false,
- :datapoint_font_size => 12
- )
- @data = []
- end
-
- # Adds a data set to the graph.
- #
- # graph.add_data( { :data => [1,2,3,4] } )
- #
- # Note that the :title is not necessary. If multiple
- # data sets are added to the graph, the pie chart will
- # display the +sums+ of the data. EG:
- #
- # graph.add_data( { :data => [1,2,3,4] } )
- # graph.add_data( { :data => [2,3,5,9] } )
- #
- # is the same as:
- #
- # graph.add_data( { :data => [3,5,8,13] } )
- def add_data arg
- arg[:data].each_index {|idx|
- @data[idx] = 0 unless @data[idx]
- @data[idx] += arg[:data][idx]
- }
- end
-
- # If true, displays a drop shadow for the chart
- attr_accessor :show_shadow
- # Sets the offset of the shadow from the pie chart
- attr_accessor :shadow_offset
- # If true, display the data labels on the chart
- attr_accessor :show_data_labels
- # If true, display the actual field values in the data labels
- attr_accessor :show_actual_values
- # If true, display the percentage value of each pie wedge in the data
- # labels
- attr_accessor :show_percent
- # If true, display the labels in the key
- attr_accessor :show_key_data_labels
- # If true, display the actual value of the field in the key
- attr_accessor :show_key_actual_values
- # If true, display the percentage value of the wedges in the key
- attr_accessor :show_key_percent
- # If true, "explode" the pie (put space between the wedges)
- attr_accessor :expanded
- # If true, expand the largest pie wedge
- attr_accessor :expand_greatest
- # The amount of space between expanded wedges
- attr_accessor :expand_gap
- # The font size of the data point labels
- attr_accessor :datapoint_font_size
-
-
- protected
-
- def add_defs defs
- gradient = defs.add_element( "filter", {
- "id"=>"dropshadow",
- "width" => "1.2",
- "height" => "1.2",
- } )
- gradient.add_element( "feGaussianBlur", {
- "stdDeviation" => "4",
- "result" => "blur"
- })
- end
-
- # We don't need the graph
- def draw_graph
- end
-
- def get_y_labels
- [""]
- end
-
- def get_x_labels
- [""]
- end
-
- def keys
- total = 0
- max_value = 0
- @data.each {|x| total += x }
- percent_scale = 100.0 / total
- count = -1
- a = @config[:fields].collect{ |x|
- count += 1
- v = @data[count]
- perc = show_key_percent ? " "+(v * percent_scale).round.to_s+"%" : ""
- x + " [" + v.to_s + "]" + perc
- }
- end
-
- RADIANS = Math::PI/180
-
- def draw_data
- @graph = @root.add_element( "g" )
- background = @graph.add_element("g")
- midground = @graph.add_element("g")
-
- diameter = @graph_height > @graph_width ? @graph_width : @graph_height
- diameter -= expand_gap if expanded or expand_greatest
- diameter -= datapoint_font_size if show_data_labels
- diameter -= 10 if show_shadow
- radius = diameter / 2.0
-
- xoff = (width - diameter) / 2
- yoff = (height - @border_bottom - diameter)
- yoff -= 10 if show_shadow
- @graph.attributes['transform'] = "translate( #{xoff} #{yoff} )"
-
- wedge_text_pad = 5
- wedge_text_pad = 20 if show_percent and show_data_labels
-
- total = 0
- max_value = 0
- @data.each {|x|
- max_value = max_value < x ? x : max_value
- total += x
- }
- percent_scale = 100.0 / total
-
- prev_percent = 0
- rad_mult = 3.6 * RADIANS
- @config[:fields].each_index { |count|
- value = @data[count]
- percent = percent_scale * value
-
- radians = prev_percent * rad_mult
- x_start = radius+(Math.sin(radians) * radius)
- y_start = radius-(Math.cos(radians) * radius)
- radians = (prev_percent+percent) * rad_mult
- x_end = radius+(Math.sin(radians) * radius)
- y_end = radius-(Math.cos(radians) * radius)
- path = "M#{radius},#{radius} L#{x_start},#{y_start} "+
- "A#{radius},#{radius} "+
- "0, #{percent >= 50 ? '1' : '0'},1, "+
- "#{x_end} #{y_end} Z"
-
-
- wedge = @foreground.add_element( "path", {
- "d" => path,
- "class" => "fill#{count+1}"
- })
-
- translate = nil
- tx = 0
- ty = 0
- half_percent = prev_percent + percent / 2
- radians = half_percent * rad_mult
-
- if show_shadow
- shadow = background.add_element( "path", {
- "d" => path,
- "filter" => "url(#dropshadow)",
- "style" => "fill: #ccc; stroke: none;"
- })
- clear = midground.add_element( "path", {
- "d" => path,
- "style" => "fill: #fff; stroke: none;"
- })
- end
-
- if expanded or (expand_greatest && value == max_value)
- tx = (Math.sin(radians) * expand_gap)
- ty = -(Math.cos(radians) * expand_gap)
- translate = "translate( #{tx} #{ty} )"
- wedge.attributes["transform"] = translate
- clear.attributes["transform"] = translate
- end
-
- if show_shadow
- shadow.attributes["transform"] =
- "translate( #{tx+shadow_offset} #{ty+shadow_offset} )"
- end
-
- if show_data_labels and value != 0
- label = ""
- label += @config[:fields][count] if show_key_data_labels
- label += " ["+value.to_s+"]" if show_actual_values
- label += " "+percent.round.to_s+"%" if show_percent
-
- msr = Math.sin(radians)
- mcr = Math.cos(radians)
- tx = radius + (msr * radius)
- ty = radius -(mcr * radius)
-
- if expanded or (expand_greatest && value == max_value)
- tx += (msr * expand_gap)
- ty -= (mcr * expand_gap)
- end
- @foreground.add_element( "text", {
- "x" => tx.to_s,
- "y" => ty.to_s,
- "class" => "dataPointLabel",
- "style" => "stroke: #fff; stroke-width: 2;"
- }).text = label.to_s
- @foreground.add_element( "text", {
- "x" => tx.to_s,
- "y" => ty.to_s,
- "class" => "dataPointLabel",
- }).text = label.to_s
- end
-
- prev_percent += percent
- }
- end
-
-
- def round val, to
- up = 10**to.to_f
- (val * up).to_i / up
- end
-
-
- def get_css
- return <<EOL
-.dataPointLabel{
- fill: #000000;
- text-anchor:middle;
- font-size: #{datapoint_font_size}px;
- font-family: "Arial", sans-serif;
- font-weight: normal;
-}
-
-/* key - MUST match fill styles */
-.key1,.fill1{
- fill: #ff0000;
- fill-opacity: 0.7;
- stroke: none;
- stroke-width: 1px;
-}
-.key2,.fill2{
- fill: #0000ff;
- fill-opacity: 0.7;
- stroke: none;
- stroke-width: 1px;
-}
-.key3,.fill3{
- fill-opacity: 0.7;
- fill: #00ff00;
- stroke: none;
- stroke-width: 1px;
-}
-.key4,.fill4{
- fill-opacity: 0.7;
- fill: #ffcc00;
- stroke: none;
- stroke-width: 1px;
-}
-.key5,.fill5{
- fill-opacity: 0.7;
- fill: #00ccff;
- stroke: none;
- stroke-width: 1px;
-}
-.key6,.fill6{
- fill-opacity: 0.7;
- fill: #ff00ff;
- stroke: none;
- stroke-width: 1px;
-}
-.key7,.fill7{
- fill-opacity: 0.7;
- fill: #00ff99;
- stroke: none;
- stroke-width: 1px;
-}
-.key8,.fill8{
- fill-opacity: 0.7;
- fill: #ffff00;
- stroke: none;
- stroke-width: 1px;
-}
-.key9,.fill9{
- fill-opacity: 0.7;
- fill: #cc6666;
- stroke: none;
- stroke-width: 1px;
-}
-.key10,.fill10{
- fill-opacity: 0.7;
- fill: #663399;
- stroke: none;
- stroke-width: 1px;
-}
-.key11,.fill11{
- fill-opacity: 0.7;
- fill: #339900;
- stroke: none;
- stroke-width: 1px;
-}
-.key12,.fill12{
- fill-opacity: 0.7;
- fill: #9966FF;
- stroke: none;
- stroke-width: 1px;
-}
-EOL
- end
- end
- end
-end
+require 'SVG/Graph/Graph'\r
+\r
+module SVG\r
+ module Graph\r
+ # === Create presentation quality SVG pie graphs easily\r
+ # \r
+ # == Synopsis\r
+ # \r
+ # require 'SVG/Graph/Pie'\r
+ # \r
+ # fields = %w(Jan Feb Mar)\r
+ # data_sales_02 = [12, 45, 21]\r
+ # \r
+ # graph = SVG::Graph::Pie.new({\r
+ # :height => 500,\r
+ # :width => 300,\r
+ # :fields => fields,\r
+ # })\r
+ # \r
+ # graph.add_data({\r
+ # :data => data_sales_02,\r
+ # :title => 'Sales 2002',\r
+ # })\r
+ # \r
+ # print "Content-type: image/svg+xml\r\n\r\n"\r
+ # print graph.burn();\r
+ # \r
+ # == Description\r
+ # \r
+ # This object aims to allow you to easily create high quality\r
+ # SVG pie graphs. You can either use the default style sheet\r
+ # or supply your own. Either way there are many options which can\r
+ # be configured to give you control over how the graph is\r
+ # generated - with or without a key, display percent on pie chart,\r
+ # title, subtitle etc.\r
+ #\r
+ # = Examples\r
+ # \r
+ # http://www.germane-software/repositories/public/SVG/test/single.rb\r
+ # \r
+ # == See also\r
+ #\r
+ # * SVG::Graph::Graph\r
+ # * SVG::Graph::BarHorizontal\r
+ # * SVG::Graph::Bar\r
+ # * SVG::Graph::Line\r
+ # * SVG::Graph::Plot\r
+ # * SVG::Graph::TimeSeries\r
+ #\r
+ # == Author\r
+ #\r
+ # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>\r
+ #\r
+ # Copyright 2004 Sean E. Russell\r
+ # This software is available under the Ruby license[LICENSE.txt]\r
+ #\r
+ class Pie < Graph\r
+ # Defaults are those set by Graph::initialize, and\r
+ # [show_shadow] true\r
+ # [shadow_offset] 10\r
+ # [show_data_labels] false\r
+ # [show_actual_values] false\r
+ # [show_percent] true\r
+ # [show_key_data_labels] true\r
+ # [show_key_actual_values] true\r
+ # [show_key_percent] false\r
+ # [expanded] false\r
+ # [expand_greatest] false\r
+ # [expand_gap] 10\r
+ # [show_x_labels] false\r
+ # [show_y_labels] false\r
+ # [datapoint_font_size] 12\r
+ def set_defaults\r
+ init_with(\r
+ :show_shadow => true,\r
+ :shadow_offset => 10, \r
+ \r
+ :show_data_labels => false,\r
+ :show_actual_values => false,\r
+ :show_percent => true,\r
+\r
+ :show_key_data_labels => true,\r
+ :show_key_actual_values => true,\r
+ :show_key_percent => false,\r
+ \r
+ :expanded => false,\r
+ :expand_greatest => false,\r
+ :expand_gap => 10,\r
+ \r
+ :show_x_labels => false,\r
+ :show_y_labels => false,\r
+ :datapoint_font_size => 12\r
+ )\r
+ @data = []\r
+ end\r
+\r
+ # Adds a data set to the graph.\r
+ #\r
+ # graph.add_data( { :data => [1,2,3,4] } )\r
+ #\r
+ # Note that the :title is not necessary. If multiple\r
+ # data sets are added to the graph, the pie chart will\r
+ # display the +sums+ of the data. EG:\r
+ #\r
+ # graph.add_data( { :data => [1,2,3,4] } )\r
+ # graph.add_data( { :data => [2,3,5,9] } )\r
+ #\r
+ # is the same as:\r
+ #\r
+ # graph.add_data( { :data => [3,5,8,13] } )\r
+ def add_data arg\r
+ arg[:data].each_index {|idx|\r
+ @data[idx] = 0 unless @data[idx]\r
+ @data[idx] += arg[:data][idx]\r
+ }\r
+ end\r
+\r
+ # If true, displays a drop shadow for the chart\r
+ attr_accessor :show_shadow \r
+ # Sets the offset of the shadow from the pie chart\r
+ attr_accessor :shadow_offset\r
+ # If true, display the data labels on the chart\r
+ attr_accessor :show_data_labels \r
+ # If true, display the actual field values in the data labels\r
+ attr_accessor :show_actual_values \r
+ # If true, display the percentage value of each pie wedge in the data\r
+ # labels\r
+ attr_accessor :show_percent\r
+ # If true, display the labels in the key\r
+ attr_accessor :show_key_data_labels \r
+ # If true, display the actual value of the field in the key\r
+ attr_accessor :show_key_actual_values \r
+ # If true, display the percentage value of the wedges in the key\r
+ attr_accessor :show_key_percent\r
+ # If true, "explode" the pie (put space between the wedges)\r
+ attr_accessor :expanded \r
+ # If true, expand the largest pie wedge\r
+ attr_accessor :expand_greatest \r
+ # The amount of space between expanded wedges\r
+ attr_accessor :expand_gap \r
+ # The font size of the data point labels\r
+ attr_accessor :datapoint_font_size\r
+\r
+\r
+ protected\r
+\r
+ def add_defs defs\r
+ gradient = defs.add_element( "filter", {\r
+ "id"=>"dropshadow",\r
+ "width" => "1.2",\r
+ "height" => "1.2",\r
+ } )\r
+ gradient.add_element( "feGaussianBlur", {\r
+ "stdDeviation" => "4",\r
+ "result" => "blur"\r
+ })\r
+ end\r
+\r
+ # We don't need the graph\r
+ def draw_graph\r
+ end\r
+\r
+ def get_y_labels\r
+ [""]\r
+ end\r
+\r
+ def get_x_labels\r
+ [""]\r
+ end\r
+\r
+ def keys\r
+ total = 0\r
+ max_value = 0\r
+ @data.each {|x| total += x }\r
+ percent_scale = 100.0 / total\r
+ count = -1\r
+ a = @config[:fields].collect{ |x|\r
+ count += 1\r
+ v = @data[count]\r
+ perc = show_key_percent ? " "+(v * percent_scale).round.to_s+"%" : ""\r
+ x + " [" + v.to_s + "]" + perc\r
+ }\r
+ end\r
+\r
+ RADIANS = Math::PI/180\r
+\r
+ def draw_data\r
+ @graph = @root.add_element( "g" )\r
+ background = @graph.add_element("g")\r
+ midground = @graph.add_element("g")\r
+\r
+ diameter = @graph_height > @graph_width ? @graph_width : @graph_height\r
+ diameter -= expand_gap if expanded or expand_greatest\r
+ diameter -= datapoint_font_size if show_data_labels\r
+ diameter -= 10 if show_shadow\r
+ radius = diameter / 2.0\r
+\r
+ xoff = (width - diameter) / 2\r
+ yoff = (height - @border_bottom - diameter)\r
+ yoff -= 10 if show_shadow\r
+ @graph.attributes['transform'] = "translate( #{xoff} #{yoff} )"\r
+\r
+ wedge_text_pad = 5\r
+ wedge_text_pad = 20 if show_percent and show_data_labels\r
+\r
+ total = 0\r
+ max_value = 0\r
+ @data.each {|x| \r
+ max_value = max_value < x ? x : max_value\r
+ total += x \r
+ }\r
+ percent_scale = 100.0 / total\r
+\r
+ prev_percent = 0\r
+ rad_mult = 3.6 * RADIANS\r
+ @config[:fields].each_index { |count|\r
+ value = @data[count]\r
+ percent = percent_scale * value\r
+\r
+ radians = prev_percent * rad_mult\r
+ x_start = radius+(Math.sin(radians) * radius)\r
+ y_start = radius-(Math.cos(radians) * radius)\r
+ radians = (prev_percent+percent) * rad_mult\r
+ x_end = radius+(Math.sin(radians) * radius)\r
+ x_end -= 0.00001 if @data.length == 1\r
+ y_end = radius-(Math.cos(radians) * radius)\r
+ path = "M#{radius},#{radius} L#{x_start},#{y_start} "+\r
+ "A#{radius},#{radius} "+\r
+ "0, #{percent >= 50 ? '1' : '0'},1, "+\r
+ "#{x_end} #{y_end} Z"\r
+\r
+\r
+ wedge = @foreground.add_element( "path", {\r
+ "d" => path,\r
+ "class" => "fill#{count+1}"\r
+ })\r
+\r
+ translate = nil\r
+ tx = 0\r
+ ty = 0\r
+ half_percent = prev_percent + percent / 2\r
+ radians = half_percent * rad_mult\r
+\r
+ if show_shadow\r
+ shadow = background.add_element( "path", {\r
+ "d" => path,\r
+ "filter" => "url(#dropshadow)",\r
+ "style" => "fill: #ccc; stroke: none;"\r
+ })\r
+ clear = midground.add_element( "path", {\r
+ "d" => path,\r
+ "style" => "fill: #fff; stroke: none;"\r
+ })\r
+ end\r
+\r
+ if expanded or (expand_greatest && value == max_value)\r
+ tx = (Math.sin(radians) * expand_gap)\r
+ ty = -(Math.cos(radians) * expand_gap)\r
+ translate = "translate( #{tx} #{ty} )"\r
+ wedge.attributes["transform"] = translate\r
+ clear.attributes["transform"] = translate if clear\r
+ end\r
+\r
+ if show_shadow\r
+ shadow.attributes["transform"] = \r
+ "translate( #{tx+shadow_offset} #{ty+shadow_offset} )"\r
+ end\r
+ \r
+ if show_data_labels and value != 0\r
+ label = ""\r
+ label += @config[:fields][count] if show_key_data_labels\r
+ label += " ["+value.to_s+"]" if show_actual_values\r
+ label += " "+percent.round.to_s+"%" if show_percent\r
+\r
+ msr = Math.sin(radians)\r
+ mcr = Math.cos(radians)\r
+ tx = radius + (msr * radius)\r
+ ty = radius -(mcr * radius)\r
+\r
+ if expanded or (expand_greatest && value == max_value)\r
+ tx += (msr * expand_gap)\r
+ ty -= (mcr * expand_gap)\r
+ end\r
+ @foreground.add_element( "text", {\r
+ "x" => tx.to_s,\r
+ "y" => ty.to_s,\r
+ "class" => "dataPointLabel",\r
+ "style" => "stroke: #fff; stroke-width: 2;"\r
+ }).text = label.to_s\r
+ @foreground.add_element( "text", {\r
+ "x" => tx.to_s,\r
+ "y" => ty.to_s,\r
+ "class" => "dataPointLabel",\r
+ }).text = label.to_s\r
+ end\r
+\r
+ prev_percent += percent\r
+ }\r
+ end\r
+ \r
+\r
+ def round val, to\r
+ up = 10**to.to_f\r
+ (val * up).to_i / up\r
+ end\r
+\r
+\r
+ def get_css\r
+ return <<EOL\r
+.dataPointLabel{\r
+ fill: #000000;\r
+ text-anchor:middle;\r
+ font-size: #{datapoint_font_size}px;\r
+ font-family: "Arial", sans-serif;\r
+ font-weight: normal;\r
+}\r
+\r
+/* key - MUST match fill styles */\r
+.key1,.fill1{\r
+ fill: #ff0000;\r
+ fill-opacity: 0.7;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key2,.fill2{\r
+ fill: #0000ff;\r
+ fill-opacity: 0.7;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key3,.fill3{\r
+ fill-opacity: 0.7;\r
+ fill: #00ff00;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key4,.fill4{\r
+ fill-opacity: 0.7;\r
+ fill: #ffcc00;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key5,.fill5{\r
+ fill-opacity: 0.7;\r
+ fill: #00ccff;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key6,.fill6{\r
+ fill-opacity: 0.7;\r
+ fill: #ff00ff;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key7,.fill7{\r
+ fill-opacity: 0.7;\r
+ fill: #00ff99;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key8,.fill8{\r
+ fill-opacity: 0.7;\r
+ fill: #ffff00;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key9,.fill9{\r
+ fill-opacity: 0.7;\r
+ fill: #cc6666;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key10,.fill10{\r
+ fill-opacity: 0.7;\r
+ fill: #663399;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key11,.fill11{\r
+ fill-opacity: 0.7;\r
+ fill: #339900;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key12,.fill12{\r
+ fill-opacity: 0.7;\r
+ fill: #9966FF;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+EOL\r
+ end\r
+ end\r
+ end\r
+end\r
-require 'SVG/Graph/Graph'
-
-module SVG
- module Graph
- # === For creating SVG plots of scalar data
- #
- # = Synopsis
- #
- # require 'SVG/Graph/Plot'
- #
- # # Data sets are x,y pairs
- # # Note that multiple data sets can differ in length, and that the
- # # data in the datasets needn't be in order; they will be ordered
- # # by the plot along the X-axis.
- # projection = [
- # 6, 11, 0, 5, 18, 7, 1, 11, 13, 9, 1, 2, 19, 0, 3, 13,
- # 7, 9
- # ]
- # actual = [
- # 0, 18, 8, 15, 9, 4, 18, 14, 10, 2, 11, 6, 14, 12,
- # 15, 6, 4, 17, 2, 12
- # ]
- #
- # graph = SVG::Graph::Plot.new({
- # :height => 500,
- # :width => 300,
- # :key => true,
- # :scale_x_integers => true,
- # :scale_y_integerrs => true,
- # })
- #
- # graph.add_data({
- # :data => projection
- # :title => 'Projected',
- # })
- #
- # graph.add_data({
- # :data => actual,
- # :title => 'Actual',
- # })
- #
- # print graph.burn()
- #
- # = Description
- #
- # Produces a graph of scalar data.
- #
- # This object aims to allow you to easily create high quality
- # SVG[http://www.w3c.org/tr/svg] scalar plots. 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
- #
- # http://www.germane-software/repositories/public/SVG/test/plot.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.
- #
- # Unlike the other types of charts, data sets must contain x,y pairs:
- #
- # [ 1, 2 ] # A data set with 1 point: (1,2)
- # [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6)
- #
- # = See also
- #
- # * SVG::Graph::Graph
- # * SVG::Graph::BarHorizontal
- # * SVG::Graph::Bar
- # * SVG::Graph::Line
- # * SVG::Graph::Pie
- # * SVG::Graph::TimeSeries
- #
- # == Author
- #
- # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
- #
- # Copyright 2004 Sean E. Russell
- # This software is available under the Ruby license[LICENSE.txt]
- #
- class Plot < Graph
-
- # In addition to the defaults set by Graph::initialize, sets
- # [show_data_points] true
- # [area_fill] false
- # [stacked] false
- def set_defaults
- init_with(
- :show_data_points => true,
- :area_fill => false,
- :stacked => false
- )
- self.top_align = self.right_align = self.top_font = self.right_font = 1
- end
-
- # Determines the scaling for the X axis divisions.
- #
- # graph.scale_x_divisions = 2
- #
- # would cause the graph to attempt to generate labels stepped by 2; EG:
- # 0,2,4,6,8...
- attr_accessor :scale_x_divisions
- # Determines the scaling for the Y axis divisions.
- #
- # graph.scale_y_divisions = 0.5
- #
- # would cause the graph to attempt to generate labels stepped by 0.5; EG:
- # 0, 0.5, 1, 1.5, 2, ...
- attr_accessor :scale_y_divisions
- # Make the X axis labels integers
- attr_accessor :scale_x_integers
- # Make the Y axis labels integers
- attr_accessor :scale_y_integers
- # Fill the area under the line
- attr_accessor :area_fill
- # Show a small circle on the graph where the line
- # goes from one point to the next.
- attr_accessor :show_data_points
- # Set the minimum value of the X axis
- attr_accessor :min_x_value
- # Set the minimum value of the Y axis
- attr_accessor :min_y_value
-
-
- # Adds data to the plot. The data must be in X,Y pairs; EG
- # [ 1, 2 ] # A data set with 1 point: (1,2)
- # [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6)
- def add_data data
- @data = [] unless @data
-
- raise "No data provided by #{conf.inspect}" unless data[:data] and
- data[:data].kind_of? Array
- raise "Data supplied must be x,y pairs! "+
- "The data provided contained an odd set of "+
- "data points" unless data[:data].length % 2 == 0
- return if data[:data].length == 0
-
- x = []
- y = []
- data[:data].each_index {|i|
- (i%2 == 0 ? x : y) << data[:data][i]
- }
- sort( x, y )
- data[:data] = [x,y]
- @data << data
- end
-
-
- protected
-
- def keys
- @data.collect{ |x| x[:title] }
- end
-
- def calculate_left_margin
- super
- label_left = get_x_labels[0].to_s.length / 2 * font_size * 0.6
- @border_left = label_left if label_left > @border_left
- end
-
- def calculate_right_margin
- super
- label_right = get_x_labels[-1].to_s.length / 2 * font_size * 0.6
- @border_right = label_right if label_right > @border_right
- end
-
-
- X = 0
- Y = 1
- def x_range
- max_value = @data.collect{|x| x[:data][X][-1] }.max
- min_value = @data.collect{|x| x[:data][X][0] }.min
- min_value = min_value<min_x_value ? min_value : min_x_value if min_x_value
-
- range = max_value - min_value
- right_pad = range == 0 ? 10 : range / 20.0
- scale_range = (max_value + right_pad) - min_value
-
- scale_division = scale_x_divisions || (scale_range / 10.0)
-
- if scale_x_integers
- scale_division = scale_division < 1 ? 1 : scale_division.round
- end
-
- [min_value, max_value, scale_division]
- end
-
- def get_x_values
- min_value, max_value, scale_division = x_range
- rv = []
- min_value.step( max_value, scale_division ) {|v| rv << v}
- return rv
- end
- alias :get_x_labels :get_x_values
-
- def field_width
- values = get_x_values
- max = @data.collect{|x| x[:data][X][-1]}.max
- dx = (max - values[-1]).to_f / (values[-1] - values[-2])
- (@graph_width.to_f - font_size*2*right_font) /
- (values.length + dx - right_align)
- end
-
-
- def y_range
- max_value = @data.collect{|x| x[:data][Y].max }.max
- min_value = @data.collect{|x| x[:data][Y].min }.min
- min_value = min_value<min_y_value ? min_value : min_y_value if min_y_value
-
- range = max_value - min_value
- top_pad = range == 0 ? 10 : range / 20.0
- scale_range = (max_value + top_pad) - min_value
-
- scale_division = scale_y_divisions || (scale_range / 10.0)
-
- if scale_y_integers
- scale_division = scale_division < 1 ? 1 : scale_division.round
- end
-
- return [min_value, max_value, scale_division]
- end
-
- def get_y_values
- min_value, max_value, scale_division = y_range
- rv = []
- min_value.step( max_value, scale_division ) {|v| rv << v}
- return rv
- end
- alias :get_y_labels :get_y_values
-
- def field_height
- values = get_y_values
- max = @data.collect{|x| x[:data][Y].max }.max
- dx = (max - values[-1]).to_f / (values[-1] - values[-2])
- (@graph_height.to_f - font_size*2*top_font) /
- (values.length + dx - top_align)
- end
-
- def draw_data
- line = 1
-
- x_min, x_max, x_div = x_range
- y_min, y_max, y_div = y_range
- x_step = (@graph_width.to_f - font_size*2) / (x_max-x_min)
- y_step = (@graph_height.to_f - font_size*2) / (y_max-y_min)
-
- for data in @data
- x_points = data[:data][X]
- y_points = data[:data][Y]
-
- lpath = "L"
- x_start = 0
- y_start = 0
- x_points.each_index { |idx|
- x = (x_points[idx] - x_min) * x_step
- y = @graph_height - (y_points[idx] - y_min) * y_step
- x_start, y_start = x,y if idx == 0
- lpath << "#{x} #{y} "
- }
-
- if area_fill
- @graph.add_element( "path", {
- "d" => "M#{x_start} #@graph_height #{lpath} V#@graph_height Z",
- "class" => "fill#{line}"
- })
- end
-
- @graph.add_element( "path", {
- "d" => "M#{x_start} #{y_start} #{lpath}",
- "class" => "line#{line}"
- })
-
- if show_data_points || show_data_values
- x_points.each_index { |idx|
- x = (x_points[idx] - x_min) * x_step
- y = @graph_height - (y_points[idx] - y_min) * y_step
- if show_data_points
- @graph.add_element( "circle", {
- "cx" => x.to_s,
- "cy" => y.to_s,
- "r" => "2.5",
- "class" => "dataPoint#{line}"
- })
- add_popup(x, y, format( x_points[idx], y_points[idx] )) if add_popups
- end
- make_datapoint_text( x, y-6, y_points[idx] )
- }
- end
- line += 1
- end
- end
-
- def format x, y
- "(#{(x * 100).to_i / 100}, #{(y * 100).to_i / 100})"
- end
-
- def get_css
- return <<EOL
-/* default line styles */
-.line1{
- fill: none;
- stroke: #ff0000;
- stroke-width: 1px;
-}
-.line2{
- fill: none;
- stroke: #0000ff;
- stroke-width: 1px;
-}
-.line3{
- fill: none;
- stroke: #00ff00;
- stroke-width: 1px;
-}
-.line4{
- fill: none;
- stroke: #ffcc00;
- stroke-width: 1px;
-}
-.line5{
- fill: none;
- stroke: #00ccff;
- stroke-width: 1px;
-}
-.line6{
- fill: none;
- stroke: #ff00ff;
- stroke-width: 1px;
-}
-.line7{
- fill: none;
- stroke: #00ffff;
- stroke-width: 1px;
-}
-.line8{
- fill: none;
- stroke: #ffff00;
- stroke-width: 1px;
-}
-.line9{
- fill: none;
- stroke: #ccc6666;
- stroke-width: 1px;
-}
-.line10{
- fill: none;
- stroke: #663399;
- stroke-width: 1px;
-}
-.line11{
- fill: none;
- stroke: #339900;
- stroke-width: 1px;
-}
-.line12{
- fill: none;
- stroke: #9966FF;
- stroke-width: 1px;
-}
-/* default fill styles */
-.fill1{
- fill: #cc0000;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill2{
- fill: #0000cc;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill3{
- fill: #00cc00;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill4{
- fill: #ffcc00;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill5{
- fill: #00ccff;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill6{
- fill: #ff00ff;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill7{
- fill: #00ffff;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill8{
- fill: #ffff00;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill9{
- fill: #cc6666;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill10{
- fill: #663399;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill11{
- fill: #339900;
- fill-opacity: 0.2;
- stroke: none;
-}
-.fill12{
- fill: #9966FF;
- fill-opacity: 0.2;
- stroke: none;
-}
-/* default line styles */
-.key1,.dataPoint1{
- fill: #ff0000;
- stroke: none;
- stroke-width: 1px;
-}
-.key2,.dataPoint2{
- fill: #0000ff;
- stroke: none;
- stroke-width: 1px;
-}
-.key3,.dataPoint3{
- fill: #00ff00;
- stroke: none;
- stroke-width: 1px;
-}
-.key4,.dataPoint4{
- fill: #ffcc00;
- stroke: none;
- stroke-width: 1px;
-}
-.key5,.dataPoint5{
- fill: #00ccff;
- stroke: none;
- stroke-width: 1px;
-}
-.key6,.dataPoint6{
- fill: #ff00ff;
- stroke: none;
- stroke-width: 1px;
-}
-.key7,.dataPoint7{
- fill: #00ffff;
- stroke: none;
- stroke-width: 1px;
-}
-.key8,.dataPoint8{
- fill: #ffff00;
- stroke: none;
- stroke-width: 1px;
-}
-.key9,.dataPoint9{
- fill: #cc6666;
- stroke: none;
- stroke-width: 1px;
-}
-.key10,.dataPoint10{
- fill: #663399;
- stroke: none;
- stroke-width: 1px;
-}
-.key11,.dataPoint11{
- fill: #339900;
- stroke: none;
- stroke-width: 1px;
-}
-.key12,.dataPoint12{
- fill: #9966FF;
- stroke: none;
- stroke-width: 1px;
-}
-EOL
- end
-
- end
- end
-end
+require 'SVG/Graph/Graph'\r
+\r
+module SVG\r
+ module Graph\r
+ # === For creating SVG plots of scalar data\r
+ # \r
+ # = Synopsis\r
+ # \r
+ # require 'SVG/Graph/Plot'\r
+ # \r
+ # # Data sets are x,y pairs\r
+ # # Note that multiple data sets can differ in length, and that the\r
+ # # data in the datasets needn't be in order; they will be ordered\r
+ # # by the plot along the X-axis.\r
+ # projection = [\r
+ # 6, 11, 0, 5, 18, 7, 1, 11, 13, 9, 1, 2, 19, 0, 3, 13,\r
+ # 7, 9 \r
+ # ]\r
+ # actual = [\r
+ # 0, 18, 8, 15, 9, 4, 18, 14, 10, 2, 11, 6, 14, 12, \r
+ # 15, 6, 4, 17, 2, 12\r
+ # ]\r
+ # \r
+ # graph = SVG::Graph::Plot.new({\r
+ # :height => 500,\r
+ # :width => 300,\r
+ # :key => true,\r
+ # :scale_x_integers => true,\r
+ # :scale_y_integerrs => true,\r
+ # })\r
+ # \r
+ # graph.add_data({\r
+ # :data => projection\r
+ # :title => 'Projected',\r
+ # })\r
+ # \r
+ # graph.add_data({\r
+ # :data => actual,\r
+ # :title => 'Actual',\r
+ # })\r
+ # \r
+ # print graph.burn()\r
+ # \r
+ # = Description\r
+ # \r
+ # Produces a graph of scalar data.\r
+ # \r
+ # This object aims to allow you to easily create high quality\r
+ # SVG[http://www.w3c.org/tr/svg] scalar plots. You can either use the\r
+ # default style sheet or supply your own. Either way there are many options\r
+ # which can be configured to give you control over how the graph is\r
+ # generated - with or without a key, data elements at each point, title,\r
+ # subtitle etc.\r
+ #\r
+ # = Examples\r
+ # \r
+ # http://www.germane-software/repositories/public/SVG/test/plot.rb\r
+ # \r
+ # = Notes\r
+ # \r
+ # The default stylesheet handles upto 10 data sets, if you\r
+ # use more you must create your own stylesheet and add the\r
+ # additional settings for the extra data sets. You will know\r
+ # if you go over 10 data sets as they will have no style and\r
+ # be in black.\r
+ #\r
+ # Unlike the other types of charts, data sets must contain x,y pairs:\r
+ #\r
+ # [ 1, 2 ] # A data set with 1 point: (1,2)\r
+ # [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6) \r
+ # \r
+ # = See also\r
+ # \r
+ # * SVG::Graph::Graph\r
+ # * SVG::Graph::BarHorizontal\r
+ # * SVG::Graph::Bar\r
+ # * SVG::Graph::Line\r
+ # * SVG::Graph::Pie\r
+ # * SVG::Graph::TimeSeries\r
+ #\r
+ # == Author\r
+ #\r
+ # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>\r
+ #\r
+ # Copyright 2004 Sean E. Russell\r
+ # This software is available under the Ruby license[LICENSE.txt]\r
+ #\r
+ class Plot < Graph\r
+\r
+ # In addition to the defaults set by Graph::initialize, sets\r
+ # [show_data_values] true\r
+ # [show_data_points] true\r
+ # [area_fill] false\r
+ # [stacked] false\r
+ def set_defaults\r
+ init_with(\r
+ :show_data_values => true,\r
+ :show_data_points => true,\r
+ :area_fill => false,\r
+ :stacked => false\r
+ )\r
+ self.top_align = self.right_align = self.top_font = self.right_font = 1\r
+ end\r
+\r
+ # Determines the scaling for the X axis divisions.\r
+ #\r
+ # graph.scale_x_divisions = 2\r
+ #\r
+ # would cause the graph to attempt to generate labels stepped by 2; EG:\r
+ # 0,2,4,6,8...\r
+ attr_accessor :scale_x_divisions\r
+ # Determines the scaling for the Y axis divisions.\r
+ #\r
+ # graph.scale_y_divisions = 0.5\r
+ #\r
+ # would cause the graph to attempt to generate labels stepped by 0.5; EG:\r
+ # 0, 0.5, 1, 1.5, 2, ...\r
+ attr_accessor :scale_y_divisions \r
+ # Make the X axis labels integers\r
+ attr_accessor :scale_x_integers \r
+ # Make the Y axis labels integers\r
+ attr_accessor :scale_y_integers \r
+ # Fill the area under the line\r
+ attr_accessor :area_fill \r
+ # Show a small circle on the graph where the line\r
+ # goes from one point to the next.\r
+ attr_accessor :show_data_points\r
+ # Set the minimum value of the X axis\r
+ attr_accessor :min_x_value \r
+ # Set the minimum value of the Y axis\r
+ attr_accessor :min_y_value\r
+\r
+\r
+ # Adds data to the plot. The data must be in X,Y pairs; EG\r
+ # [ 1, 2 ] # A data set with 1 point: (1,2)\r
+ # [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6) \r
+ def add_data data\r
+ @data = [] unless @data\r
+\r
+ raise "No data provided by #{conf.inspect}" unless data[:data] and\r
+ data[:data].kind_of? Array\r
+ raise "Data supplied must be x,y pairs! "+\r
+ "The data provided contained an odd set of "+\r
+ "data points" unless data[:data].length % 2 == 0\r
+ return if data[:data].length == 0\r
+\r
+ x = []\r
+ y = []\r
+ data[:data].each_index {|i|\r
+ (i%2 == 0 ? x : y) << data[:data][i]\r
+ }\r
+ sort( x, y )\r
+ data[:data] = [x,y]\r
+ @data << data\r
+ end\r
+\r
+\r
+ protected\r
+\r
+ def keys\r
+ @data.collect{ |x| x[:title] }\r
+ end\r
+\r
+ def calculate_left_margin\r
+ super\r
+ label_left = get_x_labels[0].to_s.length / 2 * font_size * 0.6\r
+ @border_left = label_left if label_left > @border_left\r
+ end\r
+\r
+ def calculate_right_margin\r
+ super\r
+ label_right = get_x_labels[-1].to_s.length / 2 * font_size * 0.6\r
+ @border_right = label_right if label_right > @border_right\r
+ end\r
+\r
+\r
+ X = 0\r
+ Y = 1\r
+ def x_range\r
+ max_value = @data.collect{|x| x[:data][X][-1] }.max\r
+ min_value = @data.collect{|x| x[:data][X][0] }.min\r
+ min_value = min_value<min_x_value ? min_value : min_x_value if min_x_value\r
+\r
+ range = max_value - min_value\r
+ right_pad = range == 0 ? 10 : range / 20.0\r
+ scale_range = (max_value + right_pad) - min_value\r
+\r
+ scale_division = scale_x_divisions || (scale_range / 10.0)\r
+\r
+ if scale_x_integers\r
+ scale_division = scale_division < 1 ? 1 : scale_division.round\r
+ end\r
+\r
+ [min_value, max_value, scale_division]\r
+ end\r
+\r
+ def get_x_values\r
+ min_value, max_value, scale_division = x_range\r
+ rv = []\r
+ min_value.step( max_value, scale_division ) {|v| rv << v}\r
+ return rv\r
+ end\r
+ alias :get_x_labels :get_x_values\r
+\r
+ def field_width\r
+ values = get_x_values\r
+ max = @data.collect{|x| x[:data][X][-1]}.max\r
+ dx = (max - values[-1]).to_f / (values[-1] - values[-2])\r
+ (@graph_width.to_f - font_size*2*right_font) /\r
+ (values.length + dx - right_align)\r
+ end\r
+\r
+\r
+ def y_range\r
+ max_value = @data.collect{|x| x[:data][Y].max }.max\r
+ min_value = @data.collect{|x| x[:data][Y].min }.min\r
+ min_value = min_value<min_y_value ? min_value : min_y_value if min_y_value\r
+\r
+ range = max_value - min_value\r
+ top_pad = range == 0 ? 10 : range / 20.0\r
+ scale_range = (max_value + top_pad) - min_value\r
+\r
+ scale_division = scale_y_divisions || (scale_range / 10.0)\r
+\r
+ if scale_y_integers\r
+ scale_division = scale_division < 1 ? 1 : scale_division.round\r
+ end\r
+\r
+ return [min_value, max_value, scale_division]\r
+ end\r
+\r
+ def get_y_values\r
+ min_value, max_value, scale_division = y_range\r
+ rv = []\r
+ min_value.step( max_value, scale_division ) {|v| rv << v}\r
+ return rv\r
+ end\r
+ alias :get_y_labels :get_y_values\r
+\r
+ def field_height\r
+ values = get_y_values\r
+ max = @data.collect{|x| x[:data][Y].max }.max\r
+ if values.length == 1\r
+ dx = values[-1]\r
+ else\r
+ dx = (max - values[-1]).to_f / (values[-1] - values[-2])\r
+ end\r
+ (@graph_height.to_f - font_size*2*top_font) /\r
+ (values.length + dx - top_align)\r
+ end\r
+\r
+ def draw_data\r
+ line = 1\r
+\r
+ x_min, x_max, x_div = x_range\r
+ y_min, y_max, y_div = y_range\r
+ x_step = (@graph_width.to_f - font_size*2) / (x_max-x_min)\r
+ y_step = (@graph_height.to_f - font_size*2) / (y_max-y_min)\r
+\r
+ for data in @data\r
+ x_points = data[:data][X]\r
+ y_points = data[:data][Y]\r
+\r
+ lpath = "L"\r
+ x_start = 0\r
+ y_start = 0\r
+ x_points.each_index { |idx|\r
+ x = (x_points[idx] - x_min) * x_step\r
+ y = @graph_height - (y_points[idx] - y_min) * y_step\r
+ x_start, y_start = x,y if idx == 0\r
+ lpath << "#{x} #{y} "\r
+ }\r
+\r
+ if area_fill\r
+ @graph.add_element( "path", {\r
+ "d" => "M#{x_start} #@graph_height #{lpath} V#@graph_height Z",\r
+ "class" => "fill#{line}"\r
+ })\r
+ end\r
+\r
+ @graph.add_element( "path", {\r
+ "d" => "M#{x_start} #{y_start} #{lpath}",\r
+ "class" => "line#{line}"\r
+ })\r
+\r
+ if show_data_points || show_data_values\r
+ x_points.each_index { |idx|\r
+ x = (x_points[idx] - x_min) * x_step\r
+ y = @graph_height - (y_points[idx] - y_min) * y_step\r
+ if show_data_points\r
+ @graph.add_element( "circle", {\r
+ "cx" => x.to_s,\r
+ "cy" => y.to_s,\r
+ "r" => "2.5",\r
+ "class" => "dataPoint#{line}"\r
+ })\r
+ add_popup(x, y, format( x_points[idx], y_points[idx] )) if add_popups\r
+ end\r
+ make_datapoint_text( x, y-6, y_points[idx] ) if show_data_values\r
+ }\r
+ end\r
+ line += 1\r
+ end\r
+ end\r
+\r
+ def format x, y\r
+ "(#{(x * 100).to_i / 100}, #{(y * 100).to_i / 100})"\r
+ end\r
+ \r
+ def get_css\r
+ return <<EOL\r
+/* default line styles */\r
+.line1{\r
+ fill: none;\r
+ stroke: #ff0000;\r
+ stroke-width: 1px; \r
+}\r
+.line2{\r
+ fill: none;\r
+ stroke: #0000ff;\r
+ stroke-width: 1px; \r
+}\r
+.line3{\r
+ fill: none;\r
+ stroke: #00ff00;\r
+ stroke-width: 1px; \r
+}\r
+.line4{\r
+ fill: none;\r
+ stroke: #ffcc00;\r
+ stroke-width: 1px; \r
+}\r
+.line5{\r
+ fill: none;\r
+ stroke: #00ccff;\r
+ stroke-width: 1px; \r
+}\r
+.line6{\r
+ fill: none;\r
+ stroke: #ff00ff;\r
+ stroke-width: 1px; \r
+}\r
+.line7{\r
+ fill: none;\r
+ stroke: #00ffff;\r
+ stroke-width: 1px; \r
+}\r
+.line8{\r
+ fill: none;\r
+ stroke: #ffff00;\r
+ stroke-width: 1px; \r
+}\r
+.line9{\r
+ fill: none;\r
+ stroke: #ccc6666;\r
+ stroke-width: 1px; \r
+}\r
+.line10{\r
+ fill: none;\r
+ stroke: #663399;\r
+ stroke-width: 1px; \r
+}\r
+.line11{\r
+ fill: none;\r
+ stroke: #339900;\r
+ stroke-width: 1px; \r
+}\r
+.line12{\r
+ fill: none;\r
+ stroke: #9966FF;\r
+ stroke-width: 1px; \r
+}\r
+/* default fill styles */\r
+.fill1{\r
+ fill: #cc0000;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill2{\r
+ fill: #0000cc;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill3{\r
+ fill: #00cc00;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill4{\r
+ fill: #ffcc00;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill5{\r
+ fill: #00ccff;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill6{\r
+ fill: #ff00ff;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill7{\r
+ fill: #00ffff;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill8{\r
+ fill: #ffff00;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill9{\r
+ fill: #cc6666;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill10{\r
+ fill: #663399;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill11{\r
+ fill: #339900;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+.fill12{\r
+ fill: #9966FF;\r
+ fill-opacity: 0.2;\r
+ stroke: none;\r
+}\r
+/* default line styles */\r
+.key1,.dataPoint1{\r
+ fill: #ff0000;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key2,.dataPoint2{\r
+ fill: #0000ff;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key3,.dataPoint3{\r
+ fill: #00ff00;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key4,.dataPoint4{\r
+ fill: #ffcc00;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key5,.dataPoint5{\r
+ fill: #00ccff;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key6,.dataPoint6{\r
+ fill: #ff00ff;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key7,.dataPoint7{\r
+ fill: #00ffff;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key8,.dataPoint8{\r
+ fill: #ffff00;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key9,.dataPoint9{\r
+ fill: #cc6666;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key10,.dataPoint10{\r
+ fill: #663399;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key11,.dataPoint11{\r
+ fill: #339900;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+.key12,.dataPoint12{\r
+ fill: #9966FF;\r
+ stroke: none;\r
+ stroke-width: 1px; \r
+}\r
+EOL\r
+ end\r
+\r
+ end\r
+ end\r
+end\r
-require 'SVG/Graph/Plot'
-require 'parsedate'
-
-module SVG
- module Graph
- # === For creating SVG plots of scalar temporal data
- #
- # = Synopsis
- #
- # require 'SVG/Graph/TimeSeriess'
- #
- # # Data sets are x,y pairs
- # data1 = ["6/17/72", 11, "1/11/72", 7, "4/13/04 17:31", 11,
- # "9/11/01", 9, "9/1/85", 2, "9/1/88", 1, "1/15/95", 13]
- # data2 = ["8/1/73", 18, "3/1/77", 15, "10/1/98", 4,
- # "5/1/02", 14, "3/1/95", 6, "8/1/91", 12, "12/1/87", 6,
- # "5/1/84", 17, "10/1/80", 12]
- #
- # graph = SVG::Graph::TimeSeries.new( {
- # :width => 640,
- # :height => 480,
- # :graph_title => title,
- # :show_graph_title => true,
- # :no_css => true,
- # :key => true,
- # :scale_x_integers => true,
- # :scale_y_integers => true,
- # :min_x_value => 0,
- # :min_y_value => 0,
- # :show_data_labels => true,
- # :show_x_guidelines => true,
- # :show_x_title => true,
- # :x_title => "Time",
- # :show_y_title => true,
- # :y_title => "Ice Cream Cones",
- # :y_title_text_direction => :bt,
- # :stagger_x_labels => true,
- # :x_label_format => "%m/%d/%y",
- # })
- #
- # graph.add_data({
- # :data => projection
- # :title => 'Projected',
- # })
- #
- # graph.add_data({
- # :data => actual,
- # :title => 'Actual',
- # })
- #
- # print graph.burn()
- #
- # = Description
- #
- # Produces a graph of temporal scalar data.
- #
- # = Examples
- #
- # http://www.germane-software/repositories/public/SVG/test/timeseries.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.
- #
- # Unlike the other types of charts, data sets must contain x,y pairs:
- #
- # [ "12:30", 2 ] # A data set with 1 point: ("12:30",2)
- # [ "01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and
- # # ("14:20",6)
- #
- # Note that multiple data sets within the same chart can differ in length,
- # and that the data in the datasets needn't be in order; they will be ordered
- # by the plot along the X-axis.
- #
- # The dates must be parseable by ParseDate, but otherwise can be
- # any order of magnitude (seconds within the hour, or years)
- #
- # = See also
- #
- # * SVG::Graph::Graph
- # * SVG::Graph::BarHorizontal
- # * SVG::Graph::Bar
- # * SVG::Graph::Line
- # * SVG::Graph::Pie
- # * SVG::Graph::Plot
- #
- # == Author
- #
- # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
- #
- # Copyright 2004 Sean E. Russell
- # This software is available under the Ruby license[LICENSE.txt]
- #
- class TimeSeries < Plot
- # In addition to the defaults set by Graph::initialize and
- # Plot::set_defaults, sets:
- # [x_label_format] '%Y-%m-%d %H:%M:%S'
- # [popup_format] '%Y-%m-%d %H:%M:%S'
- def set_defaults
- super
- init_with(
- #:max_time_span => '',
- :x_label_format => '%Y-%m-%d %H:%M:%S',
- :popup_format => '%Y-%m-%d %H:%M:%S'
- )
- end
-
- # The format string use do format the X axis labels.
- # See Time::strformat
- attr_accessor :x_label_format
- # Use this to set the spacing between dates on the axis. The value
- # must be of the form
- # "\d+ ?(days|weeks|months|years|hours|minutes|seconds)?"
- #
- # EG:
- #
- # graph.timescale_divisions = "2 weeks"
- #
- # will cause the chart to try to divide the X axis up into segments of
- # two week periods.
- attr_accessor :timescale_divisions
- # The formatting used for the popups. See x_label_format
- attr_accessor :popup_format
-
- # Add data to the plot.
- #
- # d1 = [ "12:30", 2 ] # A data set with 1 point: ("12:30",2)
- # d2 = [ "01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and
- # # ("14:20",6)
- # graph.add_data(
- # :data => d1,
- # :title => 'One'
- # )
- # graph.add_data(
- # :data => d2,
- # :title => 'Two'
- # )
- #
- # Note that the data must be in time,value pairs, and that the date format
- # may be any date that is parseable by ParseDate.
- def add_data data
- @data = [] unless @data
-
- raise "No data provided by #{conf.inspect}" unless data[:data] and
- data[:data].kind_of? Array
- raise "Data supplied must be x,y pairs! "+
- "The data provided contained an odd set of "+
- "data points" unless data[:data].length % 2 == 0
- return if data[:data].length == 0
-
-
- x = []
- y = []
- data[:data].each_index {|i|
- if i%2 == 0
- arr = ParseDate.parsedate( data[:data][i] )
- t = Time.local( *arr[0,6].compact )
- x << t.to_i
- else
- y << data[:data][i]
- end
- }
- sort( x, y )
- data[:data] = [x,y]
- @data << data
- end
-
-
- protected
-
- def min_x_value=(value)
- arr = ParseDate.parsedate( value )
- @min_x_value = Time.local( *arr[0,6].compact ).to_i
- end
-
-
- def format x, y
- Time.at( x ).strftime( popup_format )
- end
-
- def get_x_labels
- get_x_values.collect { |v| Time.at(v).strftime( x_label_format ) }
- end
-
- private
- def get_x_values
- rv = []
- min, max, scale_division = x_range
- if timescale_divisions
- timescale_divisions =~ /(\d+) ?(days|weeks|months|years|hours|minutes|seconds)?/
- division_units = $2 ? $2 : "days"
- amount = $1.to_i
- if amount
- step = nil
- case division_units
- when "months"
- cur = min
- while cur < max
- rv << cur
- arr = Time.at( cur ).to_a
- arr[4] += amount
- if arr[4] > 12
- arr[5] += (arr[4] / 12).to_i
- arr[4] = (arr[4] % 12)
- end
- cur = Time.local(*arr).to_i
- end
- when "years"
- cur = min
- while cur < max
- rv << cur
- arr = Time.at( cur ).to_a
- arr[5] += amount
- cur = Time.local(*arr).to_i
- end
- when "weeks"
- step = 7 * 24 * 60 * 60 * amount
- when "days"
- step = 24 * 60 * 60 * amount
- when "hours"
- step = 60 * 60 * amount
- when "minutes"
- step = 60 * amount
- when "seconds"
- step = amount
- end
- min.step( max, step ) {|v| rv << v} if step
-
- return rv
- end
- end
- min.step( max, scale_division ) {|v| rv << v}
- return rv
- end
- end
- end
-end
+require 'SVG/Graph/Plot'\r
+require 'parsedate'\r
+\r
+module SVG\r
+ module Graph\r
+ # === For creating SVG plots of scalar temporal data\r
+ # \r
+ # = Synopsis\r
+ # \r
+ # require 'SVG/Graph/TimeSeriess'\r
+ # \r
+ # # Data sets are x,y pairs\r
+ # data1 = ["6/17/72", 11, "1/11/72", 7, "4/13/04 17:31", 11, \r
+ # "9/11/01", 9, "9/1/85", 2, "9/1/88", 1, "1/15/95", 13]\r
+ # data2 = ["8/1/73", 18, "3/1/77", 15, "10/1/98", 4, \r
+ # "5/1/02", 14, "3/1/95", 6, "8/1/91", 12, "12/1/87", 6, \r
+ # "5/1/84", 17, "10/1/80", 12]\r
+ #\r
+ # graph = SVG::Graph::TimeSeries.new( {\r
+ # :width => 640,\r
+ # :height => 480,\r
+ # :graph_title => title,\r
+ # :show_graph_title => true,\r
+ # :no_css => true,\r
+ # :key => true,\r
+ # :scale_x_integers => true,\r
+ # :scale_y_integers => true,\r
+ # :min_x_value => 0,\r
+ # :min_y_value => 0,\r
+ # :show_data_labels => true,\r
+ # :show_x_guidelines => true,\r
+ # :show_x_title => true,\r
+ # :x_title => "Time",\r
+ # :show_y_title => true,\r
+ # :y_title => "Ice Cream Cones",\r
+ # :y_title_text_direction => :bt,\r
+ # :stagger_x_labels => true,\r
+ # :x_label_format => "%m/%d/%y",\r
+ # })\r
+ # \r
+ # graph.add_data({\r
+ # :data => projection\r
+ # :title => 'Projected',\r
+ # })\r
+ # \r
+ # graph.add_data({\r
+ # :data => actual,\r
+ # :title => 'Actual',\r
+ # })\r
+ # \r
+ # print graph.burn()\r
+ #\r
+ # = Description\r
+ # \r
+ # Produces a graph of temporal scalar data.\r
+ # \r
+ # = Examples\r
+ #\r
+ # http://www.germane-software/repositories/public/SVG/test/timeseries.rb\r
+ # \r
+ # = Notes\r
+ # \r
+ # The default stylesheet handles upto 10 data sets, if you\r
+ # use more you must create your own stylesheet and add the\r
+ # additional settings for the extra data sets. You will know\r
+ # if you go over 10 data sets as they will have no style and\r
+ # be in black.\r
+ #\r
+ # Unlike the other types of charts, data sets must contain x,y pairs:\r
+ #\r
+ # [ "12:30", 2 ] # A data set with 1 point: ("12:30",2)\r
+ # [ "01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and \r
+ # # ("14:20",6) \r
+ #\r
+ # Note that multiple data sets within the same chart can differ in length, \r
+ # and that the data in the datasets needn't be in order; they will be ordered\r
+ # by the plot along the X-axis.\r
+ # \r
+ # The dates must be parseable by ParseDate, but otherwise can be\r
+ # any order of magnitude (seconds within the hour, or years)\r
+ # \r
+ # = See also\r
+ # \r
+ # * SVG::Graph::Graph\r
+ # * SVG::Graph::BarHorizontal\r
+ # * SVG::Graph::Bar\r
+ # * SVG::Graph::Line\r
+ # * SVG::Graph::Pie\r
+ # * SVG::Graph::Plot\r
+ #\r
+ # == Author\r
+ #\r
+ # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>\r
+ #\r
+ # Copyright 2004 Sean E. Russell\r
+ # This software is available under the Ruby license[LICENSE.txt]\r
+ #\r
+ class TimeSeries < Plot\r
+ # In addition to the defaults set by Graph::initialize and\r
+ # Plot::set_defaults, sets:\r
+ # [x_label_format] '%Y-%m-%d %H:%M:%S'\r
+ # [popup_format] '%Y-%m-%d %H:%M:%S'\r
+ def set_defaults\r
+ super\r
+ init_with(\r
+ #:max_time_span => '',\r
+ :x_label_format => '%Y-%m-%d %H:%M:%S',\r
+ :popup_format => '%Y-%m-%d %H:%M:%S'\r
+ )\r
+ end\r
+\r
+ # The format string use do format the X axis labels.\r
+ # See Time::strformat\r
+ attr_accessor :x_label_format\r
+ # Use this to set the spacing between dates on the axis. The value\r
+ # must be of the form \r
+ # "\d+ ?(days|weeks|months|years|hours|minutes|seconds)?"\r
+ # \r
+ # EG:\r
+ #\r
+ # graph.timescale_divisions = "2 weeks"\r
+ #\r
+ # will cause the chart to try to divide the X axis up into segments of\r
+ # two week periods.\r
+ attr_accessor :timescale_divisions\r
+ # The formatting used for the popups. See x_label_format\r
+ attr_accessor :popup_format\r
+\r
+ # Add data to the plot.\r
+ #\r
+ # d1 = [ "12:30", 2 ] # A data set with 1 point: ("12:30",2)\r
+ # d2 = [ "01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and \r
+ # # ("14:20",6) \r
+ # graph.add_data( \r
+ # :data => d1,\r
+ # :title => 'One'\r
+ # )\r
+ # graph.add_data(\r
+ # :data => d2,\r
+ # :title => 'Two'\r
+ # )\r
+ #\r
+ # Note that the data must be in time,value pairs, and that the date format\r
+ # may be any date that is parseable by ParseDate.\r
+ def add_data data\r
+ @data = [] unless @data\r
+ \r
+ raise "No data provided by #{@data.inspect}" unless data[:data] and\r
+ data[:data].kind_of? Array\r
+ raise "Data supplied must be x,y pairs! "+\r
+ "The data provided contained an odd set of "+\r
+ "data points" unless data[:data].length % 2 == 0\r
+ return if data[:data].length == 0\r
+\r
+\r
+ x = []\r
+ y = []\r
+ data[:data].each_index {|i|\r
+ if i%2 == 0\r
+ arr = ParseDate.parsedate( data[:data][i] )\r
+ t = Time.local( *arr[0,6].compact )\r
+ x << t.to_i\r
+ else\r
+ y << data[:data][i]\r
+ end\r
+ }\r
+ sort( x, y )\r
+ data[:data] = [x,y]\r
+ @data << data\r
+ end\r
+\r
+\r
+ protected\r
+\r
+ def min_x_value=(value)\r
+ arr = ParseDate.parsedate( value )\r
+ @min_x_value = Time.local( *arr[0,6].compact ).to_i\r
+ end\r
+\r
+\r
+ def format x, y\r
+ Time.at( x ).strftime( popup_format )\r
+ end\r
+\r
+ def get_x_labels\r
+ get_x_values.collect { |v| Time.at(v).strftime( x_label_format ) }\r
+ end\r
+ \r
+ private\r
+ def get_x_values\r
+ rv = []\r
+ min, max, scale_division = x_range\r
+ if timescale_divisions\r
+ timescale_divisions =~ /(\d+) ?(day|week|month|year|hour|minute|second)?/\r
+ division_units = $2 ? $2 : "day"\r
+ amount = $1.to_i\r
+ if amount\r
+ step = nil\r
+ case division_units\r
+ when "month"\r
+ cur = min\r
+ while cur < max\r
+ rv << cur\r
+ arr = Time.at( cur ).to_a\r
+ arr[4] += amount\r
+ if arr[4] > 12\r
+ arr[5] += (arr[4] / 12).to_i\r
+ arr[4] = (arr[4] % 12)\r
+ end\r
+ cur = Time.local(*arr).to_i\r
+ end\r
+ when "year"\r
+ cur = min\r
+ while cur < max\r
+ rv << cur\r
+ arr = Time.at( cur ).to_a\r
+ arr[5] += amount\r
+ cur = Time.local(*arr).to_i\r
+ end\r
+ when "week"\r
+ step = 7 * 24 * 60 * 60 * amount\r
+ when "day"\r
+ step = 24 * 60 * 60 * amount\r
+ when "hour"\r
+ step = 60 * 60 * amount\r
+ when "minute"\r
+ step = 60 * amount\r
+ when "second"\r
+ step = amount\r
+ end\r
+ min.step( max, step ) {|v| rv << v} if step\r
+\r
+ return rv\r
+ end\r
+ end\r
+ min.step( max, scale_division ) {|v| rv << v}\r
+ return rv\r
+ end\r
+ end\r
+ end\r
+end\r