Skip to content

Commit a476ce8

Browse files
committed
exponential trend example grafica
1 parent 54fedf4 commit a476ce8

File tree

1 file changed

+73
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)