2 require File.dirname(__FILE__) + '/base'
4 class Gruff::Line < Gruff::Base
6 # Draw a dashed line at the given value
7 attr_accessor :baseline_value
9 # Color of the baseline
10 attr_accessor :baseline_color
12 # Hide parts of the graph to fit more datapoints, or for a different appearance.
13 attr_accessor :hide_dots, :hide_lines
15 # Call with target pixel width of graph (800, 400, 300), and/or 'false' to omit lines (points only).
17 # g = Gruff::Line.new(400) # 400px wide with lines
19 # g = Gruff::Line.new(400, false) # 400px wide, no lines (for backwards compatibility)
21 # g = Gruff::Line.new(false) # Defaults to 800px wide, no lines (for backwards compatibility)
23 # The preferred way is to call hide_dots or hide_lines instead.
25 raise ArgumentError, "Wrong number of arguments" if args.length > 2
26 if args.empty? or ((not Numeric === args.first) && (not String === args.first)) then
32 @hide_dots = @hide_lines = false
33 @baseline_color = 'red'
40 return unless @has_data
42 # Check to see if more than one datapoint was given. NaN can result otherwise.
43 @x_increment = (@column_count > 1) ? (@graph_width / (@column_count - 1).to_f) : @graph_width
45 if (defined?(@norm_baseline)) then
46 level = @graph_top + (@graph_height - @norm_baseline * @graph_height)
48 @d.stroke_color @baseline_color
50 @d.stroke_dasharray(10, 20)
52 @d.line(@graph_left, level, @graph_left + @graph_width, level)
56 @norm_data.each do |data_row|
59 data_row[1].each_with_index do |data_point, index|
60 new_x = @graph_left + (@x_increment * index)
61 next if data_point.nil?
63 draw_label(new_x, index)
65 new_y = @graph_top + (@graph_height - data_point * @graph_height)
67 # Reset each time to avoid thin-line errors
68 @d = @d.stroke data_row[DATA_COLOR_INDEX]
69 @d = @d.fill data_row[DATA_COLOR_INDEX]
70 @d = @d.stroke_opacity 1.0
71 @d = @d.stroke_width clip_value_if_greater_than(@columns / (@norm_data.first[1].size * 4), 5.0)
73 if !@hide_lines and !prev_x.nil? and !prev_y.nil? then
74 @d = @d.line(prev_x, prev_y, new_x, new_y)
76 circle_radius = clip_value_if_greater_than(@columns / (@norm_data.first[1].size * 2.5), 5.0)
77 @d = @d.circle(new_x, new_y, new_x - circle_radius, new_y) unless @hide_dots
89 @maximum_value = [@maximum_value.to_f, @baseline_value.to_f].max
91 @norm_baseline = (@baseline_value.to_f / @maximum_value.to_f) if @baseline_value