|
| 1 | +#!/usr/bin/env jruby |
| 2 | +# frozen_string_literal: true |
| 3 | + |
| 4 | +require 'picrate' |
| 5 | + |
| 6 | +class ExponentialTrend < Processing::App |
| 7 | + |
| 8 | + load_library 'grafica' |
| 9 | + java_import 'grafica.GPointsArray' |
| 10 | + java_import 'grafica.GPlot' |
| 11 | + java_import 'java.util.Random' |
| 12 | + |
| 13 | + N_POINTS = 1_000 |
| 14 | + attr_reader :plot, :log_scale, :random, :points |
| 15 | + |
| 16 | + def settings |
| 17 | + size(450, 450) |
| 18 | + end |
| 19 | + |
| 20 | + def setup |
| 21 | + sketch_title 'Exponential Trend' |
| 22 | + @random = Random.new |
| 23 | + # Prepare the points for the plot |
| 24 | + @points = GPointsArray.new(N_POINTS) |
| 25 | + @plot = GPlot.new(self) |
| 26 | + puts plot.inspect |
| 27 | + @log_scale = false |
| 28 | + N_POINTS.times do |
| 29 | + x_value = rand(10..200) |
| 30 | + y_value = 10**(0.015 * x_value) |
| 31 | + x_error = 2 * random.next_gaussian |
| 32 | + y_error = 2 * random.next_gaussian |
| 33 | + points.add(x_value + x_error, y_value + y_error) |
| 34 | + end |
| 35 | + # Create the plot |
| 36 | + plot.set_pos(25, 25) |
| 37 | + plot.set_dim(300, 300) |
| 38 | + # or all in one go |
| 39 | + # plot = GPlot.new(self, 25, 25, 300, 300) |
| 40 | + # Set the plot title and the axis labels |
| 41 | + plot.set_title_text('Exponential law') |
| 42 | + # NB: cannot use snake for getXAxis etc |
| 43 | + plot.getXAxis.set_axis_label_text('x') |
| 44 | + toggle_y_axis |
| 45 | + # Add the points to the plot |
| 46 | + plot.set_points(points) |
| 47 | + plot.set_point_color(color(100, 100, 255, 50)) |
| 48 | + end |
| 49 | + |
| 50 | + def draw |
| 51 | + background(150) |
| 52 | + plot.begin_draw |
| 53 | + plot.draw_background |
| 54 | + plot.draw_box |
| 55 | + plot.drawXAxis |
| 56 | + plot.drawYAxis |
| 57 | + plot.draw_top_axis |
| 58 | + plot.draw_right_axis |
| 59 | + plot.draw_title |
| 60 | + plot.draw_points |
| 61 | + plot.end_draw |
| 62 | + end |
| 63 | + |
| 64 | + def toggle_y_axis |
| 65 | + y_axis = plot.getYAxis |
| 66 | + if log_scale |
| 67 | + plot.set_log_scale('y') |
| 68 | + y_axis.set_axis_label_text('log y') |
| 69 | + else |
| 70 | + plot.set_log_scale('') |
| 71 | + y_axis.set_axis_label_text('y') |
| 72 | + end |
| 73 | + end |
| 74 | + |
| 75 | + def mouse_clicked |
| 76 | + @log_scale = !log_scale |
| 77 | + toggle_y_axis |
| 78 | + end |
| 79 | +end |
| 80 | + |
| 81 | +ExponentialTrend.new |
0 commit comments