lib/gruff/pie.rb in gruff-0.0.9 vs lib/gruff/pie.rb in gruff-0.1.0

- old
+ new

@@ -12,48 +12,80 @@ diameter = @graph_height radius = @graph_height / 2.0 top_x = @graph_left + (@graph_width - diameter) / 2.0 center_x = @graph_left + (@graph_width / 2.0) - center_y = @graph_top + (@graph_height / 2.0) + center_y = @graph_top + (@graph_height / 2.0) - 10 # Move graph up a bit total_sum = sums_for_pie() prev_degrees = 0.0 - @norm_data.each do |data_row| - @d = @d.stroke current_color - @d = @d.fill 'transparent' - @d.stroke_width(200.0) + # Use full data since we can easily calculate percentages + @data.each do |data_row| + if data_row[1][0] > 0 + @d = @d.stroke data_row[DATA_COLOR_INDEX] + @d = @d.fill 'transparent' + @d.stroke_width(200.0) - current_degrees = (data_row[1][0] / total_sum) * 360.0 - #@d = @d.pie_slice(center_x, center_y, radius, - # current_percent * 100.0) - - #@d = @d.arc(top_x, @graph_top, - # top_x + diameter, @graph_top + diameter, - # prev_degrees, prev_degrees + current_degrees) - radius = 100.0 - @d = @d.ellipse(center_x, center_y, + current_degrees = (data_row[1][0] / total_sum) * 360.0 + radius = 100.0 + @d = @d.ellipse(center_x, center_y, radius, radius, - prev_degrees, prev_degrees + current_degrees) + prev_degrees, prev_degrees + current_degrees + 0.5) # <= +0.5 'fudge factor' gets rid of the ugly gaps + + half_angle = prev_degrees + ((prev_degrees + current_degrees) - prev_degrees) / 2 + + @d = draw_label(center_x,center_y, + half_angle, + radius, + ((data_row[1][0] / total_sum) * 100).round.to_s + '% ') - prev_degrees += current_degrees - increment_color() + prev_degrees += current_degrees + end end @d.draw(@base_image) end private + def draw_label(center_x, center_y, angle, radius, amount) + r_offset = 130 # The distance out from the center of the pie to get point + x_offset = center_x + 15 # The label points need to be tweaked slightly + y_offset = center_y + 0 # This one doesn't though + x = x_offset + ((radius + r_offset) * Math.cos(angle.deg2rad)) + y = y_offset + ((radius + r_offset) * Math.sin(angle.deg2rad)) + + # Draw label + @d.fill = @marker_color + @d.font = @font + @d.pointsize = scale_fontsize(20) + @d.stroke = 'transparent' + @d.font_weight = BoldWeight + @d.gravity = CenterGravity + @d.annotate_scaled( @base_image, + 0, 0, + x, y, + amount, @scale) + end + def sums_for_pie total_sum = 0.0 - @norm_data.collect {|data_row| total_sum += data_row[1][0] } + @data.collect {|data_row| total_sum += data_row[1][0] } total_sum end end + +class Float + # Used for degree => radian conversions + def deg2rad + self * (Math::PI/180.0) + end +end + +# From sparklines...not currently used class Magick::Draw def pie_slice(center_x=0.0, center_y=0.0, radius=100.0, percent=0.0, rot_x=0.0) # Okay, this part is as confusing as hell, so pay attention: # This line determines the horizontal portion of the point on the circle where the X-Axis