]> projects.mako.cc - selectricity-live/blob - vendor/plugins/gruff/lib/gruff/side_stacked_bar.rb
52bbea308a648a7cd78550d86901c58a68fb0056
[selectricity-live] / vendor / plugins / gruff / lib / gruff / side_stacked_bar.rb
1 require File.dirname(__FILE__) + '/base'
2 require File.dirname(__FILE__) + '/side_bar'
3
4 ##
5 # New gruff graph type added to enable sideways stacking bar charts 
6 # (basically looks like a x/y flip of a standard stacking bar chart)
7 #
8 # alun.eyre@googlemail.com 
9
10 class Gruff::SideStackedBar < Gruff::SideBar
11
12   def draw
13     @has_left_labels = true
14     get_maximum_by_stack
15     super
16
17     return unless @has_data
18
19     # Setup spacing.
20     #
21     # Columns sit stacked.
22     spacing_factor = 0.9
23
24     @bar_width = @graph_height / @column_count.to_f
25     @d = @d.stroke_opacity 0.0
26     height = Array.new(@column_count, 0)
27     length = Array.new(@column_count, @graph_left)
28
29     @norm_data.each_with_index do |data_row, row_index|
30       @d = @d.fill data_row[DATA_COLOR_INDEX]
31
32       data_row[1].each_with_index do |data_point, point_index|
33
34           ## using the original calcs from the stacked bar chart to get the difference between
35           ## part of the bart chart we wish to stack.
36           temp1 = @graph_left + (@graph_width -
37                                     data_point * @graph_width - 
38                                     height[point_index]) + 1
39           temp2 = @graph_left + @graph_width - height[point_index] - 1
40           difference = temp2 - temp1
41
42           left_x = length[point_index] #+ 1
43               left_y = @graph_top + (@bar_width * point_index)
44           right_x = left_x + difference
45               right_y = left_y + @bar_width * spacing_factor
46           length[point_index] += difference
47         height[point_index] += (data_point * @graph_width - 2)
48
49         @d = @d.rectangle(left_x, left_y, right_x, right_y)
50
51         # Calculate center based on bar_width and current row
52         label_center = @graph_top + (@bar_width * point_index) + (@bar_width * spacing_factor / 2.0)
53         draw_label(label_center, point_index)
54       end
55
56     end
57
58     @d.draw(@base_image)    
59   end
60
61   protected
62
63   def larger_than_max?(data_point, index=0)
64     max(data_point, index) > @maximum_value
65   end
66
67   def max(data_point, index)
68     @data.inject(0) {|sum, item| sum + item[1][index]}
69   end
70
71 end

Benjamin Mako Hill || Want to submit a patch?