1#!/opt/bin/lv_micropython -i
2import utime as time
3import lvgl as lv
4import display_driver
5
6def draw_event_cb(e):
7    dsc = e.get_draw_part_dsc()
8    if dsc.part == lv.PART.ITEMS:
9        obj = e.get_target()
10        ser = obj.get_series_next(None)
11        cnt = obj.get_point_count()
12        # print("cnt: ",cnt)
13        # Make older value more transparent
14        dsc.rect_dsc.bg_opa = (lv.OPA.COVER *  dsc.id) // (cnt - 1)
15
16        # Make smaller values blue, higher values red
17        # x_array = chart.get_x_array(ser)
18        # y_array = chart.get_y_array(ser)
19        # dsc->id is the tells drawing order, but we need the ID of the point being drawn.
20        start_point = chart.get_x_start_point(ser)
21        # print("start point: ",start_point)
22        p_act = (start_point + dsc.id) % cnt # Consider start point to get the index of the array
23        # print("p_act", p_act)
24        x_opa = (x_array[p_act] * lv.OPA._50) // 200
25        y_opa = (y_array[p_act] * lv.OPA._50) // 1000
26
27        dsc.rect_dsc.bg_color = lv.palette_main(lv.PALETTE.RED).color_mix(
28                                             lv.palette_main(lv.PALETTE.BLUE),
29                                             x_opa + y_opa)
30
31def add_data(timer,chart):
32    # print("add_data")
33    x = lv.rand(0,200)
34    y = lv.rand(0,1000)
35    chart.set_next_value2(ser, x, y)
36    # chart.set_next_value2(chart.gx, y)
37    x_array.pop(0)
38    x_array.append(x)
39    y_array.pop(0)
40    y_array.append(y)
41
42#
43# A scatter chart
44#
45
46chart = lv.chart(lv.scr_act())
47chart.set_size(200, 150)
48chart.align(lv.ALIGN.CENTER, 0, 0)
49chart.add_event_cb(draw_event_cb, lv.EVENT.DRAW_PART_BEGIN, None)
50chart.set_style_line_width(0, lv.PART.ITEMS)   # Remove the lines
51
52chart.set_type(lv.chart.TYPE.SCATTER)
53
54chart.set_axis_tick(lv.chart.AXIS.PRIMARY_X, 5, 5, 5, 1, True, 30)
55chart.set_axis_tick(lv.chart.AXIS.PRIMARY_Y, 10, 5, 6, 5, True, 50)
56
57chart.set_range(lv.chart.AXIS.PRIMARY_X, 0, 200)
58chart.set_range(lv.chart.AXIS.PRIMARY_Y, 0, 1000)
59
60chart.set_point_count(50)
61
62ser = chart.add_series(lv.palette_main(lv.PALETTE.RED), lv.chart.AXIS.PRIMARY_Y)
63
64x_array = []
65y_array = []
66for i in range(50):
67    x_array.append(lv.rand(0, 200))
68    y_array.append(lv.rand(0, 1000))
69
70ser.x_points = x_array
71ser.y_points = y_array
72
73# Create an `lv_timer` to update the chart.
74
75timer = lv.timer_create_basic()
76timer.set_period(100)
77timer.set_cb(lambda src: add_data(timer,chart))
78