Update SVG library to latest stable (0.6.1) (#3056).

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/trunk@2642 e93f8b46-1217-0410-a6f0-8f06a7374b81
This commit is contained in:
Jean-Philippe Lang 2009-03-30 19:58:17 +00:00
parent 8d6d9a80d2
commit c9c269abf7
7 changed files with 2550 additions and 2519 deletions

View File

@ -1,137 +1,148 @@
require 'rexml/document' require 'rexml/document'
require 'SVG/Graph/Graph' require 'SVG/Graph/Graph'
require 'SVG/Graph/BarBase' require 'SVG/Graph/BarBase'
module SVG module SVG
module Graph module Graph
# === Create presentation quality SVG bar graphs easily # === Create presentation quality SVG bar graphs easily
# #
# = Synopsis # = Synopsis
# #
# require 'SVG/Graph/Bar' # require 'SVG/Graph/Bar'
# #
# fields = %w(Jan Feb Mar); # fields = %w(Jan Feb Mar);
# data_sales_02 = [12, 45, 21] # data_sales_02 = [12, 45, 21]
# #
# graph = SVG::Graph::Bar.new( # graph = SVG::Graph::Bar.new(
# :height => 500, # :height => 500,
# :width => 300, # :width => 300,
# :fields => fields # :fields => fields
# ) # )
# #
# graph.add_data( # graph.add_data(
# :data => data_sales_02, # :data => data_sales_02,
# :title => 'Sales 2002' # :title => 'Sales 2002'
# ) # )
# #
# print "Content-type: image/svg+xml\r\n\r\n" # print "Content-type: image/svg+xml\r\n\r\n"
# print graph.burn # print graph.burn
# #
# = Description # = Description
# #
# This object aims to allow you to easily create high quality # 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 # 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 # 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 - # 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. # with or without a key, data elements at each point, title, subtitle etc.
# #
# = Notes # = Notes
# #
# The default stylesheet handles upto 12 data sets, if you # The default stylesheet handles upto 12 data sets, if you
# use more you must create your own stylesheet and add the # use more you must create your own stylesheet and add the
# additional settings for the extra data sets. You will know # additional settings for the extra data sets. You will know
# if you go over 12 data sets as they will have no style and # if you go over 12 data sets as they will have no style and
# be in black. # be in black.
# #
# = Examples # = Examples
# #
# * http://germane-software.com/repositories/public/SVG/test/test.rb # * http://germane-software.com/repositories/public/SVG/test/test.rb
# #
# = See also # = See also
# #
# * SVG::Graph::Graph # * SVG::Graph::Graph
# * SVG::Graph::BarHorizontal # * SVG::Graph::BarHorizontal
# * SVG::Graph::Line # * SVG::Graph::Line
# * SVG::Graph::Pie # * SVG::Graph::Pie
# * SVG::Graph::Plot # * SVG::Graph::Plot
# * SVG::Graph::TimeSeries # * SVG::Graph::TimeSeries
class Bar < BarBase class Bar < BarBase
include REXML include REXML
# See Graph::initialize and BarBase::set_defaults # See Graph::initialize and BarBase::set_defaults
def set_defaults def set_defaults
super super
self.top_align = self.top_font = 1 self.top_align = self.top_font = 1
end end
protected protected
def get_x_labels def get_x_labels
@config[:fields] @config[:fields]
end end
def get_y_labels def get_y_labels
maxvalue = max_value maxvalue = max_value
minvalue = min_value minvalue = min_value
range = maxvalue - minvalue range = maxvalue - minvalue
top_pad = range == 0 ? 10 : range / 20.0 top_pad = range == 0 ? 10 : range / 20.0
scale_range = (maxvalue + top_pad) - minvalue scale_range = (maxvalue + top_pad) - minvalue
scale_division = scale_divisions || (scale_range / 10.0) scale_division = scale_divisions || (scale_range / 10.0)
if scale_integers if scale_integers
scale_division = scale_division < 1 ? 1 : scale_division.round scale_division = scale_division < 1 ? 1 : scale_division.round
end end
rv = [] rv = []
maxvalue = maxvalue%scale_division == 0 ? maxvalue = maxvalue%scale_division == 0 ?
maxvalue : maxvalue + scale_division maxvalue : maxvalue + scale_division
minvalue.step( maxvalue, scale_division ) {|v| rv << v} minvalue.step( maxvalue, scale_division ) {|v| rv << v}
return rv return rv
end end
def x_label_offset( width ) def x_label_offset( width )
width / 2.0 width / 2.0
end end
def draw_data def draw_data
fieldwidth = field_width minvalue = min_value
maxvalue = max_value fieldwidth = field_width
minvalue = min_value
unit_size = (@graph_height.to_f - font_size*2*top_font) /
fieldheight = (@graph_height.to_f - font_size*2*top_font) / (get_y_labels.max - get_y_labels.min)
(get_y_labels.max - get_y_labels.min) bargap = bar_gap ? (fieldwidth < 10 ? fieldwidth / 2 : 10) : 0
bargap = bar_gap ? (fieldwidth < 10 ? fieldwidth / 2 : 10) : 0
bar_width = fieldwidth - bargap
subbar_width = fieldwidth - bargap bar_width /= @data.length if stack == :side
subbar_width /= @data.length if stack == :side x_mod = (@graph_width-bargap)/2 - (stack==:side ? bar_width/2 : 0)
x_mod = (@graph_width-bargap)/2 - (stack==:side ? subbar_width/2 : 0)
# Y1 bottom = @graph_height
p2 = @graph_height
# to X2 field_count = 0
field_count = 0 @config[:fields].each_index { |i|
@config[:fields].each_index { |i| dataset_count = 0
dataset_count = 0 for dataset in @data
for dataset in @data
# X1 # cases (assume 0 = +ve):
p1 = (fieldwidth * field_count) # value min length
# to Y2 # +ve +ve value - min
p3 = @graph_height - ((dataset[:data][i] - minvalue) * fieldheight) # +ve -ve value - 0
p1 += subbar_width * dataset_count if stack == :side # -ve -ve value.abs - 0
@graph.add_element( "path", {
"class" => "fill#{dataset_count+1}", value = dataset[:data][i]
"d" => "M#{p1} #{p2} V#{p3} h#{subbar_width} V#{p2} Z"
}) left = (fieldwidth * field_count)
make_datapoint_text(
p1 + subbar_width/2.0, length = (value.abs - (minvalue > 0 ? minvalue : 0)) * unit_size
p3 - 6, # top is 0 if value is negative
dataset[:data][i].to_s) top = bottom - (((value < 0 ? 0 : value) - minvalue) * unit_size)
dataset_count += 1 left += bar_width * dataset_count if stack == :side
end
field_count += 1 @graph.add_element( "rect", {
} "x" => left.to_s,
end "y" => top.to_s,
end "width" => bar_width.to_s,
end "height" => length.to_s,
end "class" => "fill#{dataset_count+1}"
})
make_datapoint_text(left + bar_width/2.0, top - 6, value.to_s)
dataset_count += 1
end
field_count += 1
}
end
end
end
end

View File

@ -1,140 +1,139 @@
require 'rexml/document' require 'rexml/document'
require 'SVG/Graph/Graph' require 'SVG/Graph/Graph'
module SVG module SVG
module Graph module Graph
# = Synopsis # = Synopsis
# #
# A superclass for bar-style graphs. Do not attempt to instantiate # A superclass for bar-style graphs. Do not attempt to instantiate
# directly; use one of the subclasses instead. # directly; use one of the subclasses instead.
# #
# = Author # = Author
# #
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom> # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
# #
# Copyright 2004 Sean E. Russell # Copyright 2004 Sean E. Russell
# This software is available under the Ruby license[LICENSE.txt] # This software is available under the Ruby license[LICENSE.txt]
# #
class BarBase < SVG::Graph::Graph class BarBase < SVG::Graph::Graph
# Ensures that :fields are provided in the configuration. # Ensures that :fields are provided in the configuration.
def initialize config def initialize config
raise "fields was not supplied or is empty" unless config[:fields] && raise "fields was not supplied or is empty" unless config[:fields] &&
config[:fields].kind_of?(Array) && config[:fields].kind_of?(Array) &&
config[:fields].length > 0 config[:fields].length > 0
super super
end end
# In addition to the defaults set in Graph::initialize, sets # In addition to the defaults set in Graph::initialize, sets
# [bar_gap] true # [bar_gap] true
# [stack] :overlap # [stack] :overlap
def set_defaults def set_defaults
init_with( :bar_gap => true, :stack => :overlap ) init_with( :bar_gap => true, :stack => :overlap )
end end
# Whether to have a gap between the bars or not, default # Whether to have a gap between the bars or not, default
# is true, set to false if you don't want gaps. # is true, set to false if you don't want gaps.
attr_accessor :bar_gap attr_accessor :bar_gap
# How to stack data sets. :overlap overlaps bars with # How to stack data sets. :overlap overlaps bars with
# transparent colors, :top stacks bars on top of one another, # transparent colors, :top stacks bars on top of one another,
# :side stacks the bars side-by-side. Defaults to :overlap. # :side stacks the bars side-by-side. Defaults to :overlap.
attr_accessor :stack attr_accessor :stack
protected protected
def max_value def max_value
return @data.collect{|x| x[:data].max}.max @data.collect{|x| x[:data].max}.max
end end
def min_value def min_value
min = 0 min = 0
if min_scale_value.nil?
if (min_scale_value.nil? == false) then min = @data.collect{|x| x[:data].min}.min
min = min_scale_value min = min > 0 ? 0 : min
else else
min = @data.collect{|x| x[:data].min}.min min = min_scale_value
end end
return min
return min end
end
def get_css
def get_css return <<EOL
return <<EOL /* default fill styles for multiple datasets (probably only use a single dataset on this graph though) */
/* default fill styles for multiple datasets (probably only use a single dataset on this graph though) */ .key1,.fill1{
.key1,.fill1{ fill: #ff0000;
fill: #ff0000; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 0.5px;
stroke-width: 0.5px; }
} .key2,.fill2{
.key2,.fill2{ fill: #0000ff;
fill: #0000ff; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key3,.fill3{
.key3,.fill3{ fill: #00ff00;
fill: #00ff00; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key4,.fill4{
.key4,.fill4{ fill: #ffcc00;
fill: #ffcc00; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key5,.fill5{
.key5,.fill5{ fill: #00ccff;
fill: #00ccff; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key6,.fill6{
.key6,.fill6{ fill: #ff00ff;
fill: #ff00ff; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key7,.fill7{
.key7,.fill7{ fill: #00ffff;
fill: #00ffff; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key8,.fill8{
.key8,.fill8{ fill: #ffff00;
fill: #ffff00; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key9,.fill9{
.key9,.fill9{ fill: #cc6666;
fill: #cc6666; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key10,.fill10{
.key10,.fill10{ fill: #663399;
fill: #663399; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key11,.fill11{
.key11,.fill11{ fill: #339900;
fill: #339900; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} .key12,.fill12{
.key12,.fill12{ fill: #9966FF;
fill: #9966FF; fill-opacity: 0.5;
fill-opacity: 0.5; stroke: none;
stroke: none; stroke-width: 1px;
stroke-width: 1px; }
} EOL
EOL end
end end
end end
end end
end

View File

@ -1,136 +1,149 @@
require 'rexml/document' require 'rexml/document'
require 'SVG/Graph/BarBase' require 'SVG/Graph/BarBase'
module SVG module SVG
module Graph module Graph
# === Create presentation quality SVG horitonzal bar graphs easily # === Create presentation quality SVG horitonzal bar graphs easily
# #
# = Synopsis # = Synopsis
# #
# require 'SVG/Graph/BarHorizontal' # require 'SVG/Graph/BarHorizontal'
# #
# fields = %w(Jan Feb Mar) # fields = %w(Jan Feb Mar)
# data_sales_02 = [12, 45, 21] # data_sales_02 = [12, 45, 21]
# #
# graph = SVG::Graph::BarHorizontal.new({ # graph = SVG::Graph::BarHorizontal.new({
# :height => 500, # :height => 500,
# :width => 300, # :width => 300,
# :fields => fields, # :fields => fields,
# }) # })
# #
# graph.add_data({ # graph.add_data({
# :data => data_sales_02, # :data => data_sales_02,
# :title => 'Sales 2002', # :title => 'Sales 2002',
# }) # })
# #
# print "Content-type: image/svg+xml\r\n\r\n" # print "Content-type: image/svg+xml\r\n\r\n"
# print graph.burn # print graph.burn
# #
# = Description # = Description
# #
# This object aims to allow you to easily create high quality # This object aims to allow you to easily create high quality
# SVG horitonzal bar graphs. You can either use the default style sheet # SVG horitonzal bar graphs. You can either use the default style sheet
# or supply your own. Either way there are many options which can # or supply your own. Either way there are many options which can
# be configured to give you control over how the graph is # be configured to give you control over how the graph is
# generated - with or without a key, data elements at each point, # generated - with or without a key, data elements at each point,
# title, subtitle etc. # title, subtitle etc.
# #
# = Examples # = Examples
# #
# * http://germane-software.com/repositories/public/SVG/test/test.rb # * http://germane-software.com/repositories/public/SVG/test/test.rb
# #
# = See also # = See also
# #
# * SVG::Graph::Graph # * SVG::Graph::Graph
# * SVG::Graph::Bar # * SVG::Graph::Bar
# * SVG::Graph::Line # * SVG::Graph::Line
# * SVG::Graph::Pie # * SVG::Graph::Pie
# * SVG::Graph::Plot # * SVG::Graph::Plot
# * SVG::Graph::TimeSeries # * SVG::Graph::TimeSeries
# #
# == Author # == Author
# #
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom> # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
# #
# Copyright 2004 Sean E. Russell # Copyright 2004 Sean E. Russell
# This software is available under the Ruby license[LICENSE.txt] # This software is available under the Ruby license[LICENSE.txt]
# #
class BarHorizontal < BarBase class BarHorizontal < BarBase
# In addition to the defaults set in BarBase::set_defaults, sets # In addition to the defaults set in BarBase::set_defaults, sets
# [rotate_y_labels] true # [rotate_y_labels] true
# [show_x_guidelines] true # [show_x_guidelines] true
# [show_y_guidelines] false # [show_y_guidelines] false
def set_defaults def set_defaults
super super
init_with( init_with(
:rotate_y_labels => true, :rotate_y_labels => true,
:show_x_guidelines => true, :show_x_guidelines => true,
:show_y_guidelines => false :show_y_guidelines => false
) )
self.right_align = self.right_font = 1 self.right_align = self.right_font = 1
end end
protected protected
def get_x_labels def get_x_labels
maxvalue = max_value maxvalue = max_value
minvalue = min_value minvalue = min_value
range = maxvalue - minvalue range = maxvalue - minvalue
top_pad = range == 0 ? 10 : range / 20.0 top_pad = range == 0 ? 10 : range / 20.0
scale_range = (maxvalue + top_pad) - minvalue scale_range = (maxvalue + top_pad) - minvalue
scale_division = scale_divisions || (scale_range / 10.0) scale_division = scale_divisions || (scale_range / 10.0)
if scale_integers if scale_integers
scale_division = scale_division < 1 ? 1 : scale_division.round scale_division = scale_division < 1 ? 1 : scale_division.round
end end
rv = [] rv = []
maxvalue = maxvalue%scale_division == 0 ? maxvalue = maxvalue%scale_division == 0 ?
maxvalue : maxvalue + scale_division maxvalue : maxvalue + scale_division
minvalue.step( maxvalue, scale_division ) {|v| rv << v} minvalue.step( maxvalue, scale_division ) {|v| rv << v}
return rv return rv
end end
def get_y_labels def get_y_labels
@config[:fields] @config[:fields]
end end
def y_label_offset( height ) def y_label_offset( height )
height / -2.0 height / -2.0
end end
def draw_data def draw_data
minvalue = min_value minvalue = min_value
fieldheight = field_height fieldheight = field_height
fieldwidth = (@graph_width.to_f - font_size*2*right_font ) /
(get_x_labels.max - get_x_labels.min ) unit_size = (@graph_width.to_f - font_size*2*right_font ) /
bargap = bar_gap ? (fieldheight < 10 ? fieldheight / 2 : 10) : 0 (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 bar_height = fieldheight - bargap
bar_height /= @data.length if stack == :side
field_count = 1 y_mod = (bar_height / 2) + (font_size / 2)
y_mod = (subbar_height / 2) + (font_size / 2)
@config[:fields].each_index { |i| field_count = 1
dataset_count = 0 @config[:fields].each_index { |i|
for dataset in @data dataset_count = 0
y = @graph_height - (fieldheight * field_count) for dataset in @data
y += (subbar_height * dataset_count) if stack == :side value = dataset[:data][i]
x = (dataset[:data][i] - minvalue) * fieldwidth
top = @graph_height - (fieldheight * field_count)
@graph.add_element( "path", { top += (bar_height * dataset_count) if stack == :side
"d" => "M0 #{y} H#{x} v#{subbar_height} H0 Z", # cases (assume 0 = +ve):
"class" => "fill#{dataset_count+1}" # value min length left
}) # +ve +ve value.abs - min minvalue.abs
make_datapoint_text( # +ve -ve value.abs - 0 minvalue.abs
x+5, y+y_mod, dataset[:data][i], "text-anchor: start; " # -ve -ve value.abs - 0 minvalue.abs + value
) length = (value.abs - (minvalue > 0 ? minvalue : 0)) * unit_size
dataset_count += 1 left = (minvalue.abs + (value < 0 ? value : 0)) * unit_size
end
field_count += 1 @graph.add_element( "rect", {
} "x" => left.to_s,
end "y" => top.to_s,
end "width" => length.to_s,
end "height" => bar_height.to_s,
end "class" => "fill#{dataset_count+1}"
})
make_datapoint_text(
left+length+5, top+y_mod, value, "text-anchor: start; "
)
dataset_count += 1
end
field_count += 1
}
end
end
end
end

File diff suppressed because it is too large Load Diff

View File

@ -1,394 +1,395 @@
require 'SVG/Graph/Graph' require 'SVG/Graph/Graph'
module SVG module SVG
module Graph module Graph
# === Create presentation quality SVG pie graphs easily # === Create presentation quality SVG pie graphs easily
# #
# == Synopsis # == Synopsis
# #
# require 'SVG/Graph/Pie' # require 'SVG/Graph/Pie'
# #
# fields = %w(Jan Feb Mar) # fields = %w(Jan Feb Mar)
# data_sales_02 = [12, 45, 21] # data_sales_02 = [12, 45, 21]
# #
# graph = SVG::Graph::Pie.new({ # graph = SVG::Graph::Pie.new({
# :height => 500, # :height => 500,
# :width => 300, # :width => 300,
# :fields => fields, # :fields => fields,
# }) # })
# #
# graph.add_data({ # graph.add_data({
# :data => data_sales_02, # :data => data_sales_02,
# :title => 'Sales 2002', # :title => 'Sales 2002',
# }) # })
# #
# print "Content-type: image/svg+xml\r\n\r\n" # print "Content-type: image/svg+xml\r\n\r\n"
# print graph.burn(); # print graph.burn();
# #
# == Description # == Description
# #
# This object aims to allow you to easily create high quality # This object aims to allow you to easily create high quality
# SVG pie graphs. You can either use the default style sheet # SVG pie graphs. You can either use the default style sheet
# or supply your own. Either way there are many options which can # or supply your own. Either way there are many options which can
# be configured to give you control over how the graph is # be configured to give you control over how the graph is
# generated - with or without a key, display percent on pie chart, # generated - with or without a key, display percent on pie chart,
# title, subtitle etc. # title, subtitle etc.
# #
# = Examples # = Examples
# #
# http://www.germane-software/repositories/public/SVG/test/single.rb # http://www.germane-software/repositories/public/SVG/test/single.rb
# #
# == See also # == See also
# #
# * SVG::Graph::Graph # * SVG::Graph::Graph
# * SVG::Graph::BarHorizontal # * SVG::Graph::BarHorizontal
# * SVG::Graph::Bar # * SVG::Graph::Bar
# * SVG::Graph::Line # * SVG::Graph::Line
# * SVG::Graph::Plot # * SVG::Graph::Plot
# * SVG::Graph::TimeSeries # * SVG::Graph::TimeSeries
# #
# == Author # == Author
# #
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom> # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
# #
# Copyright 2004 Sean E. Russell # Copyright 2004 Sean E. Russell
# This software is available under the Ruby license[LICENSE.txt] # This software is available under the Ruby license[LICENSE.txt]
# #
class Pie < Graph class Pie < Graph
# Defaults are those set by Graph::initialize, and # Defaults are those set by Graph::initialize, and
# [show_shadow] true # [show_shadow] true
# [shadow_offset] 10 # [shadow_offset] 10
# [show_data_labels] false # [show_data_labels] false
# [show_actual_values] false # [show_actual_values] false
# [show_percent] true # [show_percent] true
# [show_key_data_labels] true # [show_key_data_labels] true
# [show_key_actual_values] true # [show_key_actual_values] true
# [show_key_percent] false # [show_key_percent] false
# [expanded] false # [expanded] false
# [expand_greatest] false # [expand_greatest] false
# [expand_gap] 10 # [expand_gap] 10
# [show_x_labels] false # [show_x_labels] false
# [show_y_labels] false # [show_y_labels] false
# [datapoint_font_size] 12 # [datapoint_font_size] 12
def set_defaults def set_defaults
init_with( init_with(
:show_shadow => true, :show_shadow => true,
:shadow_offset => 10, :shadow_offset => 10,
:show_data_labels => false, :show_data_labels => false,
:show_actual_values => false, :show_actual_values => false,
:show_percent => true, :show_percent => true,
:show_key_data_labels => true, :show_key_data_labels => true,
:show_key_actual_values => true, :show_key_actual_values => true,
:show_key_percent => false, :show_key_percent => false,
:expanded => false, :expanded => false,
:expand_greatest => false, :expand_greatest => false,
:expand_gap => 10, :expand_gap => 10,
:show_x_labels => false, :show_x_labels => false,
:show_y_labels => false, :show_y_labels => false,
:datapoint_font_size => 12 :datapoint_font_size => 12
) )
@data = [] @data = []
end end
# Adds a data set to the graph. # Adds a data set to the graph.
# #
# graph.add_data( { :data => [1,2,3,4] } ) # graph.add_data( { :data => [1,2,3,4] } )
# #
# Note that the :title is not necessary. If multiple # Note that the :title is not necessary. If multiple
# data sets are added to the graph, the pie chart will # data sets are added to the graph, the pie chart will
# display the +sums+ of the data. EG: # display the +sums+ of the data. EG:
# #
# graph.add_data( { :data => [1,2,3,4] } ) # graph.add_data( { :data => [1,2,3,4] } )
# graph.add_data( { :data => [2,3,5,9] } ) # graph.add_data( { :data => [2,3,5,9] } )
# #
# is the same as: # is the same as:
# #
# graph.add_data( { :data => [3,5,8,13] } ) # graph.add_data( { :data => [3,5,8,13] } )
def add_data arg def add_data arg
arg[:data].each_index {|idx| arg[:data].each_index {|idx|
@data[idx] = 0 unless @data[idx] @data[idx] = 0 unless @data[idx]
@data[idx] += arg[:data][idx] @data[idx] += arg[:data][idx]
} }
end end
# If true, displays a drop shadow for the chart # If true, displays a drop shadow for the chart
attr_accessor :show_shadow attr_accessor :show_shadow
# Sets the offset of the shadow from the pie chart # Sets the offset of the shadow from the pie chart
attr_accessor :shadow_offset attr_accessor :shadow_offset
# If true, display the data labels on the chart # If true, display the data labels on the chart
attr_accessor :show_data_labels attr_accessor :show_data_labels
# If true, display the actual field values in the data labels # If true, display the actual field values in the data labels
attr_accessor :show_actual_values attr_accessor :show_actual_values
# If true, display the percentage value of each pie wedge in the data # If true, display the percentage value of each pie wedge in the data
# labels # labels
attr_accessor :show_percent attr_accessor :show_percent
# If true, display the labels in the key # If true, display the labels in the key
attr_accessor :show_key_data_labels attr_accessor :show_key_data_labels
# If true, display the actual value of the field in the key # If true, display the actual value of the field in the key
attr_accessor :show_key_actual_values attr_accessor :show_key_actual_values
# If true, display the percentage value of the wedges in the key # If true, display the percentage value of the wedges in the key
attr_accessor :show_key_percent attr_accessor :show_key_percent
# If true, "explode" the pie (put space between the wedges) # If true, "explode" the pie (put space between the wedges)
attr_accessor :expanded attr_accessor :expanded
# If true, expand the largest pie wedge # If true, expand the largest pie wedge
attr_accessor :expand_greatest attr_accessor :expand_greatest
# The amount of space between expanded wedges # The amount of space between expanded wedges
attr_accessor :expand_gap attr_accessor :expand_gap
# The font size of the data point labels # The font size of the data point labels
attr_accessor :datapoint_font_size attr_accessor :datapoint_font_size
protected protected
def add_defs defs def add_defs defs
gradient = defs.add_element( "filter", { gradient = defs.add_element( "filter", {
"id"=>"dropshadow", "id"=>"dropshadow",
"width" => "1.2", "width" => "1.2",
"height" => "1.2", "height" => "1.2",
} ) } )
gradient.add_element( "feGaussianBlur", { gradient.add_element( "feGaussianBlur", {
"stdDeviation" => "4", "stdDeviation" => "4",
"result" => "blur" "result" => "blur"
}) })
end end
# We don't need the graph # We don't need the graph
def draw_graph def draw_graph
end end
def get_y_labels def get_y_labels
[""] [""]
end end
def get_x_labels def get_x_labels
[""] [""]
end end
def keys def keys
total = 0 total = 0
max_value = 0 max_value = 0
@data.each {|x| total += x } @data.each {|x| total += x }
percent_scale = 100.0 / total percent_scale = 100.0 / total
count = -1 count = -1
a = @config[:fields].collect{ |x| a = @config[:fields].collect{ |x|
count += 1 count += 1
v = @data[count] v = @data[count]
perc = show_key_percent ? " "+(v * percent_scale).round.to_s+"%" : "" perc = show_key_percent ? " "+(v * percent_scale).round.to_s+"%" : ""
x + " [" + v.to_s + "]" + perc x + " [" + v.to_s + "]" + perc
} }
end end
RADIANS = Math::PI/180 RADIANS = Math::PI/180
def draw_data def draw_data
@graph = @root.add_element( "g" ) @graph = @root.add_element( "g" )
background = @graph.add_element("g") background = @graph.add_element("g")
midground = @graph.add_element("g") midground = @graph.add_element("g")
diameter = @graph_height > @graph_width ? @graph_width : @graph_height diameter = @graph_height > @graph_width ? @graph_width : @graph_height
diameter -= expand_gap if expanded or expand_greatest diameter -= expand_gap if expanded or expand_greatest
diameter -= datapoint_font_size if show_data_labels diameter -= datapoint_font_size if show_data_labels
diameter -= 10 if show_shadow diameter -= 10 if show_shadow
radius = diameter / 2.0 radius = diameter / 2.0
xoff = (width - diameter) / 2 xoff = (width - diameter) / 2
yoff = (height - @border_bottom - diameter) yoff = (height - @border_bottom - diameter)
yoff -= 10 if show_shadow yoff -= 10 if show_shadow
@graph.attributes['transform'] = "translate( #{xoff} #{yoff} )" @graph.attributes['transform'] = "translate( #{xoff} #{yoff} )"
wedge_text_pad = 5 wedge_text_pad = 5
wedge_text_pad = 20 if show_percent and show_data_labels wedge_text_pad = 20 if show_percent and show_data_labels
total = 0 total = 0
max_value = 0 max_value = 0
@data.each {|x| @data.each {|x|
max_value = max_value < x ? x : max_value max_value = max_value < x ? x : max_value
total += x total += x
} }
percent_scale = 100.0 / total percent_scale = 100.0 / total
prev_percent = 0 prev_percent = 0
rad_mult = 3.6 * RADIANS rad_mult = 3.6 * RADIANS
@config[:fields].each_index { |count| @config[:fields].each_index { |count|
value = @data[count] value = @data[count]
percent = percent_scale * value percent = percent_scale * value
radians = prev_percent * rad_mult radians = prev_percent * rad_mult
x_start = radius+(Math.sin(radians) * radius) x_start = radius+(Math.sin(radians) * radius)
y_start = radius-(Math.cos(radians) * radius) y_start = radius-(Math.cos(radians) * radius)
radians = (prev_percent+percent) * rad_mult radians = (prev_percent+percent) * rad_mult
x_end = radius+(Math.sin(radians) * radius) x_end = radius+(Math.sin(radians) * radius)
y_end = radius-(Math.cos(radians) * radius) x_end -= 0.00001 if @data.length == 1
path = "M#{radius},#{radius} L#{x_start},#{y_start} "+ y_end = radius-(Math.cos(radians) * radius)
"A#{radius},#{radius} "+ path = "M#{radius},#{radius} L#{x_start},#{y_start} "+
"0, #{percent >= 50 ? '1' : '0'},1, "+ "A#{radius},#{radius} "+
"#{x_end} #{y_end} Z" "0, #{percent >= 50 ? '1' : '0'},1, "+
"#{x_end} #{y_end} Z"
wedge = @foreground.add_element( "path", {
"d" => path, wedge = @foreground.add_element( "path", {
"class" => "fill#{count+1}" "d" => path,
}) "class" => "fill#{count+1}"
})
translate = nil
tx = 0 translate = nil
ty = 0 tx = 0
half_percent = prev_percent + percent / 2 ty = 0
radians = half_percent * rad_mult half_percent = prev_percent + percent / 2
radians = half_percent * rad_mult
if show_shadow
shadow = background.add_element( "path", { if show_shadow
"d" => path, shadow = background.add_element( "path", {
"filter" => "url(#dropshadow)", "d" => path,
"style" => "fill: #ccc; stroke: none;" "filter" => "url(#dropshadow)",
}) "style" => "fill: #ccc; stroke: none;"
clear = midground.add_element( "path", { })
"d" => path, clear = midground.add_element( "path", {
"style" => "fill: #fff; stroke: none;" "d" => path,
}) "style" => "fill: #fff; stroke: none;"
end })
end
if expanded or (expand_greatest && value == max_value)
tx = (Math.sin(radians) * expand_gap) if expanded or (expand_greatest && value == max_value)
ty = -(Math.cos(radians) * expand_gap) tx = (Math.sin(radians) * expand_gap)
translate = "translate( #{tx} #{ty} )" ty = -(Math.cos(radians) * expand_gap)
wedge.attributes["transform"] = translate translate = "translate( #{tx} #{ty} )"
clear.attributes["transform"] = translate wedge.attributes["transform"] = translate
end clear.attributes["transform"] = translate if clear
end
if show_shadow
shadow.attributes["transform"] = if show_shadow
"translate( #{tx+shadow_offset} #{ty+shadow_offset} )" shadow.attributes["transform"] =
end "translate( #{tx+shadow_offset} #{ty+shadow_offset} )"
end
if show_data_labels and value != 0
label = "" if show_data_labels and value != 0
label += @config[:fields][count] if show_key_data_labels label = ""
label += " ["+value.to_s+"]" if show_actual_values label += @config[:fields][count] if show_key_data_labels
label += " "+percent.round.to_s+"%" if show_percent label += " ["+value.to_s+"]" if show_actual_values
label += " "+percent.round.to_s+"%" if show_percent
msr = Math.sin(radians)
mcr = Math.cos(radians) msr = Math.sin(radians)
tx = radius + (msr * radius) mcr = Math.cos(radians)
ty = radius -(mcr * radius) tx = radius + (msr * radius)
ty = radius -(mcr * radius)
if expanded or (expand_greatest && value == max_value)
tx += (msr * expand_gap) if expanded or (expand_greatest && value == max_value)
ty -= (mcr * expand_gap) tx += (msr * expand_gap)
end ty -= (mcr * expand_gap)
@foreground.add_element( "text", { end
"x" => tx.to_s, @foreground.add_element( "text", {
"y" => ty.to_s, "x" => tx.to_s,
"class" => "dataPointLabel", "y" => ty.to_s,
"style" => "stroke: #fff; stroke-width: 2;" "class" => "dataPointLabel",
}).text = label.to_s "style" => "stroke: #fff; stroke-width: 2;"
@foreground.add_element( "text", { }).text = label.to_s
"x" => tx.to_s, @foreground.add_element( "text", {
"y" => ty.to_s, "x" => tx.to_s,
"class" => "dataPointLabel", "y" => ty.to_s,
}).text = label.to_s "class" => "dataPointLabel",
end }).text = label.to_s
end
prev_percent += percent
} prev_percent += percent
end }
end
def round val, to
up = 10**to.to_f def round val, to
(val * up).to_i / up up = 10**to.to_f
end (val * up).to_i / up
end
def get_css
return <<EOL def get_css
.dataPointLabel{ return <<EOL
fill: #000000; .dataPointLabel{
text-anchor:middle; fill: #000000;
font-size: #{datapoint_font_size}px; text-anchor:middle;
font-family: "Arial", sans-serif; font-size: #{datapoint_font_size}px;
font-weight: normal; font-family: "Arial", sans-serif;
} font-weight: normal;
}
/* key - MUST match fill styles */
.key1,.fill1{ /* key - MUST match fill styles */
fill: #ff0000; .key1,.fill1{
fill-opacity: 0.7; fill: #ff0000;
stroke: none; fill-opacity: 0.7;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key2,.fill2{ }
fill: #0000ff; .key2,.fill2{
fill-opacity: 0.7; fill: #0000ff;
stroke: none; fill-opacity: 0.7;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key3,.fill3{ }
fill-opacity: 0.7; .key3,.fill3{
fill: #00ff00; fill-opacity: 0.7;
stroke: none; fill: #00ff00;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key4,.fill4{ }
fill-opacity: 0.7; .key4,.fill4{
fill: #ffcc00; fill-opacity: 0.7;
stroke: none; fill: #ffcc00;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key5,.fill5{ }
fill-opacity: 0.7; .key5,.fill5{
fill: #00ccff; fill-opacity: 0.7;
stroke: none; fill: #00ccff;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key6,.fill6{ }
fill-opacity: 0.7; .key6,.fill6{
fill: #ff00ff; fill-opacity: 0.7;
stroke: none; fill: #ff00ff;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key7,.fill7{ }
fill-opacity: 0.7; .key7,.fill7{
fill: #00ff99; fill-opacity: 0.7;
stroke: none; fill: #00ff99;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key8,.fill8{ }
fill-opacity: 0.7; .key8,.fill8{
fill: #ffff00; fill-opacity: 0.7;
stroke: none; fill: #ffff00;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key9,.fill9{ }
fill-opacity: 0.7; .key9,.fill9{
fill: #cc6666; fill-opacity: 0.7;
stroke: none; fill: #cc6666;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key10,.fill10{ }
fill-opacity: 0.7; .key10,.fill10{
fill: #663399; fill-opacity: 0.7;
stroke: none; fill: #663399;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key11,.fill11{ }
fill-opacity: 0.7; .key11,.fill11{
fill: #339900; fill-opacity: 0.7;
stroke: none; fill: #339900;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key12,.fill12{ }
fill-opacity: 0.7; .key12,.fill12{
fill: #9966FF; fill-opacity: 0.7;
stroke: none; fill: #9966FF;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
EOL }
end EOL
end end
end end
end end
end

View File

@ -1,494 +1,500 @@
require 'SVG/Graph/Graph' require 'SVG/Graph/Graph'
module SVG module SVG
module Graph module Graph
# === For creating SVG plots of scalar data # === For creating SVG plots of scalar data
# #
# = Synopsis # = Synopsis
# #
# require 'SVG/Graph/Plot' # require 'SVG/Graph/Plot'
# #
# # Data sets are x,y pairs # # Data sets are x,y pairs
# # Note that multiple data sets can differ in length, and that the # # 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 # # data in the datasets needn't be in order; they will be ordered
# # by the plot along the X-axis. # # by the plot along the X-axis.
# projection = [ # projection = [
# 6, 11, 0, 5, 18, 7, 1, 11, 13, 9, 1, 2, 19, 0, 3, 13, # 6, 11, 0, 5, 18, 7, 1, 11, 13, 9, 1, 2, 19, 0, 3, 13,
# 7, 9 # 7, 9
# ] # ]
# actual = [ # actual = [
# 0, 18, 8, 15, 9, 4, 18, 14, 10, 2, 11, 6, 14, 12, # 0, 18, 8, 15, 9, 4, 18, 14, 10, 2, 11, 6, 14, 12,
# 15, 6, 4, 17, 2, 12 # 15, 6, 4, 17, 2, 12
# ] # ]
# #
# graph = SVG::Graph::Plot.new({ # graph = SVG::Graph::Plot.new({
# :height => 500, # :height => 500,
# :width => 300, # :width => 300,
# :key => true, # :key => true,
# :scale_x_integers => true, # :scale_x_integers => true,
# :scale_y_integerrs => true, # :scale_y_integerrs => true,
# }) # })
# #
# graph.add_data({ # graph.add_data({
# :data => projection # :data => projection
# :title => 'Projected', # :title => 'Projected',
# }) # })
# #
# graph.add_data({ # graph.add_data({
# :data => actual, # :data => actual,
# :title => 'Actual', # :title => 'Actual',
# }) # })
# #
# print graph.burn() # print graph.burn()
# #
# = Description # = Description
# #
# Produces a graph of scalar data. # Produces a graph of scalar data.
# #
# This object aims to allow you to easily create high quality # 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 # 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 # 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 # 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, # generated - with or without a key, data elements at each point, title,
# subtitle etc. # subtitle etc.
# #
# = Examples # = Examples
# #
# http://www.germane-software/repositories/public/SVG/test/plot.rb # http://www.germane-software/repositories/public/SVG/test/plot.rb
# #
# = Notes # = Notes
# #
# The default stylesheet handles upto 10 data sets, if you # The default stylesheet handles upto 10 data sets, if you
# use more you must create your own stylesheet and add the # use more you must create your own stylesheet and add the
# additional settings for the extra data sets. You will know # additional settings for the extra data sets. You will know
# if you go over 10 data sets as they will have no style and # if you go over 10 data sets as they will have no style and
# be in black. # be in black.
# #
# Unlike the other types of charts, data sets must contain x,y pairs: # 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 ] # A data set with 1 point: (1,2)
# [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6) # [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6)
# #
# = See also # = See also
# #
# * SVG::Graph::Graph # * SVG::Graph::Graph
# * SVG::Graph::BarHorizontal # * SVG::Graph::BarHorizontal
# * SVG::Graph::Bar # * SVG::Graph::Bar
# * SVG::Graph::Line # * SVG::Graph::Line
# * SVG::Graph::Pie # * SVG::Graph::Pie
# * SVG::Graph::TimeSeries # * SVG::Graph::TimeSeries
# #
# == Author # == Author
# #
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom> # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
# #
# Copyright 2004 Sean E. Russell # Copyright 2004 Sean E. Russell
# This software is available under the Ruby license[LICENSE.txt] # This software is available under the Ruby license[LICENSE.txt]
# #
class Plot < Graph class Plot < Graph
# In addition to the defaults set by Graph::initialize, sets # In addition to the defaults set by Graph::initialize, sets
# [show_data_points] true # [show_data_values] true
# [area_fill] false # [show_data_points] true
# [stacked] false # [area_fill] false
def set_defaults # [stacked] false
init_with( def set_defaults
:show_data_points => true, init_with(
:area_fill => false, :show_data_values => true,
:stacked => false :show_data_points => true,
) :area_fill => false,
self.top_align = self.right_align = self.top_font = self.right_font = 1 :stacked => false
end )
self.top_align = self.right_align = self.top_font = self.right_font = 1
# Determines the scaling for the X axis divisions. end
#
# graph.scale_x_divisions = 2 # Determines the scaling for the X axis divisions.
# #
# would cause the graph to attempt to generate labels stepped by 2; EG: # graph.scale_x_divisions = 2
# 0,2,4,6,8... #
attr_accessor :scale_x_divisions # would cause the graph to attempt to generate labels stepped by 2; EG:
# Determines the scaling for the Y axis divisions. # 0,2,4,6,8...
# attr_accessor :scale_x_divisions
# graph.scale_y_divisions = 0.5 # Determines the scaling for the Y axis divisions.
# #
# would cause the graph to attempt to generate labels stepped by 0.5; EG: # graph.scale_y_divisions = 0.5
# 0, 0.5, 1, 1.5, 2, ... #
attr_accessor :scale_y_divisions # would cause the graph to attempt to generate labels stepped by 0.5; EG:
# Make the X axis labels integers # 0, 0.5, 1, 1.5, 2, ...
attr_accessor :scale_x_integers attr_accessor :scale_y_divisions
# Make the Y axis labels integers # Make the X axis labels integers
attr_accessor :scale_y_integers attr_accessor :scale_x_integers
# Fill the area under the line # Make the Y axis labels integers
attr_accessor :area_fill attr_accessor :scale_y_integers
# Show a small circle on the graph where the line # Fill the area under the line
# goes from one point to the next. attr_accessor :area_fill
attr_accessor :show_data_points # Show a small circle on the graph where the line
# Set the minimum value of the X axis # goes from one point to the next.
attr_accessor :min_x_value attr_accessor :show_data_points
# Set the minimum value of the Y axis # Set the minimum value of the X axis
attr_accessor :min_y_value 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) # Adds data to the plot. The data must be in X,Y pairs; EG
def add_data data # [ 1, 2 ] # A data set with 1 point: (1,2)
@data = [] unless @data # [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6)
def add_data data
raise "No data provided by #{conf.inspect}" unless data[:data] and @data = [] unless @data
data[:data].kind_of? Array
raise "Data supplied must be x,y pairs! "+ raise "No data provided by #{conf.inspect}" unless data[:data] and
"The data provided contained an odd set of "+ data[:data].kind_of? Array
"data points" unless data[:data].length % 2 == 0 raise "Data supplied must be x,y pairs! "+
return if data[:data].length == 0 "The data provided contained an odd set of "+
"data points" unless data[:data].length % 2 == 0
x = [] return if data[:data].length == 0
y = []
data[:data].each_index {|i| x = []
(i%2 == 0 ? x : y) << data[:data][i] y = []
} data[:data].each_index {|i|
sort( x, y ) (i%2 == 0 ? x : y) << data[:data][i]
data[:data] = [x,y] }
@data << data sort( x, y )
end data[:data] = [x,y]
@data << data
end
protected
def keys protected
@data.collect{ |x| x[:title] }
end def keys
@data.collect{ |x| x[:title] }
def calculate_left_margin end
super
label_left = get_x_labels[0].to_s.length / 2 * font_size * 0.6 def calculate_left_margin
@border_left = label_left if label_left > @border_left super
end label_left = get_x_labels[0].to_s.length / 2 * font_size * 0.6
@border_left = label_left if label_left > @border_left
def calculate_right_margin end
super
label_right = get_x_labels[-1].to_s.length / 2 * font_size * 0.6 def calculate_right_margin
@border_right = label_right if label_right > @border_right super
end 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 X = 0
max_value = @data.collect{|x| x[:data][X][-1] }.max Y = 1
min_value = @data.collect{|x| x[:data][X][0] }.min def x_range
min_value = min_value<min_x_value ? min_value : min_x_value if min_x_value max_value = @data.collect{|x| x[:data][X][-1] }.max
min_value = @data.collect{|x| x[:data][X][0] }.min
range = max_value - min_value min_value = min_value<min_x_value ? min_value : min_x_value if min_x_value
right_pad = range == 0 ? 10 : range / 20.0
scale_range = (max_value + right_pad) - min_value range = max_value - min_value
right_pad = range == 0 ? 10 : range / 20.0
scale_division = scale_x_divisions || (scale_range / 10.0) scale_range = (max_value + right_pad) - min_value
if scale_x_integers scale_division = scale_x_divisions || (scale_range / 10.0)
scale_division = scale_division < 1 ? 1 : scale_division.round
end if scale_x_integers
scale_division = scale_division < 1 ? 1 : scale_division.round
[min_value, max_value, scale_division] end
end
[min_value, max_value, scale_division]
def get_x_values end
min_value, max_value, scale_division = x_range
rv = [] def get_x_values
min_value.step( max_value, scale_division ) {|v| rv << v} min_value, max_value, scale_division = x_range
return rv rv = []
end min_value.step( max_value, scale_division ) {|v| rv << v}
alias :get_x_labels :get_x_values return rv
end
def field_width alias :get_x_labels :get_x_values
values = get_x_values
max = @data.collect{|x| x[:data][X][-1]}.max def field_width
dx = (max - values[-1]).to_f / (values[-1] - values[-2]) values = get_x_values
(@graph_width.to_f - font_size*2*right_font) / max = @data.collect{|x| x[:data][X][-1]}.max
(values.length + dx - right_align) dx = (max - values[-1]).to_f / (values[-1] - values[-2])
end (@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 def y_range
min_value = min_value<min_y_value ? min_value : min_y_value if min_y_value max_value = @data.collect{|x| x[:data][Y].max }.max
min_value = @data.collect{|x| x[:data][Y].min }.min
range = max_value - min_value min_value = min_value<min_y_value ? min_value : min_y_value if min_y_value
top_pad = range == 0 ? 10 : range / 20.0
scale_range = (max_value + top_pad) - min_value range = max_value - min_value
top_pad = range == 0 ? 10 : range / 20.0
scale_division = scale_y_divisions || (scale_range / 10.0) scale_range = (max_value + top_pad) - min_value
if scale_y_integers scale_division = scale_y_divisions || (scale_range / 10.0)
scale_division = scale_division < 1 ? 1 : scale_division.round
end if scale_y_integers
scale_division = scale_division < 1 ? 1 : scale_division.round
return [min_value, max_value, scale_division] end
end
return [min_value, max_value, scale_division]
def get_y_values end
min_value, max_value, scale_division = y_range
rv = [] def get_y_values
min_value.step( max_value, scale_division ) {|v| rv << v} min_value, max_value, scale_division = y_range
return rv rv = []
end min_value.step( max_value, scale_division ) {|v| rv << v}
alias :get_y_labels :get_y_values return rv
end
def field_height alias :get_y_labels :get_y_values
values = get_y_values
max = @data.collect{|x| x[:data][Y].max }.max def field_height
dx = (max - values[-1]).to_f / (values[-1] - values[-2]) values = get_y_values
(@graph_height.to_f - font_size*2*top_font) / max = @data.collect{|x| x[:data][Y].max }.max
(values.length + dx - top_align) if values.length == 1
end dx = values[-1]
else
def draw_data dx = (max - values[-1]).to_f / (values[-1] - values[-2])
line = 1 end
(@graph_height.to_f - font_size*2*top_font) /
x_min, x_max, x_div = x_range (values.length + dx - top_align)
y_min, y_max, y_div = y_range end
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) def draw_data
line = 1
for data in @data
x_points = data[:data][X] x_min, x_max, x_div = x_range
y_points = data[:data][Y] y_min, y_max, y_div = y_range
x_step = (@graph_width.to_f - font_size*2) / (x_max-x_min)
lpath = "L" y_step = (@graph_height.to_f - font_size*2) / (y_max-y_min)
x_start = 0
y_start = 0 for data in @data
x_points.each_index { |idx| x_points = data[:data][X]
x = (x_points[idx] - x_min) * x_step y_points = data[:data][Y]
y = @graph_height - (y_points[idx] - y_min) * y_step
x_start, y_start = x,y if idx == 0 lpath = "L"
lpath << "#{x} #{y} " x_start = 0
} y_start = 0
x_points.each_index { |idx|
if area_fill x = (x_points[idx] - x_min) * x_step
@graph.add_element( "path", { y = @graph_height - (y_points[idx] - y_min) * y_step
"d" => "M#{x_start} #@graph_height #{lpath} V#@graph_height Z", x_start, y_start = x,y if idx == 0
"class" => "fill#{line}" lpath << "#{x} #{y} "
}) }
end
if area_fill
@graph.add_element( "path", { @graph.add_element( "path", {
"d" => "M#{x_start} #{y_start} #{lpath}", "d" => "M#{x_start} #@graph_height #{lpath} V#@graph_height Z",
"class" => "line#{line}" "class" => "fill#{line}"
}) })
end
if show_data_points || show_data_values
x_points.each_index { |idx| @graph.add_element( "path", {
x = (x_points[idx] - x_min) * x_step "d" => "M#{x_start} #{y_start} #{lpath}",
y = @graph_height - (y_points[idx] - y_min) * y_step "class" => "line#{line}"
if show_data_points })
@graph.add_element( "circle", {
"cx" => x.to_s, if show_data_points || show_data_values
"cy" => y.to_s, x_points.each_index { |idx|
"r" => "2.5", x = (x_points[idx] - x_min) * x_step
"class" => "dataPoint#{line}" y = @graph_height - (y_points[idx] - y_min) * y_step
}) if show_data_points
add_popup(x, y, format( x_points[idx], y_points[idx] )) if add_popups @graph.add_element( "circle", {
end "cx" => x.to_s,
make_datapoint_text( x, y-6, y_points[idx] ) "cy" => y.to_s,
} "r" => "2.5",
end "class" => "dataPoint#{line}"
line += 1 })
end add_popup(x, y, format( x_points[idx], y_points[idx] )) if add_popups
end end
make_datapoint_text( x, y-6, y_points[idx] ) if show_data_values
def format x, y }
"(#{(x * 100).to_i / 100}, #{(y * 100).to_i / 100})" end
end line += 1
end
def get_css end
return <<EOL
/* default line styles */ def format x, y
.line1{ "(#{(x * 100).to_i / 100}, #{(y * 100).to_i / 100})"
fill: none; end
stroke: #ff0000;
stroke-width: 1px; def get_css
} return <<EOL
.line2{ /* default line styles */
fill: none; .line1{
stroke: #0000ff; fill: none;
stroke-width: 1px; stroke: #ff0000;
} stroke-width: 1px;
.line3{ }
fill: none; .line2{
stroke: #00ff00; fill: none;
stroke-width: 1px; stroke: #0000ff;
} stroke-width: 1px;
.line4{ }
fill: none; .line3{
stroke: #ffcc00; fill: none;
stroke-width: 1px; stroke: #00ff00;
} stroke-width: 1px;
.line5{ }
fill: none; .line4{
stroke: #00ccff; fill: none;
stroke-width: 1px; stroke: #ffcc00;
} stroke-width: 1px;
.line6{ }
fill: none; .line5{
stroke: #ff00ff; fill: none;
stroke-width: 1px; stroke: #00ccff;
} stroke-width: 1px;
.line7{ }
fill: none; .line6{
stroke: #00ffff; fill: none;
stroke-width: 1px; stroke: #ff00ff;
} stroke-width: 1px;
.line8{ }
fill: none; .line7{
stroke: #ffff00; fill: none;
stroke-width: 1px; stroke: #00ffff;
} stroke-width: 1px;
.line9{ }
fill: none; .line8{
stroke: #ccc6666; fill: none;
stroke-width: 1px; stroke: #ffff00;
} stroke-width: 1px;
.line10{ }
fill: none; .line9{
stroke: #663399; fill: none;
stroke-width: 1px; stroke: #ccc6666;
} stroke-width: 1px;
.line11{ }
fill: none; .line10{
stroke: #339900; fill: none;
stroke-width: 1px; stroke: #663399;
} stroke-width: 1px;
.line12{ }
fill: none; .line11{
stroke: #9966FF; fill: none;
stroke-width: 1px; stroke: #339900;
} stroke-width: 1px;
/* default fill styles */ }
.fill1{ .line12{
fill: #cc0000; fill: none;
fill-opacity: 0.2; stroke: #9966FF;
stroke: none; stroke-width: 1px;
} }
.fill2{ /* default fill styles */
fill: #0000cc; .fill1{
fill-opacity: 0.2; fill: #cc0000;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill3{ }
fill: #00cc00; .fill2{
fill-opacity: 0.2; fill: #0000cc;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill4{ }
fill: #ffcc00; .fill3{
fill-opacity: 0.2; fill: #00cc00;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill5{ }
fill: #00ccff; .fill4{
fill-opacity: 0.2; fill: #ffcc00;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill6{ }
fill: #ff00ff; .fill5{
fill-opacity: 0.2; fill: #00ccff;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill7{ }
fill: #00ffff; .fill6{
fill-opacity: 0.2; fill: #ff00ff;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill8{ }
fill: #ffff00; .fill7{
fill-opacity: 0.2; fill: #00ffff;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill9{ }
fill: #cc6666; .fill8{
fill-opacity: 0.2; fill: #ffff00;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill10{ }
fill: #663399; .fill9{
fill-opacity: 0.2; fill: #cc6666;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill11{ }
fill: #339900; .fill10{
fill-opacity: 0.2; fill: #663399;
stroke: none; fill-opacity: 0.2;
} stroke: none;
.fill12{ }
fill: #9966FF; .fill11{
fill-opacity: 0.2; fill: #339900;
stroke: none; fill-opacity: 0.2;
} stroke: none;
/* default line styles */ }
.key1,.dataPoint1{ .fill12{
fill: #ff0000; fill: #9966FF;
stroke: none; fill-opacity: 0.2;
stroke-width: 1px; stroke: none;
} }
.key2,.dataPoint2{ /* default line styles */
fill: #0000ff; .key1,.dataPoint1{
stroke: none; fill: #ff0000;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key3,.dataPoint3{ }
fill: #00ff00; .key2,.dataPoint2{
stroke: none; fill: #0000ff;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key4,.dataPoint4{ }
fill: #ffcc00; .key3,.dataPoint3{
stroke: none; fill: #00ff00;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key5,.dataPoint5{ }
fill: #00ccff; .key4,.dataPoint4{
stroke: none; fill: #ffcc00;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key6,.dataPoint6{ }
fill: #ff00ff; .key5,.dataPoint5{
stroke: none; fill: #00ccff;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key7,.dataPoint7{ }
fill: #00ffff; .key6,.dataPoint6{
stroke: none; fill: #ff00ff;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key8,.dataPoint8{ }
fill: #ffff00; .key7,.dataPoint7{
stroke: none; fill: #00ffff;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key9,.dataPoint9{ }
fill: #cc6666; .key8,.dataPoint8{
stroke: none; fill: #ffff00;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key10,.dataPoint10{ }
fill: #663399; .key9,.dataPoint9{
stroke: none; fill: #cc6666;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key11,.dataPoint11{ }
fill: #339900; .key10,.dataPoint10{
stroke: none; fill: #663399;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
.key12,.dataPoint12{ }
fill: #9966FF; .key11,.dataPoint11{
stroke: none; fill: #339900;
stroke-width: 1px; stroke: none;
} stroke-width: 1px;
EOL }
end .key12,.dataPoint12{
fill: #9966FF;
end stroke: none;
end stroke-width: 1px;
end }
EOL
end
end
end
end

View File

@ -1,241 +1,241 @@
require 'SVG/Graph/Plot' require 'SVG/Graph/Plot'
require 'parsedate' require 'parsedate'
module SVG module SVG
module Graph module Graph
# === For creating SVG plots of scalar temporal data # === For creating SVG plots of scalar temporal data
# #
# = Synopsis # = Synopsis
# #
# require 'SVG/Graph/TimeSeriess' # require 'SVG/Graph/TimeSeriess'
# #
# # Data sets are x,y pairs # # Data sets are x,y pairs
# data1 = ["6/17/72", 11, "1/11/72", 7, "4/13/04 17:31", 11, # 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] # "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, # 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/02", 14, "3/1/95", 6, "8/1/91", 12, "12/1/87", 6,
# "5/1/84", 17, "10/1/80", 12] # "5/1/84", 17, "10/1/80", 12]
# #
# graph = SVG::Graph::TimeSeries.new( { # graph = SVG::Graph::TimeSeries.new( {
# :width => 640, # :width => 640,
# :height => 480, # :height => 480,
# :graph_title => title, # :graph_title => title,
# :show_graph_title => true, # :show_graph_title => true,
# :no_css => true, # :no_css => true,
# :key => true, # :key => true,
# :scale_x_integers => true, # :scale_x_integers => true,
# :scale_y_integers => true, # :scale_y_integers => true,
# :min_x_value => 0, # :min_x_value => 0,
# :min_y_value => 0, # :min_y_value => 0,
# :show_data_labels => true, # :show_data_labels => true,
# :show_x_guidelines => true, # :show_x_guidelines => true,
# :show_x_title => true, # :show_x_title => true,
# :x_title => "Time", # :x_title => "Time",
# :show_y_title => true, # :show_y_title => true,
# :y_title => "Ice Cream Cones", # :y_title => "Ice Cream Cones",
# :y_title_text_direction => :bt, # :y_title_text_direction => :bt,
# :stagger_x_labels => true, # :stagger_x_labels => true,
# :x_label_format => "%m/%d/%y", # :x_label_format => "%m/%d/%y",
# }) # })
# #
# graph.add_data({ # graph.add_data({
# :data => projection # :data => projection
# :title => 'Projected', # :title => 'Projected',
# }) # })
# #
# graph.add_data({ # graph.add_data({
# :data => actual, # :data => actual,
# :title => 'Actual', # :title => 'Actual',
# }) # })
# #
# print graph.burn() # print graph.burn()
# #
# = Description # = Description
# #
# Produces a graph of temporal scalar data. # Produces a graph of temporal scalar data.
# #
# = Examples # = Examples
# #
# http://www.germane-software/repositories/public/SVG/test/timeseries.rb # http://www.germane-software/repositories/public/SVG/test/timeseries.rb
# #
# = Notes # = Notes
# #
# The default stylesheet handles upto 10 data sets, if you # The default stylesheet handles upto 10 data sets, if you
# use more you must create your own stylesheet and add the # use more you must create your own stylesheet and add the
# additional settings for the extra data sets. You will know # additional settings for the extra data sets. You will know
# if you go over 10 data sets as they will have no style and # if you go over 10 data sets as they will have no style and
# be in black. # be in black.
# #
# Unlike the other types of charts, data sets must contain x,y pairs: # 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) # [ "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 # [ "01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and
# # ("14:20",6) # # ("14:20",6)
# #
# Note that multiple data sets within the same chart can differ in length, # 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 # and that the data in the datasets needn't be in order; they will be ordered
# by the plot along the X-axis. # by the plot along the X-axis.
# #
# The dates must be parseable by ParseDate, but otherwise can be # The dates must be parseable by ParseDate, but otherwise can be
# any order of magnitude (seconds within the hour, or years) # any order of magnitude (seconds within the hour, or years)
# #
# = See also # = See also
# #
# * SVG::Graph::Graph # * SVG::Graph::Graph
# * SVG::Graph::BarHorizontal # * SVG::Graph::BarHorizontal
# * SVG::Graph::Bar # * SVG::Graph::Bar
# * SVG::Graph::Line # * SVG::Graph::Line
# * SVG::Graph::Pie # * SVG::Graph::Pie
# * SVG::Graph::Plot # * SVG::Graph::Plot
# #
# == Author # == Author
# #
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom> # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
# #
# Copyright 2004 Sean E. Russell # Copyright 2004 Sean E. Russell
# This software is available under the Ruby license[LICENSE.txt] # This software is available under the Ruby license[LICENSE.txt]
# #
class TimeSeries < Plot class TimeSeries < Plot
# In addition to the defaults set by Graph::initialize and # In addition to the defaults set by Graph::initialize and
# Plot::set_defaults, sets: # Plot::set_defaults, sets:
# [x_label_format] '%Y-%m-%d %H:%M:%S' # [x_label_format] '%Y-%m-%d %H:%M:%S'
# [popup_format] '%Y-%m-%d %H:%M:%S' # [popup_format] '%Y-%m-%d %H:%M:%S'
def set_defaults def set_defaults
super super
init_with( init_with(
#:max_time_span => '', #:max_time_span => '',
:x_label_format => '%Y-%m-%d %H:%M:%S', :x_label_format => '%Y-%m-%d %H:%M:%S',
:popup_format => '%Y-%m-%d %H:%M:%S' :popup_format => '%Y-%m-%d %H:%M:%S'
) )
end end
# The format string use do format the X axis labels. # The format string use do format the X axis labels.
# See Time::strformat # See Time::strformat
attr_accessor :x_label_format attr_accessor :x_label_format
# Use this to set the spacing between dates on the axis. The value # Use this to set the spacing between dates on the axis. The value
# must be of the form # must be of the form
# "\d+ ?(days|weeks|months|years|hours|minutes|seconds)?" # "\d+ ?(days|weeks|months|years|hours|minutes|seconds)?"
# #
# EG: # EG:
# #
# graph.timescale_divisions = "2 weeks" # graph.timescale_divisions = "2 weeks"
# #
# will cause the chart to try to divide the X axis up into segments of # will cause the chart to try to divide the X axis up into segments of
# two week periods. # two week periods.
attr_accessor :timescale_divisions attr_accessor :timescale_divisions
# The formatting used for the popups. See x_label_format # The formatting used for the popups. See x_label_format
attr_accessor :popup_format attr_accessor :popup_format
# Add data to the plot. # Add data to the plot.
# #
# d1 = [ "12:30", 2 ] # A data set with 1 point: ("12:30",2) # 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 # d2 = [ "01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and
# # ("14:20",6) # # ("14:20",6)
# graph.add_data( # graph.add_data(
# :data => d1, # :data => d1,
# :title => 'One' # :title => 'One'
# ) # )
# graph.add_data( # graph.add_data(
# :data => d2, # :data => d2,
# :title => 'Two' # :title => 'Two'
# ) # )
# #
# Note that the data must be in time,value pairs, and that the date format # Note that the data must be in time,value pairs, and that the date format
# may be any date that is parseable by ParseDate. # may be any date that is parseable by ParseDate.
def add_data data def add_data data
@data = [] unless @data @data = [] unless @data
raise "No data provided by #{conf.inspect}" unless data[:data] and raise "No data provided by #{@data.inspect}" unless data[:data] and
data[:data].kind_of? Array data[:data].kind_of? Array
raise "Data supplied must be x,y pairs! "+ raise "Data supplied must be x,y pairs! "+
"The data provided contained an odd set of "+ "The data provided contained an odd set of "+
"data points" unless data[:data].length % 2 == 0 "data points" unless data[:data].length % 2 == 0
return if data[:data].length == 0 return if data[:data].length == 0
x = [] x = []
y = [] y = []
data[:data].each_index {|i| data[:data].each_index {|i|
if i%2 == 0 if i%2 == 0
arr = ParseDate.parsedate( data[:data][i] ) arr = ParseDate.parsedate( data[:data][i] )
t = Time.local( *arr[0,6].compact ) t = Time.local( *arr[0,6].compact )
x << t.to_i x << t.to_i
else else
y << data[:data][i] y << data[:data][i]
end end
} }
sort( x, y ) sort( x, y )
data[:data] = [x,y] data[:data] = [x,y]
@data << data @data << data
end end
protected protected
def min_x_value=(value) def min_x_value=(value)
arr = ParseDate.parsedate( value ) arr = ParseDate.parsedate( value )
@min_x_value = Time.local( *arr[0,6].compact ).to_i @min_x_value = Time.local( *arr[0,6].compact ).to_i
end end
def format x, y def format x, y
Time.at( x ).strftime( popup_format ) Time.at( x ).strftime( popup_format )
end end
def get_x_labels def get_x_labels
get_x_values.collect { |v| Time.at(v).strftime( x_label_format ) } get_x_values.collect { |v| Time.at(v).strftime( x_label_format ) }
end end
private private
def get_x_values def get_x_values
rv = [] rv = []
min, max, scale_division = x_range min, max, scale_division = x_range
if timescale_divisions if timescale_divisions
timescale_divisions =~ /(\d+) ?(days|weeks|months|years|hours|minutes|seconds)?/ timescale_divisions =~ /(\d+) ?(day|week|month|year|hour|minute|second)?/
division_units = $2 ? $2 : "days" division_units = $2 ? $2 : "day"
amount = $1.to_i amount = $1.to_i
if amount if amount
step = nil step = nil
case division_units case division_units
when "months" when "month"
cur = min cur = min
while cur < max while cur < max
rv << cur rv << cur
arr = Time.at( cur ).to_a arr = Time.at( cur ).to_a
arr[4] += amount arr[4] += amount
if arr[4] > 12 if arr[4] > 12
arr[5] += (arr[4] / 12).to_i arr[5] += (arr[4] / 12).to_i
arr[4] = (arr[4] % 12) arr[4] = (arr[4] % 12)
end end
cur = Time.local(*arr).to_i cur = Time.local(*arr).to_i
end end
when "years" when "year"
cur = min cur = min
while cur < max while cur < max
rv << cur rv << cur
arr = Time.at( cur ).to_a arr = Time.at( cur ).to_a
arr[5] += amount arr[5] += amount
cur = Time.local(*arr).to_i cur = Time.local(*arr).to_i
end end
when "weeks" when "week"
step = 7 * 24 * 60 * 60 * amount step = 7 * 24 * 60 * 60 * amount
when "days" when "day"
step = 24 * 60 * 60 * amount step = 24 * 60 * 60 * amount
when "hours" when "hour"
step = 60 * 60 * amount step = 60 * 60 * amount
when "minutes" when "minute"
step = 60 * amount step = 60 * amount
when "seconds" when "second"
step = amount step = amount
end end
min.step( max, step ) {|v| rv << v} if step min.step( max, step ) {|v| rv << v} if step
return rv return rv
end end
end end
min.step( max, scale_division ) {|v| rv << v} min.step( max, scale_division ) {|v| rv << v}
return rv return rv
end end
end end
end end
end end