1#!/usr/bin/env ruby
2
3require 'tk'
4require 'tkextlib/blt'
5
6# Example of a pareto chart.
7#
8# The pareto chart mixes line and bar elements in the same graph.
9# Each processing operating is represented by a bar element.  The
10# total accumulated defects is displayed with a single line element.
11b = Tk::BLT::Barchart.new(:title=>'Defects Found During Inspection',
12                          :font=>'Helvetica 12', :plotpady=>[12, 4],
13                          :width=>'6i', :height=>'5i')
14Tk::BLT::Table.add(Tk.root, b, :fill=>:both)
15
16data = [
17  ["Spot Weld",  82,   'yellow'],
18  ["Lathe",      49,   'orange'],
19  ["Gear Cut",   38,   'green'],
20  ["Drill",      24,   'blue'],
21  ["Grind",      17,   'red'],
22  ["Lapping",    12,   'brown'],
23  ["Press",       8,   'purple'],
24  ["De-burr",     4,   'pink'],
25  ["Packaging",   3,   'cyan'],
26  ["Other",      12,   'magenta']
27]
28
29# Create an X-Y graph line element to trace the accumulated defects.
30b.line_create('accum', :label=>'', :symbol=>:none, :color=>'red')
31
32# Define a bitmap to be used to stipple the background of each bar.
33pattern1 = Tk::BLT::Bitmap.define([ [4, 4], [1, 2, 4, 8] ])
34
35# For each process, create a bar element to display the magnitude.
36count = 0
37sum   = 0
38ydata = [0]
39xdata = [0]
40labels = []
41
42data.each{|label, value, color|
43  count += 1
44  b.element_create(label, :xdata=>count, :ydata=>value, :foreground=>color,
45                   :relief=>:solid, :borderwidth=>1, :stipple=>pattern1,
46                   :background=>'lightblue')
47  labels[count] = label
48  # Get the total number of defects.
49  sum += value
50  ydata << sum
51  xdata << count
52}
53
54# Configure the coordinates of the accumulated defects,
55# now that we know what they are.
56b.element_configure('accum', :xdata=>xdata, :ydata=>ydata)
57
58# Add text markers to label the percentage of total at each point.
59xdata.zip(ydata){|x, y|
60  percent = (y * 100.0) / sum
61  if x == 0
62    text = ' 0%'
63  else
64    text = '%.1f' % percent
65  end
66  b.marker_create(:text, :coords=>[x, y], :text=>text, :font=>'Helvetica 10',
67                  :foreground=>'red4', :anchor=>:center, :yoffset=>-5)
68}
69
70# Display an auxillary y-axis for percentages.
71b.axis_configure('y2', :hide=>false, :min=>0.0, :max=>100.0,
72                 :title=>'Percentage')
73
74# Title the y-axis
75b.axis_configure('y', :title=>'Defects')
76
77# Configure the x-axis to display the process names, instead of numbers.
78b.axis_configure('x', :title=>'Process', :rotate=>90, :subdivisions=>0,
79                 :command=>proc{|w, val|
80                   val = val.round
81                   labels[val]? labels[val]: val
82                  })
83
84# No legend needed.
85b.legend_configure(:hide=>true)
86
87# Configure the grid lines.
88b.gridline_configure(:mapx=>:x, :color=>'lightblue')
89
90Tk.mainloop
91