-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
test_figure_resampler.py
1958 lines (1608 loc) · 66 KB
/
test_figure_resampler.py
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Code which tests the FigureResampler functionalities"""
__author__ = "Jonas Van Der Donckt, Jeroen Van Der Donckt, Emiel Deprost"
import datetime
import multiprocessing
import subprocess
import sys
import time
from datetime import timedelta
from typing import List
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import pytest
from plotly.subplots import make_subplots
from selenium.webdriver.common.by import By
from plotly_resampler import LTTB, EveryNthPoint, FigureResampler
from plotly_resampler.aggregation import NoGapHandler, PlotlyAggregatorParser
# Note: this will be used to skip / alter behavior when running browser tests on
# non-linux platforms.
from .utils import construct_hf_data_dict, not_on_linux
def test_add_trace_kwarg_space(float_series, bool_series, cat_series):
# see: https://plotly.com/python/subplots/#custom-sized-subplot-with-subplot-titles
base_fig = make_subplots(
rows=2,
cols=2,
specs=[[{}, {}], [{"colspan": 2}, None]],
)
kwarg_space_list = [
{},
{
"default_downsampler": LTTB(),
"resampled_trace_prefix_suffix": tuple(["<b>[r]</b>", "~~"]),
"verbose": True,
},
]
for kwarg_space in kwarg_space_list:
fig = FigureResampler(base_fig, **kwarg_space)
fig.add_trace(
go.Scatter(x=float_series.index, y=float_series),
row=1,
col=1,
limit_to_view=False,
hf_text="text",
hf_hovertext="hovertext",
)
fig.add_trace(
go.Scatter(text="text", name="bool_series"),
hf_x=bool_series.index,
hf_y=bool_series,
row=1,
col=2,
limit_to_view=True,
)
fig.add_trace(
go.Scattergl(text="text", name="cat_series"),
row=2,
col=1,
downsampler=EveryNthPoint(),
hf_x=cat_series.index,
hf_y=cat_series,
limit_to_view=True,
)
def test_add_trace_not_resampling(float_series):
# see: https://plotly.com/python/subplots/#custom-sized-subplot-with-subplot-titles
base_fig = make_subplots(
rows=2,
cols=2,
specs=[[{}, {}], [{"colspan": 2}, None]],
)
fig = FigureResampler(base_fig, default_n_shown_samples=1000)
fig.add_trace(
go.Scatter(
x=float_series.index[:800], y=float_series[:800], name="float_series"
),
row=1,
col=1,
hf_text="text",
hf_hovertext="hovertext",
)
fig.add_trace(
go.Scatter(name="float_series"),
limit_to_view=False,
row=1,
col=1,
hf_x=float_series.index[-800:],
hf_y=float_series[-800:],
hf_text="text",
hf_hovertext="hovertext",
)
def test_add_trace_not_resampling_insert_gaps():
# This test verifies whether gaps are inserted correctly when adding a trace that
# is not resampled (but `limit_to_view` is True)
idx = np.arange(500)
for i in np.random.randint(0, 500, 4):
idx[i:] += 100
s = pd.Series(np.arange(500), index=idx)
# limit_to_view=False -> no gaps inserted
fr = FigureResampler(default_n_shown_samples=1000)
fr.add_trace({}, hf_x=s.index, hf_y=s.values)
fr.add_trace(dict(x=s.index, y=s.values))
assert np.isnan(fr.data[0]["y"]).sum() == 0
assert np.isnan(fr.data[1]["y"]).sum() == 0
# limit_to_view=True -> gaps inserted
fr = FigureResampler(default_n_shown_samples=1000)
fr.add_trace({}, hf_x=s.index, hf_y=s.values, limit_to_view=True)
fr.add_trace(dict(x=s.index, y=s.values), limit_to_view=True)
assert np.isnan(fr.data[0]["y"]).sum() > 0
assert np.isnan(fr.data[1]["y"]).sum() > 0
def test_various_dtypes(float_series):
# skip the test on windows
if sys.platform.lower().startswith("win"):
pytest.skip("Skipping test on windows")
# List of dtypes supported by orjson >= 3.8
valid_dtype_list = [
np.bool_,
# ---- uints
np.uint8,
np.uint16,
np.uint32,
np.uint64,
# -------- ints
np.int8,
np.int16,
np.int32,
np.int64,
# -------- floats
np.float16, # currently not supported by orjson
np.float32,
np.float64,
]
for dtype in valid_dtype_list:
if np.issubdtype(dtype, np.unsignedinteger):
fsv = float_series.astype("int").astype(dtype)
else:
fsv = float_series.astype(dtype)
fig = FigureResampler(go.Figure(), default_n_shown_samples=1000)
# nb. datapoints > default_n_shown_samples
fig.add_trace(
go.Scatter(name="float_series"),
hf_x=fsv.index,
hf_y=fsv,
)
fig.full_figure_for_development()
# List of dtypes not supported by orjson >= 3.8
invalid_dtype_list = [np.float16]
for invalid_dtype in invalid_dtype_list:
fig = FigureResampler(go.Figure(), default_n_shown_samples=1000)
# nb. datapoints < default_n_shown_samples
with pytest.raises(TypeError):
# if this test fails -> orjson supports f16 => remove casting frome code
fig.add_trace(
go.Scatter(name="float_series"),
hf_x=float_series.index[:500],
hf_y=float_series.astype(invalid_dtype)[:500],
)
fig.full_figure_for_development()
def test_max_n_samples(float_series):
s = float_series[:5000]
fig = FigureResampler()
fig.add_trace(
go.Scattergl(name="test"), hf_x=s.index, hf_y=s, max_n_samples=len(s) + 1
)
# make sure that there is not hf_data
assert len(fig.hf_data) == 0
assert len(fig.data[0]["x"]) == len(s)
def test_add_scatter_trace_no_data():
fig = FigureResampler(default_n_shown_samples=1000)
# no x and y data
fig.add_trace(go.Scatter())
def test_add_scatter_trace_no_x():
fig = FigureResampler(go.Figure(), default_n_shown_samples=1000)
# no x data
fig.add_trace(go.Scatter(y=[2, 1, 4, 3], name="s1"))
fig.add_trace(go.Scatter(name="s2"), hf_y=[2, 1, 4, 3])
def test_add_not_a_hf_trace(float_series):
# see: https://plotly.com/python/subplots/#custom-sized-subplot-with-subplot-titles
base_fig = make_subplots(
rows=2,
cols=2,
specs=[[{}, {}], [{"colspan": 2}, None]],
)
fig = FigureResampler(base_fig, default_n_shown_samples=1000, verbose=True)
fig.add_trace(
go.Scatter(
x=float_series.index[:800], y=float_series[:800], name="float_series"
),
row=1,
col=1,
hf_text="text",
hf_hovertext="hovertext",
)
# add a not hf-trace
fig.add_trace(
go.Histogram(
x=float_series,
name="float_series",
),
row=2,
col=1,
)
def test_box_histogram(float_series):
base_fig = make_subplots(
rows=2,
cols=2,
specs=[[{}, {}], [{"colspan": 2}, None]],
)
fig = FigureResampler(base_fig, default_n_shown_samples=1000, verbose=True)
fig.add_trace(
go.Scattergl(x=float_series.index, y=float_series, name="float_series"),
row=1,
col=1,
hf_text="text",
hf_hovertext="hovertext",
)
fig.add_trace(go.Box(x=float_series.values, name="float_series"), row=1, col=2)
fig.add_trace(
go.Box(x=float_series.values**2, name="float_series**2"), row=1, col=2
)
# add a not hf-trace
fig.add_trace(
go.Histogram(
x=float_series,
name="float_series",
),
row=2,
col=1,
)
def test_log_axis():
# This test utilizes tests whether a log axis is correctly handled
n = 100_000
y = np.sin(np.arange(n) / 2_000) + np.random.randn(n) / 10
for hf_x in [None, np.arange(n)]:
fr = FigureResampler()
fr.add_trace(
go.Scattergl(
mode="lines+markers", marker_color=np.abs(y) / np.max(np.abs(y))
),
hf_x=hf_x,
# NOTE: this y can be negative (as it is a noisy sin wave)
hf_y=np.abs(y),
max_n_samples=1000,
)
fr.update_xaxes(type="log")
fr.update_yaxes(type="log")
# Here, we update the xaxis range to be a log range
# A relayout event will return the log10 values of the range
x0, x1 = np.log10(100), np.log10(50_000)
out = fr._construct_update_data({"xaxis.range[0]": x0, "xaxis.range[1]": x1})
assert len(out) == 2
assert (x1 - x0) < 10
assert len(out[1]["x"]) == 1000
assert out[-1]["x"][0] >= 100
assert out[-1]["x"][-1] <= 50_000
def test_add_traces_from_other_figure():
labels = ["Investing", "Liquid", "Real Estate", "Retirement"]
values = [324643.4435821581, 112238.37140194925, 2710711.06, 604360.2864262027]
changes_section = FigureResampler(
make_subplots(
rows=1,
cols=2,
subplot_titles=("Asset Allocation", "Changes in last 12 hours"),
specs=[[{"type": "pie"}, {"type": "xy"}]],
)
)
# First create a pie chart Figure
pie_total = go.Figure(data=[go.Pie(labels=labels, values=values)])
# Add the pie chart traces to the changes_section figure
for trace in pie_total.data:
changes_section.add_trace(trace, row=1, col=1)
def test_cat_box_histogram(float_series):
# Create a categorical series, with mostly a's, but a few sparse b's and c's
cats_list = np.array(list("aaaaaaaaaa" * 1000))
cats_list[np.random.choice(len(cats_list), 100, replace=False)] = "b"
cats_list[np.random.choice(len(cats_list), 50, replace=False)] = "c"
cat_series = pd.Series(cats_list, dtype="category")
base_fig = make_subplots(
rows=2,
cols=2,
specs=[[{}, {}], [{"colspan": 2}, None]],
)
fig = FigureResampler(base_fig, default_n_shown_samples=1000, verbose=True)
fig.add_trace(
go.Scattergl(name="cat_series", x=cat_series.index, y=cat_series),
row=1,
col=1,
hf_text="text",
hf_hovertext="hovertext",
)
fig.add_trace(go.Box(x=float_series.values, name="float_box_pow"), row=1, col=2)
fig.add_trace(
go.Box(x=float_series.values**2, name="float_box_pow_2"), row=1, col=2
)
# add a not hf-trace
fig.add_trace(
go.Histogram(
x=float_series,
name="float_hist",
),
row=2,
col=1,
)
fig.update_layout(height=700)
def test_replace_figure(float_series):
# see: https://plotly.com/python/subplots/#custom-sized-subplot-with-subplot-titles
base_fig = make_subplots(
rows=2,
cols=2,
specs=[[{}, {}], [{"colspan": 2}, None]],
)
fr_fig = FigureResampler(base_fig, default_n_shown_samples=1000)
go_fig = go.Figure()
go_fig.add_trace(go.Scattergl(x=float_series.index, y=float_series, name="fs"))
fr_fig.replace(go_fig, convert_existing_traces=False)
# assert len(fr_fig.data) == 1
assert len(fr_fig.data[0]["x"]) == len(float_series)
# the orig float series data must still be the orig shape (we passed a view so
# we must check this)
assert len(go_fig.data[0]["x"]) == len(float_series)
fr_fig.replace(go_fig, convert_existing_traces=True)
# assert len(fr_fig.data) == 1
assert len(fr_fig.data[0]["x"]) == 1000
# the orig float series data must still be the orig shape (we passed a view so
# we must check this)
assert len(go_fig.data[0]["x"]) == len(float_series)
def test_replace_properties(float_series):
resampled_trace_prefix_suffix = ("a", "b")
verbose = True
default_n_shown_samples = 1050
default_gap_handler = NoGapHandler()
default_downsampler = EveryNthPoint()
fr_fig = FigureResampler(
default_n_shown_samples=default_n_shown_samples,
verbose=verbose,
resampled_trace_prefix_suffix=resampled_trace_prefix_suffix,
default_gap_handler=default_gap_handler,
default_downsampler=default_downsampler,
)
fr_fig.add_trace(go.Scattergl(x=float_series.index, y=float_series, name="fs"))
fr_fig.replace(go.Figure())
assert fr_fig._global_n_shown_samples == default_n_shown_samples
assert fr_fig._print_verbose == verbose
assert (fr_fig._prefix, fr_fig._suffix) == resampled_trace_prefix_suffix
assert fr_fig._global_gap_handler == default_gap_handler
assert fr_fig._global_downsampler == default_downsampler
def test_nan_retained_input(float_series):
# NEW from plotly-resampler >0.9.2 => we retain the NaNs in the input data and
# the NaN handling is delegated to the aggregators
# see: https://plotly.com/python/subplots/#custom-sized-subplot-with-subplot-titles
base_fig = make_subplots(
rows=2,
cols=2,
specs=[[{}, {}], [{"colspan": 2}, None]],
)
fig = FigureResampler(
base_fig,
default_n_shown_samples=1000,
resampled_trace_prefix_suffix=(
'<b style="color:sandybrown">[R]</b>',
'<b style="color:sandybrown">[R]</b>',
),
)
# ADD nans to to the float_series
float_series = float_series.copy()
float_series.iloc[
1 + np.random.choice(len(float_series) - 2, 100, replace=False)
] = np.nan
fig.add_trace(
go.Scatter(x=float_series.index, y=float_series, name="float_series"),
row=1,
col=1,
hf_text="text",
hf_hovertext="hovertext",
)
# Check the desired behavior - normally the NaNs are retained (no changes are made
# to the input data)
assert len(fig.hf_data[0]["y"]) == len(float_series)
assert pd.isna(fig.hf_data[0]["y"]).sum() == 100
# here we test whether we are able to deal with not-nan output
float_series.iloc[
1 + np.random.choice(len(float_series) - 2, 100, replace=False)
] = np.nan
fig.add_trace(
go.Scatter(
x=float_series.index, y=float_series
), # we explicitly do not add a name
hf_hovertext="mean" + float_series.rolling(10).mean().round(2).astype("str"),
row=2,
col=1,
)
float_series.iloc[
1 + np.random.choice(len(float_series) - 2, 100, replace=False)
] = np.nan
fig.add_trace(
go.Scattergl(
x=float_series.index,
y=float_series,
text="mean" + float_series.rolling(10).mean().round(2).astype("str"),
),
row=1,
col=2,
)
def test_hf_text():
y = np.arange(10_000)
fig = FigureResampler()
fig.add_trace(
go.Scatter(name="blabla", text=y.astype(str)),
hf_y=y,
)
assert np.all(fig.hf_data[0]["text"] == y.astype(str))
assert fig.hf_data[0]["hovertext"] is None
assert len(fig.data[0].y) < 5_000
assert np.all(fig.data[0].text == fig.data[0].y.astype(int).astype(str))
assert fig.data[0].hovertext is None
fig = FigureResampler()
fig.add_trace(go.Scatter(name="blabla"), hf_y=y, hf_text=y.astype(str))
assert np.all(fig.hf_data[0]["text"] == y.astype(str))
assert fig.hf_data[0]["hovertext"] is None
assert len(fig.data[0].y) < 5_000
assert np.all(fig.data[0].text == fig.data[0].y.astype(int).astype(str))
assert fig.data[0].hovertext is None
def test_hf_hovertext():
y = np.arange(10_000)
fig = FigureResampler()
fig.add_trace(
go.Scatter(name="blabla", hovertext=y.astype(str)),
hf_y=y,
)
assert np.all(fig.hf_data[0]["hovertext"] == y.astype(str))
assert fig.hf_data[0]["text"] is None
assert len(fig.data[0].y) < 5_000
assert np.all(fig.data[0].hovertext == fig.data[0].y.astype(int).astype(str))
assert fig.data[0].text is None
fig = FigureResampler()
fig.add_trace(go.Scatter(name="blabla"), hf_y=y, hf_hovertext=y.astype(str))
assert np.all(fig.hf_data[0]["hovertext"] == y.astype(str))
assert fig.hf_data[0]["text"] is None
assert len(fig.data[0].y) < 5_000
assert np.all(fig.data[0].hovertext == fig.data[0].y.astype(int).astype(str))
assert fig.data[0].text is None
def test_hf_text_and_hf_hovertext():
y = np.arange(10_000)
fig = FigureResampler()
fig.add_trace(
go.Scatter(name="blabla", text=y.astype(str), hovertext=y.astype(str)[::-1]),
hf_y=y,
)
assert np.all(fig.hf_data[0]["text"] == y.astype(str))
assert np.all(fig.hf_data[0]["hovertext"] == y.astype(str)[::-1])
assert len(fig.data[0].y) < 5_000
assert np.all(fig.data[0].text == fig.data[0].y.astype(int).astype(str))
assert np.all(
fig.data[0].hovertext == (9_999 - fig.data[0].y).astype(int).astype(str)
)
fig = FigureResampler()
fig.add_trace(
go.Scatter(name="blabla"),
hf_y=y,
hf_text=y.astype(str),
hf_hovertext=y.astype(str)[::-1],
)
assert np.all(fig.hf_data[0]["text"] == y.astype(str))
assert np.all(fig.hf_data[0]["hovertext"] == y.astype(str)[::-1])
assert len(fig.data[0].y) < 5_000
assert np.all(fig.data[0].text == fig.data[0].y.astype(int).astype(str))
assert np.all(
fig.data[0].hovertext == (9_999 - fig.data[0].y).astype(int).astype(str)
)
def test_hf_text_and_hf_marker_color():
# Test for https://github.com/predict-idlab/plotly-resampler/issues/224
fig = FigureResampler(default_n_shown_samples=1_000)
x = pd.date_range("1-1-2000", "1-1-2001", periods=2_000)
y = np.sin(100 * np.arange(len(x)) / len(x))
text = [f'text: {yi}, color:{"black" if yi>=0.99 else "blue"}' for yi in y]
marker_color = ["black" if yi >= 0.99 else "blue" for yi in y]
trace = go.Scatter(
x=x,
y=y,
marker={"color": marker_color},
text=text,
)
fig.add_trace(trace)
# Check correct data types
assert not isinstance(fig.hf_data[0]["text"], (tuple, list))
assert fig.hf_data[0]["hovertext"] is None
assert not isinstance(fig.hf_data[0]["marker_color"], (tuple, list))
assert fig.hf_data[0]["marker_size"] is None
# Check correct hf values
assert np.all(list(fig.hf_data[0]["text"]) == text)
assert np.all(list(fig.hf_data[0]["marker_color"]) == marker_color)
# Check correct trace values
assert len(fig.data[0].y) == len(fig.data[0].text)
assert len(fig.data[0].y) == len(fig.data[0].marker.color)
y_color = ["black" if yi >= 0.99 else "blue" for yi in fig.data[0].y]
assert np.all(list(fig.data[0].marker.color) == y_color)
y_text = [f"text: {yi}, color:{ci}" for yi, ci in zip(fig.data[0].y, y_color)]
assert np.all(list(fig.data[0].text) == y_text)
def test_hf_text_and_hf_hovertext_and_hf_marker_size_nans():
y_orig = np.arange(10_000).astype(float)
y = y_orig.copy()
y[1::101] = np.nan
# NEW from plotly-resampler >0.9.2 => we retain the NaNs in the input data and
# the NaN handling is delegated to the aggregators
y_nonan = y # we do not remove the NaNs anymore
fig = FigureResampler()
fig.add_trace(
go.Scatter(
name="blabla",
text=y.astype(str),
hovertext=y.astype(str)[::-1],
marker={"size": y_orig},
),
hf_y=y,
)
assert np.all(fig.hf_data[0]["text"] == y_nonan.astype(str))
assert np.all(fig.hf_data[0]["hovertext"] == y_nonan.astype(str)[::-1])
assert np.all(fig.hf_data[0]["marker_size"] == y_orig)
fig = FigureResampler()
fig.add_trace(
go.Scatter(name="blabla"),
hf_y=y,
hf_text=y.astype(str),
hf_hovertext=y.astype(str)[::-1],
hf_marker_size=y_orig,
)
assert np.all(fig.hf_data[0]["text"] == y_nonan.astype(str))
assert np.all(fig.hf_data[0]["hovertext"] == y_nonan.astype(str)[::-1])
assert np.all(fig.hf_data[0]["marker_size"] == y_orig)
def test_multiple_timezones():
n = 5_050
# NOTE: date-range returns a (tz-aware) DatetimeIndex
dr = pd.date_range("2022-02-14", freq="s", periods=n, tz="UTC")
dr_v = np.random.randn(n)
cs = [
dr,
dr.tz_localize(None).tz_localize("Europe/Amsterdam"),
dr.tz_convert("Europe/Brussels"),
dr.tz_convert("Australia/Perth"),
dr.tz_convert("Australia/Canberra"),
# NOTE: this pd.Series tests the functionality of a Pandas series with (tz-aware) DatetimeIndex
pd.Series(dr),
pd.Series(dr.tz_localize(None).tz_localize("Europe/Amsterdam")),
pd.Series(dr.tz_convert("Europe/Brussels")),
pd.Series(dr.tz_convert("Australia/Perth")),
pd.Series(dr.tz_convert("Australia/Canberra")),
]
plain_plotly_fig = make_subplots(rows=len(cs), cols=1, shared_xaxes=True)
plain_plotly_fig.update_layout(height=min(300, 250 * len(cs)))
fr_fig = FigureResampler(
make_subplots(rows=len(cs), cols=1, shared_xaxes=True),
default_n_shown_samples=500,
convert_existing_traces=False,
verbose=True,
)
fr_fig.update_layout(height=min(300, 250 * len(cs)))
for i, date_range in enumerate(cs, 1):
name = date_range.dtype.name.split(", ")[-1][:-1]
plain_plotly_fig.add_trace(
go.Scattergl(x=date_range, y=dr_v, name=name), row=i, col=1
)
fr_fig.add_trace(
go.Scattergl(name=name),
hf_x=date_range,
hf_y=dr_v,
row=i,
col=1,
)
# Assert that the time parsing is exactly the same
assert plain_plotly_fig.data[i - 1].x[0] == fr_fig.data[i - 1].x[0]
def test_set_hfx_tz_aware_series():
df = pd.DataFrame(
{
"timestamp": pd.date_range(
"2020-01-01", "2020-01-02", freq="1s"
).tz_localize("Asia/Seoul")
}
)
df["value"] = np.random.randn(len(df))
fr = FigureResampler()
fr.add_trace({}, hf_x=pd.Index(df.timestamp), hf_y=df.value)
assert isinstance(fr.hf_data[0]["x"], pd.DatetimeIndex)
# Now we set the pd.Series as hf_x
fr.hf_data[0]["x"] = df.timestamp
assert not isinstance(fr.hf_data[0]["x"], pd.DatetimeIndex)
# perform an update
out = fr._construct_update_data(
{"xaxis.autorange": True, "xaxis.showspikes": False}
)
assert len(out) == 2
# assert that the update was performed correctly
assert isinstance(fr.hf_data[0]["x"], pd.DatetimeIndex)
assert all(fr.hf_data[0]["x"] == pd.DatetimeIndex(df.timestamp))
def test_tz_xaxis_range():
# test related to issue 212 - github.com/predict-idlab/plotly-resampler/issues/212
n = 50_000
s = pd.Series(
index=pd.date_range("2020-01-01", periods=n, freq="1min", tz="UTC"),
data=23 + np.random.randn(n),
)
fig = go.Figure(
layout=go.Layout(
title=dict(
text="AirT test timeseries",
y=0.98,
x=0.5,
xanchor="center",
yanchor="top",
),
xaxis=dict(title="Time", type="date"),
yaxis=dict(title="Air Temp (ºC)", range=[20, 30], fixedrange=True),
template="seaborn",
margin=dict(l=50, r=50, t=50, b=50, pad=5),
showlegend=True,
)
)
fr = FigureResampler(fig, verbose=True, default_n_shown_samples=2000)
fr.add_trace(go.Scattergl(name="AirT", mode="markers"), hf_x=s.index, hf_y=s)
fr.add_trace(go.Scattergl(name="AirT", mode="markers", x=s.index, y=s))
fr.add_vline(x=s.index[0])
fr.add_vline(x=s.index[-1])
start = s.index[0] - timedelta(hours=48)
end = s.index[-1] + timedelta(hours=48)
fr.update_xaxes(range=[start, end])
# verify whether the update was performed correctly
out = fr._construct_update_data({"xaxis.range[0]": start, "xaxis.range[1]": end})
assert len(out) == 3
assert len(out[1]["x"]) == 2000
assert len(out[2]["x"]) == 2000
def test_compare_tz_with_fixed_offset():
# related: https://github.com/predict-idlab/plotly-resampler/issues/305
fig = FigureResampler()
x = pd.date_range("2024-04-01T00:00:00", "2025-01-01T00:00:00", freq="H")
x = x.tz_localize("Asia/Taipei")
y = np.random.randn(len(x))
fig.add_trace(
go.Scattergl(x=x, y=y, name="demo", mode="lines+markers"),
max_n_samples=int(len(x) * 0.2),
)
relayout_data = {
"xaxis.range[0]": "2024-04-27T08:00:00+08:00",
"xaxis.range[1]": "2024-05-04T17:15:39.491031+08:00",
}
fig.construct_update_data_patch(relayout_data)
def test_compare_tz_with_fixed_offset_2():
# related: https://github.com/predict-idlab/plotly-resampler/issues/305
fig = FigureResampler()
x = pd.date_range("2024-04-01T00:00:00", "2025-01-01T00:00:00", freq="H")
x = x.tz_localize("UTC")
x = x.tz_convert("Canada/Pacific")
y = np.random.randn(len(x))
fig.add_trace(
go.Scattergl(x=x, y=y, name="demo", mode="lines+markers"),
max_n_samples=int(len(x) * 0.2),
)
relayout_data = {
"xaxis.range[0]": pd.Timestamp("2024-03-01T00:00:00").tz_localize(
"Canada/Pacific"
),
"xaxis.range[1]": pd.Timestamp("2024-03-31T00:00:00").tz_localize(
"Canada/Pacific"
),
}
fig.construct_update_data_patch(relayout_data)
def test_datetime_hf_x_no_index():
df = pd.DataFrame(
{"timestamp": pd.date_range("2020-01-01", "2020-01-02", freq="1s")}
)
df["value"] = np.random.randn(len(df))
# add via hf_x kwargs
fr = FigureResampler()
fr.add_trace({}, hf_x=df.timestamp, hf_y=df.value)
output = fr._construct_update_data(
{
"xaxis.range[0]": "2020-01-01 00:00:00",
"xaxis.range[1]": "2020-01-01 00:00:20",
}
)
assert len(output) == 2
assert isinstance(output[1]["x"], pd.Index)
# add via scatter kwargs
fr = FigureResampler()
fr.add_trace(go.Scatter(x=df.timestamp, y=df.value))
output = fr._construct_update_data(
{
"xaxis.range[0]": "2020-01-01 00:00:00",
"xaxis.range[1]": "2020-01-01 00:00:20",
}
)
assert len(output) == 2
assert isinstance(output[1]["x"], pd.Index)
def test_multiple_timezones_in_single_x_index__datetimes_and_timestamps():
# TODO: can be improved with pytest parametrize
y = np.arange(20)
index1 = pd.date_range("2018-01-01", periods=10, freq="H", tz="US/Eastern")
index2 = pd.date_range("2018-01-02", periods=10, freq="H", tz="Asia/Dubai")
index_timestamps = index1.append(index2)
assert all(isinstance(x, pd.Timestamp) for x in index_timestamps)
index1_datetimes = pd.Index([x.to_pydatetime() for x in index1])
index_datetimes = pd.Index([x.to_pydatetime() for x in index_timestamps])
assert not any(isinstance(x, pd.Timestamp) for x in index_datetimes)
assert all(isinstance(x, datetime.datetime) for x in index_datetimes)
## Test why we throw ValueError if array is still of object type after
## successful pd.to_datetime call
# String array of datetimes with same tz -> NOT object array
assert not pd.to_datetime(index1.astype("str")).dtype == "object"
assert not pd.to_datetime(index1_datetimes.astype("str")).dtype == "object"
# String array of datetimes with multiple tz -> object array
assert pd.to_datetime(index_timestamps.astype("str")).dtype == "object"
assert pd.to_datetime(index_datetimes.astype("str")).dtype == "object"
for index in [index_timestamps, index_datetimes]:
fig = go.Figure()
fig.add_trace(go.Scattergl(x=index, y=y))
with pytest.raises(ValueError):
fr_fig = FigureResampler(fig, default_n_shown_samples=10)
# Add as hf_x as index
fr_fig = FigureResampler(default_n_shown_samples=10)
with pytest.raises(ValueError):
fr_fig.add_trace(go.Scattergl(), hf_x=index, hf_y=y)
# Add as hf_x as object array of datetime values
fr_fig = FigureResampler(default_n_shown_samples=10)
with pytest.raises(ValueError):
fr_fig.add_trace(go.Scattergl(), hf_x=index.values.astype("object"), hf_y=y)
# Add as hf_x as string array
fr_fig = FigureResampler(default_n_shown_samples=10)
with pytest.raises(ValueError):
fr_fig.add_trace(go.Scattergl(), hf_x=index.astype(str), hf_y=y)
# Add as hf_x as object array of strings
fr_fig = FigureResampler(default_n_shown_samples=10)
with pytest.raises(ValueError):
fr_fig.add_trace(
go.Scattergl(), hf_x=index.astype(str).astype("object"), hf_y=y
)
fig = go.Figure()
fig.add_trace(go.Scattergl(x=index.astype("object"), y=y))
with pytest.raises(ValueError):
fr_fig = FigureResampler(fig, default_n_shown_samples=10)
fig = go.Figure()
fig.add_trace(go.Scattergl(x=index.astype("str"), y=y))
with pytest.raises(ValueError):
fr_fig = FigureResampler(fig, default_n_shown_samples=10)
def test_proper_copy_of_wrapped_fig(float_series):
plotly_fig = go.Figure()
plotly_fig.add_trace(
go.Scatter(
x=float_series.index,
y=float_series,
)
)
plotly_resampler_fig = FigureResampler(plotly_fig, default_n_shown_samples=500)
assert len(plotly_fig.data) == 1
assert all(plotly_fig.data[0].x == float_series.index)
assert all(plotly_fig.data[0].y == float_series.values)
assert (len(plotly_fig.data[0].x) > 500) & (len(plotly_fig.data[0].y) > 500)
assert len(plotly_resampler_fig.data) == 1
assert len(plotly_resampler_fig.data[0].x) == 500
assert len(plotly_resampler_fig.data[0].y) == 500
def test_low_dim_input():
fig = go.Figure()
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[1, 2, 3], name="a"))
fig = FigureResampler(go.Figure())
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[1, 2, 3], name="a"))
fig.add_trace(go.Scatter(), hf_x=[1, 2, 3], hf_y=[1, 2, 3])
def test_2d_input_y():
# Create some dummy dataframe with a nan
df = pd.DataFrame(
index=np.arange(5_000), data={"a": np.arange(5_000), "b": np.arange(5_000)}
)
df.iloc[42] = np.nan
plotly_fig = go.Figure()
plotly_fig.add_trace(
go.Scatter(
x=df.index,
y=df[["a"]], # (100, 1) shape
)
)
with pytest.raises(AssertionError) as e_info:
_ = FigureResampler( # does not alter plotly_fig
plotly_fig,
default_n_shown_samples=500,
)
assert "1 dimensional" in e_info
def test_hf_x_object_array():
y = np.random.randn(100)
## Object array of datetime
### Should be parsed to a pd.DatetimeIndex (is more efficient than object array)
x = pd.date_range("2020-01-01", freq="s", periods=100).astype("object")
assert x.dtype == "object"
assert isinstance(x[0], pd.Timestamp)
# Add in the scatter
fig = FigureResampler(default_n_shown_samples=50)
fig.add_trace(go.Scatter(name="blabla", x=x, y=y))
assert isinstance(fig.hf_data[0]["x"], pd.DatetimeIndex)
assert isinstance(fig.hf_data[0]["x"][0], pd.Timestamp)
# Add as hf_x
fig = FigureResampler(default_n_shown_samples=50)
fig.add_trace(go.Scatter(name="blabla"), hf_x=x, hf_y=y)
assert isinstance(fig.hf_data[0]["x"], pd.DatetimeIndex)
assert isinstance(fig.hf_data[0]["x"][0], pd.Timestamp)
## Object array of datetime strings
### Should be parsed to a pd.DatetimeIndex (is more efficient than object array)
x = pd.date_range("2020-01-01", freq="s", periods=100).astype(str).astype("object")
assert x.dtype == "object"
assert isinstance(x[0], str)
# Add in the scatter
fig = FigureResampler(default_n_shown_samples=50)
fig.add_trace(go.Scatter(name="blabla", x=x, y=y))
assert isinstance(fig.hf_data[0]["x"], pd.DatetimeIndex)
assert isinstance(fig.hf_data[0]["x"][0], pd.Timestamp)
# Add as hf_x
fig = FigureResampler(default_n_shown_samples=50)
fig.add_trace(go.Scatter(name="blabla"), hf_x=x, hf_y=y)
assert isinstance(fig.hf_data[0]["x"], pd.DatetimeIndex)
assert isinstance(fig.hf_data[0]["x"][0], pd.Timestamp)
## Object array of ints
### Should be parsed to an int array (is more efficient than object array)
x = np.arange(100).astype("object")
assert x.dtype == "object"
assert isinstance(x[0], int)
# Add in the scatter
fig = FigureResampler(default_n_shown_samples=50)
fig.add_trace(go.Scatter(name="blabla", x=x, y=y))
assert np.issubdtype(fig.hf_data[0]["x"].dtype, np.integer)
# Add as hf_x
fig = FigureResampler(default_n_shown_samples=50)
fig.add_trace(go.Scatter(name="blabla"), hf_x=x, hf_y=y)
assert np.issubdtype(fig.hf_data[0]["x"].dtype, np.integer)
## Object array of ints as strings
### Should be an integer array where the values are int objects
x = np.arange(100).astype(str).astype("object")