4 # Author:: Geoffrey Grosenbach boss@topfunky.com
6 # Originally Created:: October 23, 2005
8 # Extra thanks to Tim Hunter for writing RMagick,
9 # and also contributions by
10 # Jarkko Laine, Mike Perham, Andreas Schwarz,
11 # Alun Eyre, Guillaume Theoret, David Stokar,
12 # Paul Rogers, Dave Woodward, Frank Oxener,
13 # Kevin Clark, Cies Breijs, Richard Cowin,
14 # and a cast of thousands.
19 require File.dirname(__FILE__) + '/deprecated'
30 # Draw extra lines showing where the margins and text centers are
33 # Used for navigating the array of data to plot
38 # Blank space around the edges of the graph
39 TOP_MARGIN = BOTTOM_MARGIN = RIGHT_MARGIN = LEFT_MARGIN = 20.0
41 # Space around text elements. Mostly used for vertical spacing
42 LEGEND_MARGIN = TITLE_MARGIN = LABEL_MARGIN = 10.0
44 DEFAULT_TARGET_WIDTH = 800
46 # A hash of names for the individual columns, where the key is the array index for the column this label represents.
48 # Not all columns need to be named.
50 # Example: 0 => 2005, 3 => 2006, 5 => 2007, 7 => 2008
53 # Used internally for spacing.
55 # By default, labels are centered over the point they represent.
56 attr_accessor :center_labels_over_point
58 # Used internally for horizontal graph types.
59 attr_accessor :has_left_labels
61 # A label for the bottom of the graph
62 attr_accessor :x_axis_label
64 # A label for the left side of the graph
65 attr_accessor :y_axis_label
67 # attr_accessor :x_axis_increment
69 # Manually set increment of the horizontal marking lines
70 attr_accessor :y_axis_increment
72 # Get or set the list of colors that will be used to draw the bars or lines.
75 # The large title of the graph displayed at the top
78 # Font used for titles, labels, etc. Works best if you provide the full path to the TTF font file.
79 # RMagick must be built with the Freetype libraries for this to work properly.
81 # Tries to find Bitstream Vera (Vera.ttf) in the location specified by
82 # ENV['MAGICK_FONT_PATH']. Uses default RMagick font otherwise.
84 # The font= method below fulfills the role of the writer, so we only need
88 attr_accessor :font_color
90 # Hide various elements
91 attr_accessor :hide_line_markers, :hide_legend, :hide_title, :hide_line_numbers
93 # Message shown when there is no data. Fits up to 20 characters. Defaults to "No Data."
94 attr_accessor :no_data_message
96 # The font size of the large title at the top of the graph
97 attr_accessor :title_font_size
99 # Optionally set the size of the font. Based on an 800x600px graph. Default is 20.
101 # Will be scaled down if graph is smaller than 800px wide.
102 attr_accessor :legend_font_size
104 # The font size of the labels around the graph
105 attr_accessor :marker_font_size
107 # The color of the auxiliary lines
108 attr_accessor :marker_color
110 # The number of horizontal lines shown for reference
111 attr_accessor :marker_count
114 # You can manually set a minimum value instead of having the values guessed for you.
116 # Set it after you have given all your data to the graph object.
117 attr_accessor :minimum_value
119 # You can manually set a maximum value, such as a percentage-based graph that always goes to 100.
121 # If you use this, you must set it after you have given all your data to the graph object.
122 attr_accessor :maximum_value
124 # Set to false if you don't want the data to be sorted with largest avg values at the back.
128 attr_accessor :additional_line_values
131 attr_accessor :stacked
134 # Optionally set the size of the colored box by each item in the legend. Default is 20.0
136 # Will be scaled down if graph is smaller than 800px wide.
137 attr_accessor :legend_box_size
140 # If one numerical argument is given, the graph is drawn at 4/3 ratio according to the given width (800 results in 800x600, 400 gives 400x300, etc.).
142 # Or, send a geometry string for other ratios ('800x400', '400x225').
144 # Looks for Bitstream Vera as the default font. Expects an environment var of MAGICK_FONT_PATH to be set. (Uses RMagick's default font otherwise.)
145 def initialize(target_width=DEFAULT_TARGET_WIDTH)
147 if not Numeric === target_width
148 geometric_width, geometric_height = target_width.split('x')
149 @columns = geometric_width.to_f
150 @rows = geometric_height.to_f
152 @columns = target_width.to_f
153 @rows = target_width.to_f * 0.75
163 # Set instance variables for this object.
165 # Subclasses can override this, call super, then set values separately.
167 # This makes it possible to set defaults in a subclass but still allow
168 # developers to change this values in their program.
171 # Internal for calculations
173 @raw_rows = 800.0 * (@rows/@columns)
176 @maximum_value = @minimum_value = nil
180 @labels_seen = Hash.new
184 @scale = @columns / @raw_columns
186 vera_font_path = File.expand_path('Vera.ttf', ENV['MAGICK_FONT_PATH'])
187 @font = File.exists?(vera_font_path) ? vera_font_path : nil
189 @marker_font_size = 21.0
190 @legend_font_size = 20.0
191 @title_font_size = 36.0
193 @legend_box_size = 20.0
195 @no_data_message = "No Data"
197 @hide_line_markers = @hide_legend = @hide_title = @hide_line_numbers = false
198 @center_labels_over_point = true
199 @has_left_labels = false
201 @additional_line_values = []
202 @additional_line_colors = []
205 @x_axis_label = @y_axis_label = nil
206 @y_axis_increment = nil
216 # Add a color to the list of available colors for lines.
219 # add_color('#c0e9d3')
220 def add_color(colorname)
225 # Replace the entire color list with a new array of colors. You need to have one more color
226 # than the number of datasets you intend to draw. Also aliased as the colors= setter method.
229 # replace_colors('#cc99cc', '#d9e043', '#34d8a2')
230 def replace_colors(color_list=[])
235 # You can set a theme manually. Assign a hash to this method before you send your data.
238 # :colors => %w(orange purple green white red),
239 # :marker_color => 'blue',
240 # :background_colors => %w(black grey)
243 # :background_image => 'squirrel.png' is also possible.
245 # (Or hopefully something better looking than that.)
251 :colors => ['black', 'white'],
252 :additional_line_colors => [],
253 :marker_color => 'white',
254 :font_color => 'black',
255 :background_colors => nil,
256 :background_image => nil
258 @theme_options = defaults.merge options
260 @colors = @theme_options[:colors]
261 @marker_color = @theme_options[:marker_color]
262 @font_color = @theme_options[:font_color] || @marker_color
263 @additional_line_colors = @theme_options[:additional_line_colors]
268 # A color scheme similar to the popular presentation software.
278 @colors = [@yellow, @blue, @green, @red, @purple, @orange, @white]
282 :marker_color => 'white',
283 :font_color => 'white',
284 :background_colors => ['black', '#4a465a']
288 # A color scheme plucked from the colors on the popular usability blog.
298 @colors = [@yellow, @blue, @green, @red, @purple, @orange, @black]
302 :marker_color => 'black',
303 :font_color => 'black',
304 :background_colors => ['#d1edf5', 'white']
308 # A color scheme from the colors used on the 2005 Rails keynote presentation at RubyConf.
309 def theme_rails_keynote
316 @light_grey = '#999999'
318 @colors = [@green, @grey, @orange, @red, @white, @light_grey, @black]
322 :marker_color => 'white',
323 :font_color => 'white',
324 :background_colors => ['#0083a3', '#0083a3']
328 # A color scheme similar to that used on the popular podcast site.
333 @dark_pink = '#a21764'
335 @light_grey = '#999999'
336 @dark_blue = '#3a5b87'
338 @colors = [@grey, @white, @dark_blue, @dark_pink, @green, @light_grey, @black]
342 :marker_color => 'white',
343 :font_color => 'white',
344 :background_colors => ['#ff47a4', '#ff1f81']
356 '#a9a9da', # dk purple
363 :marker_color => '#aea9a9', # Grey
364 :font_color => 'black',
365 :background_colors => 'white'
383 :marker_color => '#aea9a9', # Grey
384 :font_color => 'black',
385 :background_colors => 'white'
390 # Parameters are an array where the first element is the name of the dataset
391 # and the value is an array of values to plot.
393 # Can be called multiple times with different datasets for a multi-valued graph.
395 # If the color argument is nil, the next color from the default theme will be used.
397 # NOTE: If you want to use a preset theme, you must set it before calling data().
401 # data("Bart S.", [95, 45, 78, 89, 88, 76], '#ffcc00')
403 def data(name, data_points=[], color=nil)
404 data_points = Array(data_points) # make sure it's an array
405 @data << [name, data_points, (color || increment_color)]
406 # Set column count if this is larger than previous counts
407 @column_count = (data_points.length > @column_count) ? data_points.length : @column_count
410 data_points.each_with_index do |data_point, index|
411 next if data_point.nil?
413 # Setup max/min so spread starts at the low end of the data points
414 if @maximum_value.nil? && @minimum_value.nil?
415 @maximum_value = @minimum_value = data_point
418 # TODO Doesn't work with stacked bar graphs
419 # Original: @maximum_value = larger_than_max?(data_point, index) ? max(data_point, index) : @maximum_value
420 @maximum_value = larger_than_max?(data_point) ? data_point : @maximum_value
421 @has_data = true if @maximum_value > 0
423 @minimum_value = less_than_min?(data_point) ? data_point : @minimum_value
424 @has_data = true if @minimum_value < 0
428 # Writes the graph to a file. Defaults to 'graph.png'
430 # Example: write('graphs/my_pretty_graph.png')
431 def write(filename="graph.png")
433 @base_image.write(filename)
436 # Return the graph as a rendered binary blob.
437 def to_blob(fileformat='PNG')
439 return @base_image.to_blob do
440 self.format = fileformat
446 # Overridden by subclasses to do the actual plotting of the graph.
448 # Subclasses should start by calling super() for this method.
450 make_stacked if @stacked
455 @d.rectangle( LEFT_MARGIN, TOP_MARGIN,
456 @raw_columns - RIGHT_MARGIN, @raw_rows - BOTTOM_MARGIN)
458 @d.rectangle( @graph_left, @graph_top, @graph_right, @graph_bottom)
463 # Calculates size of drawable area and draws the decorations.
470 # Maybe should be done in one of the following functions for more granularity.
477 setup_graph_measurements()
478 sort_norm_data() if @sort # Sort norm_data with avg largest values set first (for display)
486 # Make copy of data with values scaled between 0-100
487 def normalize(force=false)
488 if @norm_data.nil? || force
490 return unless @has_data
494 @data.each do |data_row|
495 norm_data_points = []
496 data_row[DATA_VALUES_INDEX].each do |data_point|
498 norm_data_points << nil
500 norm_data_points << ((data_point.to_f - @minimum_value.to_f ) / @spread)
503 @norm_data << [data_row[DATA_LABEL_INDEX], norm_data_points, data_row[DATA_COLOR_INDEX]]
509 @spread = @maximum_value.to_f - @minimum_value.to_f
510 @spread = @spread > 0 ? @spread : 1
514 # Calculates size of drawable area, general font dimensions, etc.
516 def setup_graph_measurements
517 @marker_caps_height = calculate_caps_height(@marker_font_size)
518 @title_caps_height = calculate_caps_height(@title_font_size)
519 @legend_caps_height = calculate_caps_height(@legend_font_size)
521 if @hide_line_markers
524 @graph_bottom_margin) = [LEFT_MARGIN, RIGHT_MARGIN, BOTTOM_MARGIN]
526 longest_left_label_width = 0
528 longest_left_label_width = calculate_width(@marker_font_size,
529 labels.values.inject('') { |value, memo| (value.to_s.length > memo.to_s.length) ? value : memo }) * 1.25
531 longest_left_label_width = calculate_width(@marker_font_size,
532 label(@maximum_value.to_f))
535 # Shift graph if left line numbers are hidden
536 line_number_width = @hide_line_numbers && !@has_left_labels ?
538 (longest_left_label_width + LABEL_MARGIN * 2)
540 @graph_left = LEFT_MARGIN +
542 (@y_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN * 2)
543 # Make space for half the width of the rightmost column label.
544 # Might be greater than the number of columns if between-style bar markers are used.
545 last_label = @labels.keys.sort.last.to_i
546 extra_room_for_long_label = (last_label >= (@column_count-1) && @center_labels_over_point) ?
547 calculate_width(@marker_font_size, @labels[last_label])/2.0 :
549 @graph_right_margin = RIGHT_MARGIN + extra_room_for_long_label
551 @graph_bottom_margin = BOTTOM_MARGIN +
552 @marker_caps_height + LABEL_MARGIN
555 @graph_right = @raw_columns - @graph_right_margin
556 @graph_width = @raw_columns - @graph_left - @graph_right_margin
558 # When @hide title, leave a TITLE_MARGIN space for aesthetics.
559 # Same with @hide_legend
560 @graph_top = TOP_MARGIN +
561 (@hide_title ? TITLE_MARGIN : @title_caps_height + TITLE_MARGIN * 2) +
562 (@hide_legend ? LEGEND_MARGIN : @legend_caps_height + LEGEND_MARGIN * 2)
564 @graph_bottom = @raw_rows - @graph_bottom_margin -
565 (@x_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN)
567 @graph_height = @graph_bottom - @graph_top
570 # Draw the optional labels for the x axis and y axis.
572 unless @x_axis_label.nil?
574 # Centered vertically and horizontally by setting the
575 # height to 1.0 and the width to the width of the graph.
576 x_axis_label_y_coordinate = @graph_bottom + LABEL_MARGIN * 2 + @marker_caps_height
578 # TODO Center between graph area
579 @d.fill = @font_color
580 @d.font = @font if @font
581 @d.stroke('transparent')
582 @d.pointsize = scale_fontsize(@marker_font_size)
583 @d.gravity = NorthGravity
584 @d = @d.annotate_scaled( @base_image,
586 0.0, x_axis_label_y_coordinate,
587 @x_axis_label, @scale)
588 debug { @d.line 0.0, x_axis_label_y_coordinate, @raw_columns, x_axis_label_y_coordinate }
591 unless @y_axis_label.nil?
592 # Y Axis, rotated vertically
594 @d.gravity = CenterGravity
595 @d = @d.annotate_scaled( @base_image,
597 LEFT_MARGIN + @marker_caps_height / 2.0, 0.0,
598 @y_axis_label, @scale)
603 # Draws horizontal background lines and labels
604 def draw_line_markers
605 return if @hide_line_markers
607 @d = @d.stroke_antialias false
609 if @y_axis_increment.nil?
610 # Try to use a number of horizontal lines that will come out even.
612 # TODO Do the same for larger numbers...100, 75, 50, 25
613 if @marker_count.nil?
614 (3..7).each do |lines|
615 if @spread % lines == 0.0
616 @marker_count = lines
622 @increment = (@spread > 0) ? significant(@spread / @marker_count) : 1
624 # TODO Make this work for negative values
625 @maximum_value = [@maximum_value.ceil, @y_axis_increment].max
626 @minimum_value = @minimum_value.floor
630 @marker_count = (@spread / @y_axis_increment).to_i
631 @increment = @y_axis_increment
633 @increment_scaled = @graph_height.to_f / (@spread / @increment)
635 # Draw horizontal line markers and annotate with numbers
636 (0..@marker_count).each do |index|
637 y = @graph_top + @graph_height - index.to_f * @increment_scaled
639 @d = @d.stroke(@marker_color)
640 @d = @d.stroke_width 1
641 @d = @d.line(@graph_left, y, @graph_right, y)
643 marker_label = index * @increment + @minimum_value.to_f
645 unless @hide_line_numbers
646 @d.fill = @font_color
647 @d.font = @font if @font
648 @d.stroke('transparent')
649 @d.pointsize = scale_fontsize(@marker_font_size)
650 @d.gravity = EastGravity
652 # Vertically center with 1.0 for the height
653 @d = @d.annotate_scaled( @base_image,
654 @graph_left - LABEL_MARGIN, 1.0,
656 label(marker_label), @scale)
660 # # Submitted by a contibutor...the utility escapes me
662 # @additional_line_values.each do |value|
663 # @increment_scaled = @graph_height.to_f / (@maximum_value.to_f / value)
665 # y = @graph_top + @graph_height - @increment_scaled
667 # @d = @d.stroke(@additional_line_colors[i])
668 # @d = @d.line(@graph_left, y, @graph_right, y)
671 # @d.fill = @additional_line_colors[i]
672 # @d.font = @font if @font
673 # @d.stroke('transparent')
674 # @d.pointsize = scale_fontsize(@marker_font_size)
675 # @d.gravity = EastGravity
676 # @d = @d.annotate_scaled( @base_image,
678 # -10, y - (@marker_font_size/2.0),
683 @d = @d.stroke_antialias true
686 # Draws a legend with the names of the datasets
687 # matched to the colors used to draw them.
689 return if @hide_legend
691 @legend_labels = @data.collect {|item| item[DATA_LABEL_INDEX] }
693 legend_square_width = @legend_box_size # small square with color of this item
695 # May fix legend drawing problem at small sizes
696 @d.font = @font if @font
697 @d.pointsize = @legend_font_size
699 metrics = @d.get_type_metrics(@base_image, @legend_labels.join(''))
700 legend_text_width = metrics.width
701 legend_width = legend_text_width +
702 (@legend_labels.length * legend_square_width * 2.7)
703 legend_left = (@raw_columns - legend_width) / 2
704 legend_increment = legend_width / @legend_labels.length.to_f
706 current_x_offset = legend_left
707 current_y_offset = @hide_title ?
708 TOP_MARGIN + LEGEND_MARGIN :
710 TITLE_MARGIN + @title_caps_height +
713 debug { @d.line 0.0, current_y_offset, @raw_columns, current_y_offset }
715 @legend_labels.each_with_index do |legend_label, index|
718 @d.fill = @font_color
719 @d.font = @font if @font
720 @d.pointsize = scale_fontsize(@legend_font_size)
721 @d.stroke('transparent')
722 @d.font_weight = NormalWeight
723 @d.gravity = WestGravity
724 @d = @d.annotate_scaled( @base_image,
726 current_x_offset + (legend_square_width * 1.7), current_y_offset,
727 legend_label.to_s, @scale)
729 # Now draw box with color of this dataset
730 @d = @d.stroke('transparent')
731 @d = @d.fill @data[index][DATA_COLOR_INDEX]
732 @d = @d.rectangle(current_x_offset,
733 current_y_offset - legend_square_width / 2.0,
734 current_x_offset + legend_square_width,
735 current_y_offset + legend_square_width / 2.0)
737 @d.pointsize = @legend_font_size
738 metrics = @d.get_type_metrics(@base_image, legend_label.to_s)
739 current_string_offset = metrics.width + (legend_square_width * 2.7)
740 current_x_offset += current_string_offset
746 return if (@hide_title || @title.nil?)
748 @d.fill = @font_color
749 @d.font = @font if @font
750 @d.stroke('transparent')
751 @d.pointsize = scale_fontsize(@title_font_size)
752 @d.font_weight = BoldWeight
753 @d.gravity = NorthGravity
754 @d = @d.annotate_scaled( @base_image,
761 # Draws column labels below graph, centered over x_offset
763 # TODO Allow WestGravity as an option
765 def draw_label(x_offset, index)
766 return if @hide_line_markers
768 if !@labels[index].nil? && @labels_seen[index].nil?
769 y_offset = @graph_bottom + LABEL_MARGIN
771 @d.fill = @font_color
772 @d.font = @font if @font
773 @d.stroke('transparent')
774 @d.font_weight = NormalWeight
775 @d.pointsize = scale_fontsize(@marker_font_size)
776 @d.gravity = NorthGravity
777 @d = @d.annotate_scaled(@base_image,
780 @labels[index], @scale)
781 @labels_seen[index] = 1
782 debug { @d.line 0.0, y_offset, @raw_columns, y_offset }
787 @d.fill = @font_color
788 @d.font = @font if @font
789 @d.stroke('transparent')
790 @d.font_weight = NormalWeight
791 @d.pointsize = scale_fontsize(80)
792 @d.gravity = CenterGravity
793 @d = @d.annotate_scaled( @base_image,
794 @raw_columns, @raw_rows/2.0,
796 @no_data_message, @scale)
800 # Finds the best background to render based on the provided theme options.
802 # Creates a @base_image to draw on.
804 def render_background
805 case @theme_options[:background_colors]
807 @base_image = render_gradiated_background(*@theme_options[:background_colors])
809 @base_image = render_solid_background(@theme_options[:background_colors])
811 @base_image = render_image_background(*@theme_options[:background_image])
816 # Make a new image at the current size with a solid +color+.
818 def render_solid_background(color)
819 Image.new(@columns, @rows) {
820 self.background_color = color
824 # Use with a theme definition method to draw a gradiated background.
825 def render_gradiated_background(top_color, bottom_color)
826 Image.new(@columns, @rows,
827 GradientFill.new(0, 0, 100, 0, top_color, bottom_color))
830 # Use with a theme to use an image (800x600 original) background.
831 def render_image_background(image_path)
832 image = Image.read(image_path)
834 image[0].resize!(@scale) # TODO Resize with new scale (crop if necessary for wide graph)
839 # Use with a theme to make a transparent background
840 def render_transparent_background
841 Image.new(@columns, @rows) do
842 self.background_color = 'transparent'
852 # Scale down from 800x600 used to calculate drawing.
853 @d = @d.scale(@scale, @scale)
860 # Return a comparable fontsize for the current graph.
861 def scale_fontsize(value)
862 new_fontsize = value * @scale
863 # return new_fontsize < 10.0 ? 10.0 : new_fontsize
867 def clip_value_if_greater_than(value, max_value)
868 (value > max_value) ? max_value : value
871 # Overridden by subclasses such as stacked bar.
872 def larger_than_max?(data_point, index=0)
873 data_point > @maximum_value
876 def less_than_min?(data_point, index=0)
877 data_point < @minimum_value
881 # Overridden by subclasses that need it.
882 def max(data_point, index)
887 # Overridden by subclasses that need it.
888 def min(data_point, index)
893 return 1.0 if inc == 0 # Keep from going into infinite loop
905 res = inc.floor * factor
906 if (res.to_i.to_f == res)
913 # Sort with largest overall summed value at front of array
914 # so it shows up correctly in the drawn graph.
916 @norm_data.sort! { |a,b| sums(b[1]) <=> sums(a[1]) }
921 data_set.collect {|num| total_sum += num.to_f }
926 # Used by StackedBar and child classes.
928 # May need to be moved to the StackedBar class.
930 def get_maximum_by_stack
931 # Get sum of each stack
933 @data.each do |data_set|
934 data_set[DATA_VALUES_INDEX].each_with_index do |data_point, i|
935 max_hash[i] = 0.0 unless max_hash[i]
936 max_hash[i] += data_point.to_f
941 max_hash.keys.each do |key|
942 @maximum_value = max_hash[key] if max_hash[key] > @maximum_value
948 stacked_values = Array.new(@column_count, 0)
949 @data.each do |value_set|
950 value_set[1].each_with_index do |value, index|
951 stacked_values[index] += value
953 value_set[1] = stacked_values.dup
959 # Takes a block and draws it if DEBUG is true.
961 # debug { @d.rectangle x1, y1, x2, y2 }
965 @d = @d.fill 'transparent'
966 @d = @d.stroke 'turquoise'
976 if @color_index < @colors.length
978 return @colors[@color_index - 1]
988 # Return a formatted string representing a number value that should be printed as a label.
991 if (@spread.to_f % @marker_count.to_f == 0) || !@y_axis_increment.nil?
992 return value.to_i.to_s
996 sprintf("%0i", value)
998 sprintf("%0.2f", value)
1005 # Returns the height of the capital letter 'X' for the current font and size.
1007 # Not scaled since it deals with dimensions that the regular
1008 # scaling will handle.
1010 def calculate_caps_height(font_size)
1011 @d.pointsize = font_size
1012 @d.get_type_metrics(@base_image, 'X').height
1016 # Returns the width of a string at this pointsize.
1018 # Not scaled since it deals with dimensions that the regular
1019 # scaling will handle.
1021 def calculate_width(font_size, text)
1022 @d.pointsize = font_size
1023 @d.get_type_metrics(@base_image, text.to_s).width
1028 class IncorrectNumberOfDatasetsException < StandardError; end
1037 # Additional method since Draw.scale doesn't affect annotations.
1038 def annotate_scaled(img, width, height, x, y, text, scale)
1039 scaled_width = (width * scale) >= 1 ? (width * scale) : 1
1040 scaled_height = (height * scale) >= 1 ? (height * scale) : 1
1043 scaled_width, scaled_height,
1044 x * scale, y * scale,