File: Plot.rb

package info (click to toggle)
ruby-svg-graph 2.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,312 kB
  • sloc: javascript: 23,548; ruby: 4,234; xml: 224; makefile: 2
file content (636 lines) | stat: -rw-r--r-- 17,889 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
require_relative 'Graph'
require_relative 'DataPoint'

module SVG
  module Graph
    # === For creating SVG plots of scalar data
    #
    # = Synopsis
    #
    #   require 'SVG/Graph/Plot'
    #
    #   # Data sets are x,y pairs
    #   # Note that multiple data sets can differ in length, and that the
    #   # data in the datasets needn't be in order; they will be ordered
    #   # by the plot along the X-axis.
    #   projection = [
    #     6, 11,    0, 5,   18, 7,   1, 11,   13, 9,   1, 2,   19, 0,   3, 13,
    #     7, 9
    #   ]
    #   actual = [
    #     0, 18,    8, 15,    9, 4,   18, 14,   10, 2,   11, 6,  14, 12,
    #     15, 6,   4, 17,   2, 12
    #   ]
    #
    #   graph = SVG::Graph::Plot.new({
    #   	:height => 500,
    #    	:width => 300,
    #     :key => true,
    #     :scale_x_integers => true,
    #     :scale_y_integers => true,
    #   })
    #
    #   graph.add_data({
    #   	:data => projection
    # 	  :title => 'Projected',
    #   })
    #
    #   graph.add_data({
    #   	:data => actual,
    # 	  :title => 'Actual',
    #   })
    #
    #   print graph.burn()
    #
    # = Description
    #
    # Produces a graph of scalar data.
    #
    # This object aims to allow you to easily create high quality
    # SVG[http://www.w3c.org/tr/svg] scalar plots. You can either use the
    # default style sheet or supply your own. Either way there are many options
    # which can be configured to give you control over how the graph is
    # generated - with or without a key, data elements at each point, title,
    # subtitle etc.
    #
    # = Examples
    #
    # https://github.com/lumean/svg-graph2/blob/master/examples/plot.rb
    #
    # = Notes
    #
    # The default stylesheet handles upto 12 data sets, if you
    # use more you must create your own stylesheet and add the
    # additional settings for the extra data sets. You will know
    # if you go over 12 data sets as they will have no style and
    # be in black.
    #
    # Unlike the other types of charts, data sets must contain x,y pairs:
    #
    #   [ 1,2 ]    # A data set with 1 point: (1,2)
    #   [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6)
    # Additional possible notation
    #   [ [1,2], 5,6] # A data set with 2 points: (1,2) and (5,6), mixed notation
    #   [ [1,2], [5,6]] # A data set with 2 points: (1,2) and (5,6), nested array
    #
    # = See also
    #
    # * SVG::Graph::Graph
    # * SVG::Graph::BarHorizontal
    # * SVG::Graph::Bar
    # * SVG::Graph::Line
    # * SVG::Graph::Pie
    # * SVG::Graph::TimeSeries
    #
    # == Author
    #
    # Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
    #
    # Copyright 2004 Sean E. Russell
    # This software is available under the Ruby license[LICENSE.txt]
    #
    class Plot < Graph

      # In addition to the defaults set by Graph::initialize, sets
      # [show_data_points] true
      # [area_fill] false
      # [stacked] false, will not have any effect if true
      # [show_lines] true
      # [round_popups] true
      def set_defaults
        init_with(
          :show_data_points  => true,
          :area_fill         => false,
          :stacked           => false,
          :show_lines        => true,
          :round_popups      => true,
          :scale_x_integers  => false,
          :scale_y_integers  => false,
         )
      end

      # Determines the scaling for the X axis divisions.
      #
      #   graph.scale_x_divisions = 2
      #
      # would cause the graph to attempt to generate labels stepped by 2; EG:
      # 0,2,4,6,8...
      # default is automatic such that there are 10 labels
      attr_accessor :scale_x_divisions
      # Determines the scaling for the Y axis divisions.
      #
      #   graph.scale_y_divisions = 0.5
      #
      # would cause the graph to attempt to generate labels stepped by 0.5; EG:
      # 0, 0.5, 1, 1.5, 2, ...
      # default is automatic such that there are 10 labels
      attr_accessor :scale_y_divisions
      # Make the X axis labels integers, default: false
      attr_accessor :scale_x_integers
      # Make the Y axis labels integers, default: false
      attr_accessor :scale_y_integers
      # Fill the area under the line, default: false
      attr_accessor :area_fill
      # Show a small circle on the graph where the line
      # goes from one point to the next. default: true
      attr_accessor :show_data_points
      # Set the minimum value of the X axis, if nil the minimum from data is chosen, default: nil
      attr_accessor :min_x_value
      # Set the maximum value of the X axis, if nil the maximum from data is chosen, default: nil
      attr_accessor :max_x_value
      # Set the minimum value of the Y axis, if nil the minimum from data is chosen, default: nil
      attr_accessor :min_y_value
      # Set the maximum value of the Y axis, if nil the maximum from data is chosen, default: nil
      attr_accessor :max_y_value
      # Show lines connecting data points, default: true
      attr_accessor :show_lines
      # Round value of data points in popups to integer, default: true
      attr_accessor :round_popups


      # Adds data to the plot.  The data must be in X,Y pairs; EG
      #   data_set1 = [ 1, 2 ]    # A data set with 1 point: (1,2)
      #   data_set2 = [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6)
      # It's also supported to supply nested array or a mix (flatten is applied to the array); EG
      #   data_set2 = [[1,2], 5,6]
      # or
      #   data_set2 = [[1,2], [5,6]]
      #
      #   graph.add_data({
      #     :data => data_set1,
      #     :title => 'single point'
      #   })
      #   graph.add_data({
      #     :data => data_set2,
      #     :title => 'two points'
      #   })
      # @param conf [Hash] with keys
      #          :data [Array] of x,y pairs, one pair for each point
      #          :title [String] mandatory name of data series for legend of graph
      #          :description [Array<String>] (optional) if given, description for each datapoint (shown in popups)
      #          :shape [Array<String>] (optional) if given, DataPoint shape is chosen based on this string instead of description
      #          :url [Array<String>] (optional)  if given, link will be added to each datapoint
      def add_data(conf)
        @data ||= []
        raise "No data provided by #{conf.inspect}" unless conf[:data].is_a?(Array)
        # support array of arrays and flatten it
        conf[:data] = conf[:data].flatten
        # check that we have pairs of values
        raise "Data supplied must be x,y pairs!  "+
          "The data provided contained an odd set of "+
          "data points" unless conf[:data].length % 2 == 0

        # clear the min/max x/y range caches
        clear_cache

        # remove nil values
        conf[:data] = conf[:data].compact

        return if conf[:data].length.zero?

        add_data_init_or_check_optional_keys(conf, conf[:data].size / 2)

        x = []
        y = []
        conf[:data].each_index {|i|
          (i%2 == 0 ? x : y) << conf[:data][i]
        }
        sort(x, y, conf[:description], conf[:shape], conf[:url])
        conf[:data] = [x, y]
        # at the end data looks like:
        # [
        #   [all x values],
        #   [all y values]
        # ]
        @data << conf
      end

      protected

      def keys
        @data.collect{ |x| x[:title] }
      end

      def calculate_left_margin
        super
        label_left = get_x_labels[0].to_s.length / 2 * font_size * 0.6
        @border_left = label_left if label_left > @border_left
      end

      def calculate_right_margin
        super
        label_right = get_x_labels[-1].to_s.length / 2 * font_size * 0.6
        @border_right = label_right if label_right > @border_right
      end

      X = 0
      Y = 1

      # procedure to clear all the cached variables used in working out the
      # max and min ranges for the chart
      def clear_cache
        @max_x_cache = @min_x_cache = @max_y_cache = @min_y_cache = nil
      end

      def max_x_range
        return @max_x_cache unless @max_x_cache.nil?

        # needs to be computed fresh when called, to cover the use-case:
        # add_data -> burn -> add_data -> burn
        # when values would be cached, the graph is not updated for second burning
        max_value = @data.collect{|x| x[:data][X][-1] }.max
        max_value = max_value > max_x_value ? max_value : max_x_value if max_x_value
        @max_x_cache = max_value
        @max_x_cache
      end

      def min_x_range
        return @min_x_cache unless @min_x_cache.nil?

        # needs to be computed fresh when called, to cover the use-case:
        # add_data -> burn -> add_data -> burn
        # when values would be cached, the graph is not updated for second burning
        min_value = @data.collect{|x| x[:data][X][0] }.min
        min_value = min_value < min_x_value ? min_value : min_x_value if min_x_value
        @min_x_cache = min_value
        @min_x_cache
      end

      # calculate the min and max x value as well as the scale division used for the x-axis
      def x_label_range
        max_value = max_x_range
        min_value = min_x_range
        range = max_value - min_value
        # add some padding on right
        if range == 0
          max_value += 10
        else
          max_value += range / 20.0
        end
        scale_range = max_value - min_value

        # either use the given step size or by default do 9 divisions.
        scale_division = scale_x_divisions || (scale_range / 9.0)
        @x_offset = 0

        if scale_x_integers
          scale_division = scale_division < 1 ? 1 : scale_division.ceil
          @x_offset = min_value.to_f - min_value.floor
          min_value = min_value.floor
        end

        [min_value, max_value, scale_division]
      end

      # get array of values for the x axis divisions, assuming left-most value starts
      # exactly where the graph starts.
      def get_x_values
        min_value, max_value, @x_scale_division = x_label_range
        x_times = ((max_value-min_value)/@x_scale_division).round + 1
        rv = []
        x_times.times{|v| rv << (min_value + (v * @x_scale_division))}
        return rv
      end
      alias :get_x_labels :get_x_values

      def field_width
        # exclude values which are outside max_x_range
        values = get_x_values
        @graph_width.to_f / (values.length - 1 ) # -1 is to use entire x-axis
                                                 # otherwise there is always 1 division unused
      end

      def max_y_range
        return @max_y_cache unless @max_y_cache.nil?

        max_value = @data.collect{|x| x[:data][Y].max }.max
        max_value = max_value > max_y_value ? max_value : max_y_value if max_y_value
        @max_y_cache = max_value
        @max_y_cache
      end

      def min_y_range
        return @min_y_cache unless @min_y_cache.nil?

        # needs to be computed fresh when called, to cover the use-case:
        # add_data -> burn -> add_data -> burn
        # when values would be cached, the graph is not updated for second burning
        min_value = @data.collect{|x| x[:data][Y].min }.min
        min_value = min_value < min_y_value ? min_value : min_y_value if min_y_value
        @min_y_cache = min_value
        @min_y_cache
      end

      def y_label_range
        max_value = max_y_range
        min_value = min_y_range
        range = max_value - min_value
        # add some padding on top
        if range == 0
          max_value += 10
        else
          max_value += range / 20.0
        end
        scale_range = max_value - min_value

        scale_division = scale_y_divisions || (scale_range / 9.0)
        @y_offset = 0

        if scale_y_integers
          scale_division = scale_division < 1 ? 1 : scale_division.ceil
          @y_offset = (min_value.to_f - min_value.floor).to_f
          min_value = min_value.floor
        end

        return [min_value, max_value, scale_division]
      end

      def get_y_values
        min_value, max_value, @y_scale_division = y_label_range
        if max_value != min_value
          while (max_value - min_value) < @y_scale_division
            @y_scale_division /= 9.0
          end
        end
        rv = []
        min_value.step( max_value + @y_scale_division, @y_scale_division ) {|v| rv << v}
        rv << rv[0] + 1 if rv.length == 1
        return rv
      end
      alias :get_y_labels :get_y_values

      def field_height
        # exclude values which are outside max_x_range
        values = get_y_values
        max = max_y_range
        if values.length == 1
          dx = values[-1]
        else
          dx = (max - values[-1]).to_f / (values[-1] - values[-2])
        end
        @graph_height.to_f / (values.length - 1)
      end

      # calculates the x,y coordinates of a datapoint in the plot area
      def calc_coords(x, y)
        coords = {:x => 0, :y => 0}
        # scale the coordinates, use float division / multiplication
        # otherwise the point will be place inaccurate
        coords[:x] = (x + @x_offset)/@x_scale_division.to_f * field_width
        coords[:y] = @graph_height - (y + @y_offset)/@y_scale_division.to_f * field_height
        return coords
      end

      def draw_data
        line = 1

        x_min = min_x_range
        y_min = min_y_range

        for data in @data
          x_points = data[:data][X]
          y_points = data[:data][Y]

          lpath = "L"
          x_start = 0
          y_start = 0
          x_points.each_index { |idx|
            c = calc_coords(x_points[idx] -  x_min, y_points[idx] -  y_min)
            x_start, y_start = c[:x],c[:y] if idx == 0
            lpath << "#{c[:x]} #{c[:y]} "
          }

          if area_fill
            @graph.add_element( "path", {
              "d" => "M#{x_start} #@graph_height #{lpath} V#@graph_height Z",
              "class" => "fill#{line}"
            })
          end

          if show_lines
            @graph.add_element( "path", {
              "d" => "M#{x_start} #{y_start} #{lpath}",
              "class" => "line#{line}"
            })
          end

          if show_data_points || show_data_values || add_popups
            x_points.each_index { |idx|
              c = calc_coords(x_points[idx] -  x_min, y_points[idx] -  y_min)
              if show_data_points
                shape_selection_string = data[:description][idx].to_s
                if !data[:shape][idx].nil?
                  shape_selection_string = data[:shape][idx].to_s
                end
                DataPoint.new(c[:x], c[:y], line).shape(shape_selection_string).each{|s|
                  @graph.add_element( *s )
                }
              end
              make_datapoint_text( c[:x], c[:y]-6, y_points[idx] )
              add_popup(c[:x], c[:y], format( x_points[idx], y_points[idx], data[:description][idx].to_s), "", data[:url][idx].to_s)
            }
          end
          line += 1
        end
      end

      # returns the formatted string which is added as popup information
      def format x, y, desc
        info = []
        info << (round_popups ? x.round : @number_format % x )
        info << (round_popups ? y.round : @number_format % y )
        info << desc if !desc.empty?
        "(#{info.compact.join(', ')})"
      end

      def get_css
        return <<EOL
/* default line styles */
.line1{
	fill: none;
	stroke: #ff0000;
	stroke-width: 1px;
}
.line2{
	fill: none;
	stroke: #0000ff;
	stroke-width: 1px;
}
.line3{
	fill: none;
	stroke: #00ff00;
	stroke-width: 1px;
}
.line4{
	fill: none;
	stroke: #ffcc00;
	stroke-width: 1px;
}
.line5{
	fill: none;
	stroke: #00ccff;
	stroke-width: 1px;
}
.line6{
	fill: none;
	stroke: #ff00ff;
	stroke-width: 1px;
}
.line7{
	fill: none;
	stroke: #00ffff;
	stroke-width: 1px;
}
.line8{
	fill: none;
	stroke: #ffff00;
	stroke-width: 1px;
}
.line9{
	fill: none;
	stroke: #cc6666;
	stroke-width: 1px;
}
.line10{
	fill: none;
	stroke: #663399;
	stroke-width: 1px;
}
.line11{
	fill: none;
	stroke: #339900;
	stroke-width: 1px;
}
.line12{
	fill: none;
	stroke: #9966FF;
	stroke-width: 1px;
}
/* default fill styles */
.fill1{
	fill: #cc0000;
	fill-opacity: 0.2;
	stroke: none;
}
.fill2{
	fill: #0000cc;
	fill-opacity: 0.2;
	stroke: none;
}
.fill3{
	fill: #00cc00;
	fill-opacity: 0.2;
	stroke: none;
}
.fill4{
	fill: #ffcc00;
	fill-opacity: 0.2;
	stroke: none;
}
.fill5{
	fill: #00ccff;
	fill-opacity: 0.2;
	stroke: none;
}
.fill6{
	fill: #ff00ff;
	fill-opacity: 0.2;
	stroke: none;
}
.fill7{
	fill: #00ffff;
	fill-opacity: 0.2;
	stroke: none;
}
.fill8{
	fill: #ffff00;
	fill-opacity: 0.2;
	stroke: none;
}
.fill9{
	fill: #cc6666;
	fill-opacity: 0.2;
	stroke: none;
}
.fill10{
	fill: #663399;
	fill-opacity: 0.2;
	stroke: none;
}
.fill11{
	fill: #339900;
	fill-opacity: 0.2;
	stroke: none;
}
.fill12{
	fill: #9966FF;
	fill-opacity: 0.2;
	stroke: none;
}
/* default line styles */
.key1,.dataPoint1{
	fill: #ff0000;
	stroke: none;
	stroke-width: 1px;
}
.key2,.dataPoint2{
	fill: #0000ff;
	stroke: none;
	stroke-width: 1px;
}
.key3,.dataPoint3{
	fill: #00ff00;
	stroke: none;
	stroke-width: 1px;
}
.key4,.dataPoint4{
	fill: #ffcc00;
	stroke: none;
	stroke-width: 1px;
}
.key5,.dataPoint5{
	fill: #00ccff;
	stroke: none;
	stroke-width: 1px;
}
.key6,.dataPoint6{
	fill: #ff00ff;
	stroke: none;
	stroke-width: 1px;
}
.key7,.dataPoint7{
	fill: #00ffff;
	stroke: none;
	stroke-width: 1px;
}
.key8,.dataPoint8{
	fill: #ffff00;
	stroke: none;
	stroke-width: 1px;
}
.key9,.dataPoint9{
	fill: #cc6666;
	stroke: none;
	stroke-width: 1px;
}
.key10,.dataPoint10{
	fill: #663399;
	stroke: none;
	stroke-width: 1px;
}
.key11,.dataPoint11{
	fill: #339900;
	stroke: none;
	stroke-width: 1px;
}
.key12,.dataPoint12{
	fill: #9966FF;
	stroke: none;
	stroke-width: 1px;
}
EOL
      end

    end
  end
end