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 # A hash of names for the individual columns, where the key is the array index for the column this label represents.
46 # Not all columns need to be named.
48 # Example: 0 => 2005, 3 => 2006, 5 => 2007, 7 => 2008
51 # Used internally for spacing.
53 # By default, labels are centered over the point they represent.
54 attr_accessor :center_labels_over_point
56 # Used internally for horizontal graph types.
57 attr_accessor :has_left_labels
59 # A label for the bottom of the graph
60 attr_accessor :x_axis_label
62 # A label for the left side of the graph
63 attr_accessor :y_axis_label
65 # attr_accessor :x_axis_increment
67 # Manually set increment of the horizontal marking lines
68 attr_accessor :y_axis_increment
70 # Get or set the list of colors that will be used to draw the bars or lines.
73 # The large title of the graph displayed at the top
76 # Font used for titles, labels, etc. Works best if you provide the full path to the TTF font file.
77 # RMagick must be built with the Freetype libraries for this to work properly.
79 # Tries to find Bitstream Vera (Vera.ttf) in the location specified by
80 # ENV['MAGICK_FONT_PATH']. Uses default RMagick font otherwise.
83 attr_accessor :font_color
85 # Hide various elements
86 attr_accessor :hide_line_markers, :hide_legend, :hide_title, :hide_line_numbers
88 # Message shown when there is no data. Fits up to 20 characters. Defaults to "No Data."
89 attr_accessor :no_data_message
91 # The font size of the large title at the top of the graph
92 attr_accessor :title_font_size
94 # Optionally set the size of the font. Based on an 800x600px graph. Default is 20.
96 # Will be scaled down if graph is smaller than 800px wide.
97 attr_accessor :legend_font_size
99 # The font size of the labels around the graph
100 attr_accessor :marker_font_size
102 # The color of the auxiliary lines
103 attr_accessor :marker_color
105 # The number of horizontal lines shown for reference
106 attr_accessor :marker_count
109 # You can manually set a minimum value instead of having the values guessed for you.
111 # Set it after you have given all your data to the graph object.
112 attr_accessor :minimum_value
114 # You can manually set a maximum value, such as a percentage-based graph that always goes to 100.
116 # If you use this, you must set it after you have given all your data to the graph object.
117 attr_accessor :maximum_value
119 # Set to false if you don't want the data to be sorted with largest avg values at the back.
123 attr_accessor :additional_line_values
126 attr_accessor :stacked
129 # Optionally set the size of the colored box by each item in the legend. Default is 20.0
131 # Will be scaled down if graph is smaller than 800px wide.
132 attr_accessor :legend_box_size
135 # 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.).
137 # Or, send a geometry string for other ratios ('800x400', '400x225').
139 # 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.)
140 def initialize(target_width=800)
142 if not Numeric === target_width
143 geometric_width, geometric_height = target_width.split('x')
144 @columns = geometric_width.to_f
145 @rows = geometric_height.to_f
147 @columns = target_width.to_f
148 @rows = target_width.to_f * 0.75
158 # Set instance variables for this object.
160 # Subclasses can override this, call super, then set values separately.
162 # This makes it possible to set defaults in a subclass but still allow
163 # developers to change this values in their program.
166 # Internal for calculations
168 @raw_rows = 800.0 * (@rows/@columns)
171 @maximum_value = @minimum_value = nil
175 @labels_seen = Hash.new
179 @scale = @columns / @raw_columns
181 vera_font_path = File.expand_path('Vera.ttf', ENV['MAGICK_FONT_PATH'])
182 @font = File.exists?(vera_font_path) ? vera_font_path : nil
184 @marker_font_size = 21.0
185 @legend_font_size = 20.0
186 @title_font_size = 36.0
188 @legend_box_size = 20.0
190 @no_data_message = "No Data"
192 @hide_line_markers = @hide_legend = @hide_title = @hide_line_numbers = false
193 @center_labels_over_point = true
194 @has_left_labels = false
196 @additional_line_values = []
197 @additional_line_colors = []
200 @x_axis_label = @y_axis_label = nil
201 @y_axis_increment = nil
211 # Add a color to the list of available colors for lines.
214 # add_color('#c0e9d3')
215 def add_color(colorname)
220 # Replace the entire color list with a new array of colors. You need to have one more color
221 # than the number of datasets you intend to draw. Also aliased as the colors= setter method.
224 # replace_colors('#cc99cc', '#d9e043', '#34d8a2')
225 def replace_colors(color_list=[])
230 # You can set a theme manually. Assign a hash to this method before you send your data.
233 # :colors => %w(orange purple green white red),
234 # :marker_color => 'blue',
235 # :background_colors => %w(black grey)
238 # :background_image => 'squirrel.png' is also possible.
240 # (Or hopefully something better looking than that.)
246 :colors => ['black', 'white'],
247 :additional_line_colors => [],
248 :marker_color => 'white',
249 :font_color => 'black',
250 :background_colors => nil,
251 :background_image => nil
253 @theme_options = defaults.merge options
255 @colors = @theme_options[:colors]
256 @marker_color = @theme_options[:marker_color]
257 @font_color = @theme_options[:font_color] || @marker_color
258 @additional_line_colors = @theme_options[:additional_line_colors]
263 # A color scheme similar to the popular presentation software.
273 @colors = [@yellow, @blue, @green, @red, @purple, @orange, @white]
277 :marker_color => 'white',
278 :font_color => 'white',
279 :background_colors => ['black', '#4a465a']
283 # A color scheme plucked from the colors on the popular usability blog.
293 @colors = [@yellow, @blue, @green, @red, @purple, @orange, @black]
297 :marker_color => 'black',
298 :font_color => 'black',
299 :background_colors => ['#d1edf5', 'white']
303 # A color scheme from the colors used on the 2005 Rails keynote presentation at RubyConf.
304 def theme_rails_keynote
311 @light_grey = '#999999'
313 @colors = [@green, @grey, @orange, @red, @white, @light_grey, @black]
317 :marker_color => 'white',
318 :font_color => 'white',
319 :background_colors => ['#0083a3', '#0083a3']
323 # A color scheme similar to that used on the popular podcast site.
328 @dark_pink = '#a21764'
330 @light_grey = '#999999'
331 @dark_blue = '#3a5b87'
333 @colors = [@grey, @white, @dark_blue, @dark_pink, @green, @light_grey, @black]
337 :marker_color => 'white',
338 :font_color => 'white',
339 :background_colors => ['#ff47a4', '#ff1f81']
343 # Parameters are an array where the first element is the name of the dataset
344 # and the value is an array of values to plot.
346 # Can be called multiple times with different datasets for a multi-valued graph.
348 # If the color argument is nil, the next color from the default theme will be used.
350 # NOTE: If you want to use a preset theme, you must set it before calling data().
354 # data("Bart S.", [95, 45, 78, 89, 88, 76], '#ffcc00')
356 def data(name, data_points=[], color=nil)
357 data_points = Array(data_points) # make sure it's an array
358 @data << [name, data_points, (color || increment_color)]
359 # Set column count if this is larger than previous counts
360 @column_count = (data_points.length > @column_count) ? data_points.length : @column_count
363 data_points.each_with_index do |data_point, index|
364 next if data_point.nil?
366 # Setup max/min so spread starts at the low end of the data points
367 if @maximum_value.nil? && @minimum_value.nil?
368 @maximum_value = @minimum_value = data_point
371 # TODO Doesn't work with stacked bar graphs
372 # Original: @maximum_value = larger_than_max?(data_point, index) ? max(data_point, index) : @maximum_value
373 @maximum_value = larger_than_max?(data_point) ? data_point : @maximum_value
374 @has_data = true if @maximum_value > 0
376 @minimum_value = less_than_min?(data_point) ? data_point : @minimum_value
377 @has_data = true if @minimum_value < 0
381 # Writes the graph to a file. Defaults to 'graph.png'
383 # Example: write('graphs/my_pretty_graph.png')
384 def write(filename="graph.png")
386 @base_image.write(filename)
389 # Return the graph as a rendered binary blob.
390 def to_blob(fileformat='PNG')
392 return @base_image.to_blob do
393 self.format = fileformat
399 # Overridden by subclasses to do the actual plotting of the graph.
401 # Subclasses should start by calling super() for this method.
403 make_stacked if @stacked
408 @d.rectangle( LEFT_MARGIN, TOP_MARGIN,
409 @raw_columns - RIGHT_MARGIN, @raw_rows - BOTTOM_MARGIN)
411 @d.rectangle( @graph_left, @graph_top, @graph_right, @graph_bottom)
416 # Calculates size of drawable area and draws the decorations.
423 # Maybe should be done in one of the following functions for more granularity.
430 setup_graph_measurements()
431 sort_norm_data() if @sort # Sort norm_data with avg largest values set first (for display)
439 # Make copy of data with values scaled between 0-100
440 def normalize(force=false)
441 if @norm_data.nil? || force
443 return unless @has_data
447 @data.each do |data_row|
448 norm_data_points = []
449 data_row[DATA_VALUES_INDEX].each do |data_point|
451 norm_data_points << nil
453 norm_data_points << ((data_point.to_f - @minimum_value.to_f ) / @spread)
456 @norm_data << [data_row[DATA_LABEL_INDEX], norm_data_points, data_row[DATA_COLOR_INDEX]]
462 @spread = @maximum_value.to_f - @minimum_value.to_f
463 @spread = @spread > 0 ? @spread : 1
467 # Calculates size of drawable area, general font dimensions, etc.
469 def setup_graph_measurements
470 @marker_caps_height = calculate_caps_height(@marker_font_size)
471 @title_caps_height = calculate_caps_height(@title_font_size)
472 @legend_caps_height = calculate_caps_height(@legend_font_size)
474 if @hide_line_markers
477 @graph_bottom_margin) = [LEFT_MARGIN, RIGHT_MARGIN, BOTTOM_MARGIN]
479 longest_left_label_width = 0
481 longest_left_label_width = calculate_width(@marker_font_size,
482 labels.values.inject('') { |value, memo| (value.to_s.length > memo.to_s.length) ? value : memo }) * 1.25
484 longest_left_label_width = calculate_width(@marker_font_size,
485 label(@maximum_value.to_f))
488 # Shift graph if left line numbers are hidden
489 line_number_width = @hide_line_numbers && !@has_left_labels ?
491 (longest_left_label_width + LABEL_MARGIN * 2)
493 @graph_left = LEFT_MARGIN +
495 (@y_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN * 2)
496 # Make space for half the width of the rightmost column label.
497 # Might be greater than the number of columns if between-style bar markers are used.
498 last_label = @labels.keys.sort.last.to_i
499 extra_room_for_long_label = (last_label >= (@column_count-1) && @center_labels_over_point) ?
500 calculate_width(@marker_font_size, @labels[last_label])/2.0 :
502 @graph_right_margin = RIGHT_MARGIN + extra_room_for_long_label
504 @graph_bottom_margin = BOTTOM_MARGIN +
505 @marker_caps_height + LABEL_MARGIN
508 @graph_right = @raw_columns - @graph_right_margin
509 @graph_width = @raw_columns - @graph_left - @graph_right_margin
511 # When @hide title, leave a TITLE_MARGIN space for aesthetics.
512 # Same with @hide_legend
513 @graph_top = TOP_MARGIN +
514 (@hide_title ? TITLE_MARGIN : @title_caps_height + TITLE_MARGIN * 2) +
515 (@hide_legend ? LEGEND_MARGIN : @legend_caps_height + LEGEND_MARGIN * 2)
517 @graph_bottom = @raw_rows - @graph_bottom_margin -
518 (@x_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN)
520 @graph_height = @graph_bottom - @graph_top
523 # Draw the optional labels for the x axis and y axis.
525 unless @x_axis_label.nil?
527 # Centered vertically and horizontally by setting the
528 # height to 1.0 and the width to the width of the graph.
529 x_axis_label_y_coordinate = @graph_bottom + LABEL_MARGIN * 2 + @marker_caps_height
531 # TODO Center between graph area
532 @d.fill = @font_color
533 @d.font = @font if @font
534 @d.stroke('transparent')
535 @d.pointsize = scale_fontsize(@marker_font_size)
536 @d.gravity = NorthGravity
537 @d = @d.annotate_scaled( @base_image,
539 0.0, x_axis_label_y_coordinate,
540 @x_axis_label, @scale)
541 debug { @d.line 0.0, x_axis_label_y_coordinate, @raw_columns, x_axis_label_y_coordinate }
544 unless @y_axis_label.nil?
545 # Y Axis, rotated vertically
547 @d.gravity = CenterGravity
548 @d = @d.annotate_scaled( @base_image,
550 LEFT_MARGIN + @marker_caps_height / 2.0, 0.0,
551 @y_axis_label, @scale)
556 # Draws horizontal background lines and labels
557 def draw_line_markers
558 return if @hide_line_markers
560 @d = @d.stroke_antialias false
562 if @y_axis_increment.nil?
563 # Try to use a number of horizontal lines that will come out even.
565 # TODO Do the same for larger numbers...100, 75, 50, 25
566 if @marker_count.nil?
567 (3..7).each do |lines|
568 if @spread % lines == 0.0
569 @marker_count = lines
575 @increment = (@spread > 0) ? significant(@spread / @marker_count) : 1
577 # TODO Make this work for negative values
578 @maximum_value = [@maximum_value.ceil, @y_axis_increment].max
579 @minimum_value = @minimum_value.floor
583 @marker_count = (@spread / @y_axis_increment).to_i
584 @increment = @y_axis_increment
586 @increment_scaled = @graph_height.to_f / (@spread / @increment)
588 # Draw horizontal line markers and annotate with numbers
589 (0..@marker_count).each do |index|
590 y = @graph_top + @graph_height - index.to_f * @increment_scaled
592 @d = @d.stroke(@marker_color)
593 @d = @d.stroke_width 1
594 @d = @d.line(@graph_left, y, @graph_right, y)
596 marker_label = index * @increment + @minimum_value.to_f
598 unless @hide_line_numbers
599 @d.fill = @font_color
600 @d.font = @font if @font
601 @d.stroke('transparent')
602 @d.pointsize = scale_fontsize(@marker_font_size)
603 @d.gravity = EastGravity
605 # Vertically center with 1.0 for the height
606 @d = @d.annotate_scaled( @base_image,
607 @graph_left - LABEL_MARGIN, 1.0,
609 label(marker_label), @scale)
613 # # Submitted by a contibutor...the utility escapes me
615 # @additional_line_values.each do |value|
616 # @increment_scaled = @graph_height.to_f / (@maximum_value.to_f / value)
618 # y = @graph_top + @graph_height - @increment_scaled
620 # @d = @d.stroke(@additional_line_colors[i])
621 # @d = @d.line(@graph_left, y, @graph_right, y)
624 # @d.fill = @additional_line_colors[i]
625 # @d.font = @font if @font
626 # @d.stroke('transparent')
627 # @d.pointsize = scale_fontsize(@marker_font_size)
628 # @d.gravity = EastGravity
629 # @d = @d.annotate_scaled( @base_image,
631 # -10, y - (@marker_font_size/2.0),
636 @d = @d.stroke_antialias true
639 # Draws a legend with the names of the datasets
640 # matched to the colors used to draw them.
642 return if @hide_legend
644 @legend_labels = @data.collect {|item| item[DATA_LABEL_INDEX] }
646 legend_square_width = @legend_box_size # small square with color of this item
648 # May fix legend drawing problem at small sizes
649 @d.font = @font if @font
650 @d.pointsize = @legend_font_size
652 metrics = @d.get_type_metrics(@base_image, @legend_labels.join(''))
653 legend_text_width = metrics.width
654 legend_width = legend_text_width +
655 (@legend_labels.length * legend_square_width * 2.7)
656 legend_left = (@raw_columns - legend_width) / 2
657 legend_increment = legend_width / @legend_labels.length.to_f
659 current_x_offset = legend_left
660 current_y_offset = @hide_title ?
661 TOP_MARGIN + LEGEND_MARGIN :
663 TITLE_MARGIN + @title_caps_height +
666 debug { @d.line 0.0, current_y_offset, @raw_columns, current_y_offset }
668 @legend_labels.each_with_index do |legend_label, index|
671 @d.fill = @font_color
672 @d.font = @font if @font
673 @d.pointsize = scale_fontsize(@legend_font_size)
674 @d.stroke('transparent')
675 @d.font_weight = NormalWeight
676 @d.gravity = WestGravity
677 @d = @d.annotate_scaled( @base_image,
679 current_x_offset + (legend_square_width * 1.7), current_y_offset,
680 legend_label.to_s, @scale)
682 # Now draw box with color of this dataset
683 @d = @d.stroke('transparent')
684 @d = @d.fill @data[index][DATA_COLOR_INDEX]
685 @d = @d.rectangle(current_x_offset,
686 current_y_offset - legend_square_width / 2.0,
687 current_x_offset + legend_square_width,
688 current_y_offset + legend_square_width / 2.0)
690 @d.pointsize = @legend_font_size
691 metrics = @d.get_type_metrics(@base_image, legend_label.to_s)
692 current_string_offset = metrics.width + (legend_square_width * 2.7)
693 current_x_offset += current_string_offset
699 return if (@hide_title || @title.nil?)
701 @d.fill = @font_color
702 @d.font = @font if @font
703 @d.stroke('transparent')
704 @d.pointsize = scale_fontsize(@title_font_size)
705 @d.font_weight = BoldWeight
706 @d.gravity = NorthGravity
707 @d = @d.annotate_scaled( @base_image,
714 # Draws column labels below graph, centered over x_offset
716 # TODO Allow WestGravity as an option
718 def draw_label(x_offset, index, count=nil)
719 return if @hide_line_markers
721 if !@labels[index].nil? && @labels_seen[index].nil?
722 y_offset = @graph_bottom + LABEL_MARGIN
724 if count && (count % 2) == 1
725 y_offset += 1.5 * LABEL_MARGIN
728 @d.fill = @font_color
729 @d.font = @font if @font
730 @d.stroke('transparent')
731 @d.font_weight = NormalWeight
732 @d.pointsize = scale_fontsize(@marker_font_size)
733 @d.gravity = NorthGravity
734 @d = @d.annotate_scaled(@base_image,
737 @labels[index], @scale)
738 @labels_seen[index] = 1
739 debug { @d.line 0.0, y_offset, @raw_columns, y_offset }
744 @d.fill = @font_color
745 @d.font = @font if @font
746 @d.stroke('transparent')
747 @d.font_weight = NormalWeight
748 @d.pointsize = scale_fontsize(80)
749 @d.gravity = CenterGravity
750 @d = @d.annotate_scaled( @base_image,
751 @raw_columns, @raw_rows/2.0,
753 @no_data_message, @scale)
757 # Finds the best background to render based on the provided theme options.
759 # Creates a @base_image to draw on.
761 def render_background
762 case @theme_options[:background_colors]
764 @base_image = render_gradiated_background(*@theme_options[:background_colors])
766 @base_image = render_solid_background(@theme_options[:background_colors])
768 @base_image = render_image_background(*@theme_options[:background_image])
773 # Make a new image at the current size with a solid +color+.
775 def render_solid_background(color)
776 Image.new(@columns, @rows) {
777 self.background_color = color
781 # Use with a theme definition method to draw a gradiated background.
782 def render_gradiated_background(top_color, bottom_color)
783 Image.new(@columns, @rows,
784 GradientFill.new(0, 0, 100, 0, top_color, bottom_color))
787 # Use with a theme to use an image (800x600 original) background.
788 def render_image_background(image_path)
789 image = Image.read(image_path)
791 image[0].resize!(@scale) # TODO Resize with new scale (crop if necessary for wide graph)
796 # Use with a theme to make a transparent background
797 def render_transparent_background
798 Image.new(@columns, @rows) do
799 self.background_color = 'transparent'
809 # Scale down from 800x600 used to calculate drawing.
810 @d = @d.scale(@scale, @scale)
817 # Return a comparable fontsize for the current graph.
818 def scale_fontsize(value)
819 new_fontsize = value * @scale
820 # return new_fontsize < 10.0 ? 10.0 : new_fontsize
824 def clip_value_if_greater_than(value, max_value)
825 (value > max_value) ? max_value : value
828 # Overridden by subclasses such as stacked bar.
829 def larger_than_max?(data_point, index=0)
830 data_point > @maximum_value
833 def less_than_min?(data_point, index=0)
834 data_point < @minimum_value
838 # Overridden by subclasses that need it.
839 def max(data_point, index)
844 # Overridden by subclasses that need it.
845 def min(data_point, index)
850 return 1.0 if inc == 0 # Keep from going into infinite loop
862 res = inc.floor * factor
863 if (res.to_i.to_f == res)
870 # Sort with largest overall summed value at front of array
871 # so it shows up correctly in the drawn graph.
873 @norm_data.sort! { |a,b| sums(b[1]) <=> sums(a[1]) }
878 data_set.collect {|num| total_sum += num.to_f }
883 # Used by StackedBar and child classes.
885 # May need to be moved to the StackedBar class.
887 def get_maximum_by_stack
888 # Get sum of each stack
890 @data.each do |data_set|
891 data_set[DATA_VALUES_INDEX].each_with_index do |data_point, i|
892 max_hash[i] = 0.0 unless max_hash[i]
893 max_hash[i] += data_point.to_f
898 max_hash.keys.each do |key|
899 @maximum_value = max_hash[key] if max_hash[key] > @maximum_value
905 stacked_values = Array.new(@column_count, 0)
906 @data.each do |value_set|
907 value_set[1].each_with_index do |value, index|
908 stacked_values[index] += value
910 value_set[1] = stacked_values.dup
916 # Takes a block and draws it if DEBUG is true.
918 # debug { @d.rectangle x1, y1, x2, y2 }
922 @d = @d.fill 'transparent'
923 @d = @d.stroke 'turquoise'
933 if @color_index < @colors.length
935 return @colors[@color_index - 1]
945 # Return a formatted string representing a number value that should be printed as a label.
948 if (@spread.to_f % @marker_count.to_f == 0) || !@y_axis_increment.nil?
949 return value.to_i.to_s
953 sprintf("%0i", value)
955 sprintf("%0.2f", value)
962 # Returns the height of the capital letter 'X' for the current font and size.
964 # Not scaled since it deals with dimensions that the regular
965 # scaling will handle.
967 def calculate_caps_height(font_size)
968 @d.pointsize = font_size
969 @d.get_type_metrics(@base_image, 'X').height
973 # Returns the width of a string at this pointsize.
975 # Not scaled since it deals with dimensions that the regular
976 # scaling will handle.
978 def calculate_width(font_size, text)
979 @d.pointsize = font_size
980 @d.get_type_metrics(@base_image, text.to_s).width
985 class IncorrectNumberOfDatasetsException < StandardError; end
994 # Additional method since Draw.scale doesn't affect annotations.
995 def annotate_scaled(img, width, height, x, y, text, scale)
996 scaled_width = (width * scale) >= 1 ? (width * scale) : 1
997 scaled_height = (height * scale) >= 1 ? (height * scale) : 1
1000 scaled_width, scaled_height,
1001 x * scale, y * scale,