FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
prophet/python/prophet/plot.py at main · facebook/prophet · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
facebook
/
prophet
Public
Notifications
You must be signed in to change notification settings
Fork
4.6k
Star
20.4k
Code
Issues
449
Pull requests
3
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
prophet
/
python
/
prophet
/
plot.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1156 lines (1042 loc) · 39.2 KB
Breadcrumbs
prophet
/
python
/
prophet
/
plot.py
Copy path
File metadata and controls
1156 lines (1042 loc) · 39.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from
__future__
import
annotations
import
logging
from
typing
import
TYPE_CHECKING
,
cast
import
numpy
as
np
import
pandas
as
pd
# TODO: separate performance_metrics into a different module. there is an implicit circular import between forecaster.py and diagnostics.py
from
prophet
.
diagnostics
import
performance_metrics
if
TYPE_CHECKING
:
from
typing
import
Literal
,
Sequence
,
TypeVar
,
type_check_only
from
typing_extensions
import
TypedDict
from
prophet
.
forecaster
import
Prophet
import
matplotlib
.
pyplot
as
plt
import
plotly
.
graph_objs
as
go
_AxT
=
TypeVar
(
'_AxT'
,
bound
=
plt
.
Axes
)
@
type_check_only
class
_PlotlyProps
(
TypedDict
):
traces
:
list
[
go
.
Scatter
]
xaxis
:
go
.
layout
.
XAxis
yaxis
:
go
.
layout
.
YAxis
logger
:
logging
.
Logger
=
logging
.
getLogger
(
'prophet.plot'
)
try
:
from
matplotlib
import
pyplot
as
plt
from
matplotlib
.
dates
import
(
MonthLocator
,
num2date
,
AutoDateLocator
,
AutoDateFormatter
,
)
from
matplotlib
.
ticker
import
FuncFormatter
from
pandas
.
plotting
import
deregister_matplotlib_converters
deregister_matplotlib_converters
()
except
ImportError
:
logger
.
error
(
'Importing matplotlib failed. Plotting will not work.'
)
try
:
import
plotly
.
graph_objs
as
go
from
plotly
.
subplots
import
make_subplots
except
ImportError
:
logger
.
error
(
'Importing plotly failed. Interactive plots will not work.'
)
def
plot
(
m
:
Prophet
,
fcst
:
pd
.
DataFrame
,
ax
:
plt
.
Axes
|
None
=
None
,
uncertainty
:
bool
=
True
,
plot_cap
:
bool
=
True
,
xlabel
:
str
=
"ds"
,
ylabel
:
str
=
"y"
,
figsize
:
tuple
[
int
,
int
]
=
(
10
,
6
),
include_legend
:
bool
=
False
,
)
->
plt
.
Figure
:
"""Plot the Prophet forecast.
Parameters
----------
m: Prophet model.
fcst: pd.DataFrame output of m.predict.
ax: Optional matplotlib axes on which to plot.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
plot_cap: Optional boolean indicating if the capacity should be shown
in the figure, if available.
xlabel: Optional label name on X-axis
ylabel: Optional label name on Y-axis
figsize: Optional tuple width, height in inches.
include_legend: Optional boolean to add legend to the plot.
Returns
-------
A matplotlib figure.
"""
user_provided_ax
=
False
if
ax
is
None
else
True
if
ax
is
None
:
fig
=
plt
.
figure
(
facecolor
=
'w'
,
figsize
=
figsize
)
ax
=
fig
.
add_subplot
(
111
)
else
:
fig
=
cast
(
'plt.Figure'
,
ax
.
get_figure
())
fcst_t
=
fcst
[
'ds'
]
history
=
cast
(
'pd.DataFrame'
,
m
.
history
)
ax
.
plot
(
history
[
'ds'
],
history
[
'y'
],
'k.'
,
label
=
'Observed data points'
)
ax
.
plot
(
fcst_t
,
fcst
[
'yhat'
],
ls
=
'-'
,
c
=
'#0072B2'
,
label
=
'Forecast'
)
if
'cap'
in
fcst
and
plot_cap
:
ax
.
plot
(
fcst_t
,
fcst
[
'cap'
],
ls
=
'--'
,
c
=
'k'
,
label
=
'Maximum capacity'
)
if
m
.
logistic_floor
and
'floor'
in
fcst
and
plot_cap
:
ax
.
plot
(
fcst_t
,
fcst
[
'floor'
],
ls
=
'--'
,
c
=
'k'
,
label
=
'Minimum capacity'
)
if
uncertainty
and
m
.
uncertainty_samples
:
ax
.
fill_between
(
fcst_t
,
fcst
[
'yhat_lower'
],
fcst
[
'yhat_upper'
],
color
=
'#0072B2'
,
alpha
=
0.2
,
label
=
'Uncertainty interval'
)
# Specify formatting to workaround matplotlib issue #12925
locator
=
AutoDateLocator
(
interval_multiples
=
False
)
formatter
=
AutoDateFormatter
(
locator
)
ax
.
xaxis
.
set_major_locator
(
locator
)
ax
.
xaxis
.
set_major_formatter
(
formatter
)
ax
.
grid
(
True
,
which
=
'major'
,
c
=
'gray'
,
ls
=
'-'
,
lw
=
1
,
alpha
=
0.2
)
ax
.
set_xlabel
(
xlabel
)
ax
.
set_ylabel
(
ylabel
)
if
include_legend
:
ax
.
legend
()
if
not
user_provided_ax
:
try
:
if
fig
.
get_layout_engine
()
is
None
:
fig
.
tight_layout
()
except
AttributeError
:
fig
.
tight_layout
()
return
fig
def
plot_components
(
m
:
Prophet
,
fcst
:
pd
.
DataFrame
,
uncertainty
:
bool
=
True
,
plot_cap
:
bool
=
True
,
weekly_start
:
int
=
0
,
yearly_start
:
int
=
0
,
figsize
:
tuple
[
int
,
int
]
|
None
=
None
,
)
->
plt
.
Figure
:
"""Plot the Prophet forecast components.
Will plot whichever are available of: trend, holidays, weekly
seasonality, yearly seasonality, and additive and multiplicative extra
regressors.
Parameters
----------
m: Prophet model.
fcst: pd.DataFrame output of m.predict.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
plot_cap: Optional boolean indicating if the capacity should be shown
in the figure, if available.
weekly_start: Optional int specifying the start day of the weekly
seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
by 1 day to Monday, and so on.
yearly_start: Optional int specifying the start day of the yearly
seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
by 1 day to Jan 2, and so on.
figsize: Optional tuple width, height in inches.
Returns
-------
A matplotlib figure.
"""
# Identify components to be plotted
components
=
[
'trend'
]
if
m
.
train_holiday_names
is
not
None
and
'holidays'
in
fcst
:
components
.
append
(
'holidays'
)
# Plot weekly seasonality, if present
if
'weekly'
in
m
.
seasonalities
and
'weekly'
in
fcst
:
components
.
append
(
'weekly'
)
# Yearly if present
if
'yearly'
in
m
.
seasonalities
and
'yearly'
in
fcst
:
components
.
append
(
'yearly'
)
# Other seasonalities
components
.
extend
([
name
for
name
in
sorted
(
m
.
seasonalities
)
if
name
in
fcst
and
name
not
in
[
'weekly'
,
'yearly'
]
])
regressors
=
{
'additive'
:
False
,
'multiplicative'
:
False
}
for
name
,
props
in
m
.
extra_regressors
.
items
():
regressors
[
props
[
'mode'
]]
=
True
for
mode
in
[
'additive'
,
'multiplicative'
]:
if
regressors
[
mode
]
and
'extra_regressors_{}'
.
format
(
mode
)
in
fcst
:
components
.
append
(
'extra_regressors_{}'
.
format
(
mode
))
npanel
=
len
(
components
)
figsize
=
figsize
if
figsize
else
(
9
,
3
*
npanel
)
fig
,
axes
=
plt
.
subplots
(
npanel
,
1
,
facecolor
=
'w'
,
figsize
=
figsize
)
if
npanel
==
1
:
axes
=
[
axes
]
multiplicative_axes
=
[]
dt
=
cast
(
'pd.DataFrame'
,
m
.
history
)[
'ds'
].
diff
()
min_dt
=
dt
.
iloc
[
cast
(
'np.ndarray'
,
dt
.
values
).
nonzero
()[
0
]].
min
()
for
ax
,
plot_name
in
zip
(
axes
,
components
):
if
plot_name
==
'trend'
:
plot_forecast_component
(
m
=
m
,
fcst
=
fcst
,
name
=
'trend'
,
ax
=
ax
,
uncertainty
=
uncertainty
,
plot_cap
=
plot_cap
,
)
elif
plot_name
in
m
.
seasonalities
:
if
(
(
plot_name
==
'weekly'
or
m
.
seasonalities
[
plot_name
][
'period'
]
==
7
)
and
(
min_dt
==
pd
.
Timedelta
(
days
=
1
))
):
plot_weekly
(
m
=
m
,
name
=
plot_name
,
ax
=
ax
,
uncertainty
=
uncertainty
,
weekly_start
=
weekly_start
)
elif
plot_name
==
'yearly'
or
m
.
seasonalities
[
plot_name
][
'period'
]
==
365.25
:
plot_yearly
(
m
=
m
,
name
=
plot_name
,
ax
=
ax
,
uncertainty
=
uncertainty
,
yearly_start
=
yearly_start
)
else
:
plot_seasonality
(
m
=
m
,
name
=
plot_name
,
ax
=
ax
,
uncertainty
=
uncertainty
,
)
elif
plot_name
in
[
'holidays'
,
'extra_regressors_additive'
,
'extra_regressors_multiplicative'
,
]:
plot_forecast_component
(
m
=
m
,
fcst
=
fcst
,
name
=
plot_name
,
ax
=
ax
,
uncertainty
=
uncertainty
,
plot_cap
=
False
,
)
assert
m
.
component_modes
is
not
None
if
plot_name
in
m
.
component_modes
[
'multiplicative'
]:
multiplicative_axes
.
append
(
ax
)
try
:
if
fig
.
get_layout_engine
()
is
None
:
fig
.
tight_layout
()
except
AttributeError
:
fig
.
tight_layout
()
# Reset multiplicative axes labels after tight_layout adjustment
for
ax
in
multiplicative_axes
:
ax
=
set_y_as_percent
(
ax
)
return
fig
def
plot_forecast_component
(
m
:
Prophet
,
fcst
:
pd
.
DataFrame
,
name
:
str
,
ax
:
plt
.
Axes
|
None
=
None
,
uncertainty
:
bool
=
True
,
plot_cap
:
bool
=
False
,
figsize
:
tuple
[
int
,
int
]
=
(
10
,
6
),
)
->
Sequence
[
plt
.
Artist
]:
"""Plot a particular component of the forecast.
Parameters
----------
m: Prophet model.
fcst: pd.DataFrame output of m.predict.
name: Name of the component to plot.
ax: Optional matplotlib Axes to plot on.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
plot_cap: Optional boolean indicating if the capacity should be shown
in the figure, if available.
figsize: Optional tuple width, height in inches.
Returns
-------
a list of matplotlib artists
"""
artists
=
[]
if
not
ax
:
fig
=
plt
.
figure
(
facecolor
=
'w'
,
figsize
=
figsize
)
ax
=
fig
.
add_subplot
(
111
)
fcst_t
=
fcst
[
'ds'
]
artists
+=
ax
.
plot
(
fcst_t
,
fcst
[
name
],
ls
=
'-'
,
c
=
'#0072B2'
)
if
'cap'
in
fcst
and
plot_cap
:
artists
+=
ax
.
plot
(
fcst_t
,
fcst
[
'cap'
],
ls
=
'--'
,
c
=
'k'
)
if
m
.
logistic_floor
and
'floor'
in
fcst
and
plot_cap
:
ax
.
plot
(
fcst_t
,
fcst
[
'floor'
],
ls
=
'--'
,
c
=
'k'
)
if
uncertainty
and
m
.
uncertainty_samples
:
artists
+=
[
ax
.
fill_between
(
fcst_t
,
fcst
[
name
+
'_lower'
],
fcst
[
name
+
'_upper'
],
color
=
'#0072B2'
,
alpha
=
0.2
)]
# Specify formatting to workaround matplotlib issue #12925
locator
=
AutoDateLocator
(
interval_multiples
=
False
)
formatter
=
AutoDateFormatter
(
locator
)
ax
.
xaxis
.
set_major_locator
(
locator
)
ax
.
xaxis
.
set_major_formatter
(
formatter
)
ax
.
grid
(
True
,
which
=
'major'
,
c
=
'gray'
,
ls
=
'-'
,
lw
=
1
,
alpha
=
0.2
)
ax
.
set_xlabel
(
'ds'
)
ax
.
set_ylabel
(
name
)
assert
m
.
component_modes
if
name
in
m
.
component_modes
[
'multiplicative'
]:
ax
=
set_y_as_percent
(
ax
)
return
artists
def
seasonality_plot_df
(
m
:
Prophet
,
ds
:
Sequence
[
pd
.
Timestamp
]
|
pd
.
DatetimeIndex
,
)
->
pd
.
DataFrame
:
"""Prepare dataframe for plotting seasonal components.
Parameters
----------
m: Prophet model.
ds: List of dates for column ds.
Returns
-------
A dataframe with seasonal components on ds.
"""
df_dict
=
{
'ds'
:
ds
,
'cap'
:
1.
,
'floor'
:
0.
}
for
name
in
m
.
extra_regressors
:
df_dict
[
name
]
=
0.
# Activate all conditional seasonality columns
for
props
in
m
.
seasonalities
.
values
():
if
props
[
'condition_name'
]
is
not
None
:
df_dict
[
props
[
'condition_name'
]]
=
True
df
=
pd
.
DataFrame
(
df_dict
)
df
=
m
.
setup_dataframe
(
df
)
return
df
def
plot_weekly
(
m
:
Prophet
,
ax
:
plt
.
Axes
|
None
=
None
,
uncertainty
:
bool
=
True
,
weekly_start
:
int
=
0
,
figsize
:
tuple
[
int
,
int
]
=
(
10
,
6
),
name
:
str
=
'weekly'
,
)
->
Sequence
[
plt
.
Artist
]:
"""Plot the weekly component of the forecast.
Parameters
----------
m: Prophet model.
ax: Optional matplotlib Axes to plot on. One will be created if this
is not provided.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
weekly_start: Optional int specifying the start day of the weekly
seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
by 1 day to Monday, and so on.
figsize: Optional tuple width, height in inches.
name: Name of seasonality component if changed from default 'weekly'.
Returns
-------
a list of matplotlib artists
"""
artists
=
[]
if
not
ax
:
fig
=
plt
.
figure
(
facecolor
=
'w'
,
figsize
=
figsize
)
ax
=
fig
.
add_subplot
(
111
)
# Compute weekly seasonality for a Sun-Sat sequence of dates.
days
=
(
pd
.
date_range
(
start
=
'2017-01-01'
,
periods
=
7
)
+
pd
.
Timedelta
(
days
=
weekly_start
))
df_w
=
seasonality_plot_df
(
m
,
days
)
seas
=
m
.
predict_seasonal_components
(
df_w
)
days
=
days
.
day_name
()
artists
+=
ax
.
plot
(
range
(
len
(
days
)),
seas
[
name
],
ls
=
'-'
,
c
=
'#0072B2'
)
if
uncertainty
and
m
.
uncertainty_samples
:
artists
+=
[
ax
.
fill_between
(
range
(
len
(
days
)),
seas
[
name
+
'_lower'
],
seas
[
name
+
'_upper'
],
color
=
'#0072B2'
,
alpha
=
0.2
)]
ax
.
grid
(
True
,
which
=
'major'
,
c
=
'gray'
,
ls
=
'-'
,
lw
=
1
,
alpha
=
0.2
)
ax
.
set_xticks
(
range
(
len
(
days
)))
ax
.
set_xticklabels
(
days
)
ax
.
set_xlabel
(
'Day of week'
)
ax
.
set_ylabel
(
name
)
if
m
.
seasonalities
[
name
][
'mode'
]
==
'multiplicative'
:
ax
=
set_y_as_percent
(
ax
)
return
artists
def
plot_yearly
(
m
:
Prophet
,
ax
:
plt
.
Axes
|
None
=
None
,
uncertainty
:
bool
=
True
,
yearly_start
:
int
=
0
,
figsize
:
tuple
[
int
,
int
]
=
(
10
,
6
),
name
:
str
=
'yearly'
,
)
->
Sequence
[
plt
.
Artist
]:
"""Plot the yearly component of the forecast.
Parameters
----------
m: Prophet model.
ax: Optional matplotlib Axes to plot on. One will be created if
this is not provided.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
yearly_start: Optional int specifying the start day of the yearly
seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
by 1 day to Jan 2, and so on.
figsize: Optional tuple width, height in inches.
name: Name of seasonality component if previously changed from default 'yearly'.
Returns
-------
a list of matplotlib artists
"""
artists
=
[]
if
not
ax
:
fig
=
plt
.
figure
(
facecolor
=
'w'
,
figsize
=
figsize
)
ax
=
fig
.
add_subplot
(
111
)
# Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates.
days
=
(
pd
.
date_range
(
start
=
'2017-01-01'
,
periods
=
365
)
+
pd
.
Timedelta
(
days
=
yearly_start
))
df_y
=
seasonality_plot_df
(
m
,
days
)
seas
=
m
.
predict_seasonal_components
(
df_y
)
artists
+=
ax
.
plot
(
df_y
[
'ds'
],
seas
[
name
],
ls
=
'-'
,
c
=
'#0072B2'
)
if
uncertainty
and
m
.
uncertainty_samples
:
artists
+=
[
ax
.
fill_between
(
df_y
[
'ds'
],
seas
[
name
+
'_lower'
],
seas
[
name
+
'_upper'
],
color
=
'#0072B2'
,
alpha
=
0.2
)]
ax
.
grid
(
True
,
which
=
'major'
,
c
=
'gray'
,
ls
=
'-'
,
lw
=
1
,
alpha
=
0.2
)
months
=
MonthLocator
(
range
(
1
,
13
),
bymonthday
=
1
,
interval
=
2
)
ax
.
xaxis
.
set_major_formatter
(
FuncFormatter
(
lambda
x
,
pos
=
None
:
'{dt:%B} {dt.day}'
.
format
(
dt
=
num2date
(
x
))))
ax
.
xaxis
.
set_major_locator
(
months
)
ax
.
set_xlabel
(
'Day of year'
)
ax
.
set_ylabel
(
name
)
if
m
.
seasonalities
[
name
][
'mode'
]
==
'multiplicative'
:
ax
=
set_y_as_percent
(
ax
)
return
artists
def
plot_seasonality
(
m
:
Prophet
,
name
:
str
,
ax
:
plt
.
Axes
|
None
=
None
,
uncertainty
:
bool
=
True
,
figsize
:
tuple
[
int
,
int
]
=
(
10
,
6
),
)
->
Sequence
[
plt
.
Artist
]:
"""Plot a custom seasonal component.
Parameters
----------
m: Prophet model.
name: Seasonality name, like 'daily', 'weekly'.
ax: Optional matplotlib Axes to plot on. One will be created if
this is not provided.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
figsize: Optional tuple width, height in inches.
Returns
-------
a list of matplotlib artists
"""
artists
=
[]
if
not
ax
:
fig
=
plt
.
figure
(
facecolor
=
'w'
,
figsize
=
figsize
)
ax
=
fig
.
add_subplot
(
111
)
# Compute seasonality from Jan 1 through a single period.
start
=
pd
.
to_datetime
(
'2017-01-01 0000'
)
period
=
m
.
seasonalities
[
name
][
'period'
]
end
=
start
+
pd
.
Timedelta
(
days
=
period
)
plot_points
=
200
# https://github.com/pandas-dev/pandas-stubs/issues/1645
days
=
pd
.
to_datetime
(
np
.
linspace
(
start
.
value
,
end
.
value
,
plot_points
))
# pyrefly:ignore[no-matching-overload]
df_y
=
seasonality_plot_df
(
m
,
days
)
seas
=
m
.
predict_seasonal_components
(
df_y
)
artists
+=
ax
.
plot
(
df_y
[
'ds'
],
seas
[
name
],
ls
=
'-'
,
c
=
'#0072B2'
)
if
uncertainty
and
m
.
uncertainty_samples
:
artists
+=
[
ax
.
fill_between
(
df_y
[
'ds'
],
seas
[
name
+
'_lower'
],
seas
[
name
+
'_upper'
],
color
=
'#0072B2'
,
alpha
=
0.2
)]
ax
.
grid
(
True
,
which
=
'major'
,
c
=
'gray'
,
ls
=
'-'
,
lw
=
1
,
alpha
=
0.2
)
n_ticks
=
8
# https://github.com/pandas-dev/pandas-stubs/issues/1645
xticks
=
pd
.
to_datetime
(
np
.
linspace
(
start
.
value
,
end
.
value
,
n_ticks
)
# pyrefly:ignore[no-matching-overload]
).
to_pydatetime
()
ax
.
set_xticks
(
xticks
)
if
name
==
'yearly'
:
fmt
=
FuncFormatter
(
lambda
x
,
pos
=
None
:
'{dt:%B} {dt.day}'
.
format
(
dt
=
num2date
(
x
)))
ax
.
set_xlabel
(
'Day of year'
)
elif
name
==
'weekly'
:
fmt
=
FuncFormatter
(
lambda
x
,
pos
=
None
:
'{dt:%A}'
.
format
(
dt
=
num2date
(
x
)))
ax
.
set_xlabel
(
'Day of Week'
)
elif
name
==
'daily'
:
fmt
=
FuncFormatter
(
lambda
x
,
pos
=
None
:
'{dt:%T}'
.
format
(
dt
=
num2date
(
x
)))
ax
.
set_xlabel
(
'Hour of day'
)
elif
period
<=
2
:
fmt
=
FuncFormatter
(
lambda
x
,
pos
=
None
:
'{dt:%T}'
.
format
(
dt
=
num2date
(
x
)))
ax
.
set_xlabel
(
'Hours'
)
else
:
fmt
=
FuncFormatter
(
lambda
x
,
pos
=
None
:
'{:.0f}'
.
format
(
pos
*
period
/
(
n_ticks
-
1
)))
ax
.
set_xlabel
(
'Days'
)
ax
.
xaxis
.
set_major_formatter
(
fmt
)
ax
.
set_ylabel
(
name
)
if
m
.
seasonalities
[
name
][
'mode'
]
==
'multiplicative'
:
ax
=
set_y_as_percent
(
ax
)
return
artists
def
set_y_as_percent
(
ax
:
_AxT
)
->
_AxT
:
yticks
=
100
*
ax
.
get_yticks
()
yticklabels
=
[
'{0:.4g}%'
.
format
(
y
)
for
y
in
yticks
]
ax
.
set_yticks
(
ax
.
get_yticks
().
tolist
())
ax
.
set_yticklabels
(
yticklabels
)
return
ax
def
add_changepoints_to_plot
(
ax
:
plt
.
Axes
,
m
:
Prophet
,
fcst
:
pd
.
DataFrame
,
threshold
:
float
=
0.01
,
cp_color
:
str
=
'r'
,
cp_linestyle
:
str
=
'--'
,
trend
:
bool
=
True
,
)
->
list
[
plt
.
Line2D
]:
"""Add markers for significant changepoints to prophet forecast plot.
Example:
fig = m.plot(forecast)
add_changepoints_to_plot(fig.gca(), m, forecast)
Parameters
----------
ax: axis on which to overlay changepoint markers.
m: Prophet model.
fcst: Forecast output from m.predict.
threshold: Threshold on trend change magnitude for significance.
cp_color: Color of changepoint markers.
cp_linestyle: Linestyle for changepoint markers.
trend: If True, will also overlay the trend.
Returns
-------
a list of matplotlib artists
"""
artists
=
[]
if
trend
:
artists
.
extend
(
ax
.
plot
(
fcst
[
'ds'
],
fcst
[
'trend'
],
c
=
cp_color
))
assert
m
.
changepoints
is
not
None
signif_changepoints
=
m
.
changepoints
[
np
.
abs
(
np
.
nanmean
(
m
.
params
[
'delta'
],
axis
=
0
))
>=
threshold
]
if
len
(
m
.
changepoints
)
>
0
else
[]
for
cp
in
signif_changepoints
:
# Matplotlib stubs type axvline x as float; pandas Timestamp is accepted at runtime.
artists
.
append
(
ax
.
axvline
(
x
=
cp
,
c
=
cp_color
,
ls
=
cp_linestyle
))
# pyrefly:ignore[bad-argument-type]
return
artists
def
plot_cross_validation_metric
(
df_cv
:
pd
.
DataFrame
,
metric
:
str
,
rolling_window
:
float
=
0.1
,
ax
:
plt
.
Axes
|
None
=
None
,
figsize
:
tuple
[
int
,
int
]
=
(
10
,
6
),
color
:
str
=
'b'
,
point_color
:
str
=
'gray'
,
)
->
plt
.
Figure
:
"""Plot a performance metric vs. forecast horizon from cross validation.
Cross validation produces a collection of out-of-sample model predictions
that can be compared to actual values, at a range of different horizons
(distance from the cutoff). This computes a specified performance metric
for each prediction, and aggregated over a rolling window with horizon.
This uses prophet.diagnostics.performance_metrics to compute the metrics.
Valid values of metric are 'mse', 'rmse', 'mae', 'mape', 'mdape', 'smape', and 'coverage'.
rolling_window is the proportion of data included in the rolling window of
aggregation. The default value of 0.1 means 10% of data are included in the
aggregation for computing the metric.
As a concrete example, if metric='mse', then this plot will show the
squared error for each cross validation prediction, along with the MSE
averaged over rolling windows of 10% of the data.
Parameters
----------
df_cv: The output from prophet.diagnostics.cross_validation.
metric: Metric name, one of ['mse', 'rmse', 'mae', 'mape', 'mdape', 'smape', 'coverage'].
rolling_window: Proportion of data to use for rolling average of metric.
In [0, 1]. Defaults to 0.1.
ax: Optional matplotlib axis on which to plot. If not given, a new figure
will be created.
figsize: Optional tuple width, height in inches.
color: Optional color for plot and error points, useful when plotting
multiple model performances on one axis for comparison.
Returns
-------
a matplotlib figure.
"""
if
ax
is
None
:
fig
=
plt
.
figure
(
facecolor
=
'w'
,
figsize
=
figsize
)
ax
=
fig
.
add_subplot
(
111
)
else
:
fig
=
cast
(
'plt.Figure'
,
ax
.
get_figure
())
# Get the metric at the level of individual predictions, and with the rolling window.
df_none
=
performance_metrics
(
df_cv
,
metrics
=
[
metric
],
rolling_window
=
-
1
)
df_h
=
performance_metrics
(
df_cv
,
metrics
=
[
metric
],
rolling_window
=
rolling_window
)
assert
df_none
is
not
None
assert
df_h
is
not
None
# Some work because matplotlib does not handle timedelta
# Target ~10 ticks.
tick_w
=
max
(
df_none
[
'horizon'
].
astype
(
'timedelta64[ns]'
))
/
10.
# Find the largest time resolution that has <1 unit per bin.
dts
:
list
[
Literal
[
"D"
,
"h"
,
"m"
,
"s"
,
"ms"
,
"us"
,
"ns"
]]
dts
=
[
'D'
,
'h'
,
'm'
,
's'
,
'ms'
,
'us'
,
'ns'
]
dt_names
=
[
'days'
,
'hours'
,
'minutes'
,
'seconds'
,
'milliseconds'
,
'microseconds'
,
'nanoseconds'
]
dt_conversions
=
[
24
*
60
*
60
*
10
**
9
,
60
*
60
*
10
**
9
,
60
*
10
**
9
,
10
**
9
,
10
**
6
,
10
**
3
,
1.
,
]
for
i
,
dt
in
enumerate
(
dts
):
if
np
.
timedelta64
(
1
,
dt
)
<
np
.
timedelta64
(
tick_w
,
'ns'
):
break
x_plt
=
np
.
asarray
(
df_none
[
'horizon'
].
astype
(
'timedelta64[ns]'
)).
view
(
np
.
int64
)
/
float
(
dt_conversions
[
i
])
x_plt_h
=
np
.
asarray
(
df_h
[
'horizon'
].
astype
(
'timedelta64[ns]'
)).
view
(
np
.
int64
)
/
float
(
dt_conversions
[
i
])
ax
.
plot
(
x_plt
,
df_none
[
metric
],
'.'
,
alpha
=
0.1
,
c
=
point_color
)
ax
.
plot
(
x_plt_h
,
df_h
[
metric
],
'-'
,
c
=
color
)
ax
.
grid
(
True
)
ax
.
set_xlabel
(
'Horizon ({})'
.
format
(
dt_names
[
i
]))
ax
.
set_ylabel
(
metric
)
return
fig
def
plot_plotly
(
m
:
Prophet
,
fcst
:
pd
.
DataFrame
,
uncertainty
:
bool
=
True
,
plot_cap
:
bool
=
True
,
trend
:
bool
=
False
,
changepoints
:
bool
=
False
,
changepoints_threshold
:
float
=
0.01
,
xlabel
:
str
=
'ds'
,
ylabel
:
str
=
'y'
,
figsize
:
tuple
[
int
,
int
]
=
(
900
,
600
)
)
->
go
.
Figure
:
"""Plot the Prophet forecast with Plotly offline.
Plotting in Jupyter Notebook requires initializing plotly.offline.init_notebook_mode():
>>> import plotly.offline as py
>>> py.init_notebook_mode()
Then the figure can be displayed using plotly.offline.iplot(...):
>>> fig = plot_plotly(m, fcst)
>>> py.iplot(fig)
see https://plot.ly/python/offline/ for details
Parameters
----------
m: Prophet model.
fcst: pd.DataFrame output of m.predict.
uncertainty: Optional boolean to plot uncertainty intervals.
plot_cap: Optional boolean indicating if the capacity should be shown
in the figure, if available.
trend: Optional boolean to plot trend
changepoints: Optional boolean to plot changepoints
changepoints_threshold: Threshold on trend change magnitude for significance.
xlabel: Optional label name on X-axis
ylabel: Optional label name on Y-axis
figsize: The plot's size (in px).
Returns
-------
A Plotly Figure.
"""
prediction_color
=
'#0072B2'
error_color
=
'rgba(0, 114, 178, 0.2)'
# '#0072B2' with 0.2 opacity
actual_color
=
'black'
cap_color
=
'black'
trend_color
=
'#B23B00'
line_width
=
2
marker_size
=
4
data
=
[]
# Add actual
assert
m
.
history
data
.
append
(
go
.
Scatter
(
name
=
'Actual'
,
x
=
m
.
history
[
'ds'
],
y
=
m
.
history
[
'y'
],
marker
=
dict
(
color
=
actual_color
,
size
=
marker_size
),
mode
=
'markers'
))
# Add lower bound
if
uncertainty
and
m
.
uncertainty_samples
:
data
.
append
(
go
.
Scatter
(
x
=
fcst
[
'ds'
],
y
=
fcst
[
'yhat_lower'
],
mode
=
'lines'
,
line
=
dict
(
width
=
0
),
hoverinfo
=
'skip'
))
# Add prediction
data
.
append
(
go
.
Scatter
(
name
=
'Predicted'
,
x
=
fcst
[
'ds'
],
y
=
fcst
[
'yhat'
],
mode
=
'lines'
,
line
=
dict
(
color
=
prediction_color
,
width
=
line_width
),
fillcolor
=
error_color
,
fill
=
'tonexty'
if
uncertainty
and
m
.
uncertainty_samples
else
'none'
))
# Add upper bound
if
uncertainty
and
m
.
uncertainty_samples
:
data
.
append
(
go
.
Scatter
(
x
=
fcst
[
'ds'
],
y
=
fcst
[
'yhat_upper'
],
mode
=
'lines'
,
line
=
dict
(
width
=
0
),
fillcolor
=
error_color
,
fill
=
'tonexty'
,
hoverinfo
=
'skip'
))
# Add caps
if
'cap'
in
fcst
and
plot_cap
:
data
.
append
(
go
.
Scatter
(
name
=
'Cap'
,
x
=
fcst
[
'ds'
],
y
=
fcst
[
'cap'
],
mode
=
'lines'
,
line
=
dict
(
color
=
cap_color
,
dash
=
'dash'
,
width
=
line_width
),
))
if
m
.
logistic_floor
and
'floor'
in
fcst
and
plot_cap
:
data
.
append
(
go
.
Scatter
(
name
=
'Floor'
,
x
=
fcst
[
'ds'
],
y
=
fcst
[
'floor'
],
mode
=
'lines'
,
line
=
dict
(
color
=
cap_color
,
dash
=
'dash'
,
width
=
line_width
),
))
# Add trend
if
trend
:
data
.
append
(
go
.
Scatter
(
name
=
'Trend'
,
x
=
fcst
[
'ds'
],
y
=
fcst
[
'trend'
],
mode
=
'lines'
,
line
=
dict
(
color
=
trend_color
,
width
=
line_width
),
))
# Add changepoints
assert
m
.
changepoints
if
changepoints
and
len
(
m
.
changepoints
)
>
0
:
signif_changepoints
=
m
.
changepoints
[
np
.
abs
(
np
.
nanmean
(
m
.
params
[
'delta'
],
axis
=
0
))
>=
changepoints_threshold
]
data
.
append
(
go
.
Scatter
(
x
=
signif_changepoints
,
y
=
fcst
.
loc
[
fcst
[
'ds'
].
isin
(
signif_changepoints
),
'trend'
],
marker
=
dict
(
size
=
50
,
symbol
=
'line-ns-open'
,
color
=
trend_color
,
line
=
dict
(
width
=
line_width
)),
mode
=
'markers'
,
hoverinfo
=
'skip'
))
layout
=
dict
(
showlegend
=
False
,
width
=
figsize
[
0
],
height
=
figsize
[
1
],
yaxis
=
dict
(
title
=
ylabel
),
xaxis
=
dict
(
title
=
xlabel
,
type
=
'date'
,
rangeselector
=
dict
(
buttons
=
list
([
dict
(
count
=
7
,
label
=
'1w'
,
step
=
'day'
,
stepmode
=
'backward'
),
dict
(
count
=
1
,
label
=
'1m'
,
step
=
'month'
,
stepmode
=
'backward'
),
dict
(
count
=
6
,
label
=
'6m'
,
step
=
'month'
,
stepmode
=
'backward'
),
dict
(
count
=
1
,
label
=
'1y'
,
step
=
'year'
,
stepmode
=
'backward'
),
dict
(
step
=
'all'
)
])
),
rangeslider
=
dict
(
visible
=
True
),
),
)
fig
=
go
.
Figure
(
data
=
data
,
layout
=
layout
)
return
fig
def
plot_components_plotly
(
m
:
Prophet
,
fcst
:
pd
.
DataFrame
,
uncertainty
:
bool
=
True
,
plot_cap
:
bool
=
True
,
figsize
:
tuple
[
int
,
int
]
=
(
900
,
200
),
)
->
go
.
Figure
:
"""Plot the Prophet forecast components using Plotly.
See plot_plotly() for Plotly setup instructions
Will plot whichever are available of: trend, holidays, weekly
seasonality, yearly seasonality, and additive and multiplicative extra
regressors.
Parameters
----------
m: Prophet model.
fcst: pd.DataFrame output of m.predict.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
plot_cap: Optional boolean indicating if the capacity should be shown
in the figure, if available.
figsize: Set the size for the subplots (in px).
Returns
-------
A Plotly Figure.
"""
# Identify components to plot and get their Plotly props
components
=
{}
components
[
'trend'
]
=
get_forecast_component_plotly_props
(
m
,
fcst
,
'trend'
,
uncertainty
,
plot_cap
)
if
m
.
train_holiday_names
is
not
None
and
'holidays'
in
fcst
:
components
[
'holidays'
]
=
get_forecast_component_plotly_props
(
m
,
fcst
,
'holidays'
,
uncertainty
)
regressors
=
{
'additive'
:
False
,
'multiplicative'
:
False
}
for
name
,
props
in
m
.
extra_regressors
.
items
():
regressors
[
props
[
'mode'
]]
=
True
for
mode
in
[
'additive'
,
'multiplicative'
]:
if
regressors
[
mode
]
and
'extra_regressors_{}'
.
format
(
mode
)
in
fcst
:
components
[
'extra_regressors_{}'
.
format
(
mode
)]
=
get_forecast_component_plotly_props
(
m
,
fcst
,
'extra_regressors_{}'
.
format
(
mode
))
for
seasonality
in
m
.
seasonalities
:
components
[
seasonality
]
=
get_seasonality_plotly_props
(
m
,
seasonality
)
# Create Plotly subplot figure and add the components to it
fig
=
make_subplots
(
rows
=
len
(
components
),
cols
=
1
,
print_grid
=
False
)
fig
[
'layout'
].
update
(
go
.
Layout
(
showlegend
=
False
,
width
=
figsize
[
0
],
height
=
figsize
[
1
]
*
len
(
components
)
))
for
i
,
name
in
enumerate
(
components
):
if
i
==
0
:
xaxis
=
fig
[
'layout'
][
'xaxis'
]
yaxis
=
fig
[
'layout'
][
'yaxis'
]
else
:
xaxis
=
fig
[
'layout'
][
'xaxis{}'
.
format
(
i
+
1
)]
yaxis
=
fig
[
'layout'
][
'yaxis{}'
.
format
(
i
+
1
)]
xaxis
.
update
(
components
[
name
][
'xaxis'
])
yaxis
.
update
(
components
[
name
][
'yaxis'
])
for
trace
in
components
[
name
][
'traces'
]:
fig
.
append_trace
(
trace
,
i
+
1
,
1
)
return
fig
def
plot_forecast_component_plotly
(
m
:
Prophet
,
fcst
:
pd
.
DataFrame
,
name
:
str
,
uncertainty
:
bool
=
True
,
plot_cap
:
bool
=
False
,
figsize
:
tuple
[
int
,
int
]
=
(
900
,
300
)
)
->
go
.
Figure
:
"""Plot a particular component of the forecast using Plotly.
See plot_plotly() for Plotly setup instructions
Parameters
----------
m: Prophet model.
fcst: pd.DataFrame output of m.predict.
name: Name of the component to plot.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
plot_cap: Optional boolean indicating if the capacity should be shown
in the figure, if available.
figsize: The plot's size (in px).
Returns
-------
A Plotly Figure.
"""
props
=
get_forecast_component_plotly_props
(
m
,
fcst
,
name
,
uncertainty
,
plot_cap
)
layout
=
go
.
Layout
(
width
=
figsize
[
0
],
height
=
figsize
[
1
],
showlegend
=
False
,
xaxis
=
props
[
'xaxis'
],
yaxis
=
props
[
'yaxis'
]
)
fig
=
go
.
Figure
(
data
=
props
[
'traces'
],
layout
=
layout
)
return
fig
def
plot_seasonality_plotly
(
m
:
Prophet
,
name
:
str
,
uncertainty
:
bool
=
True
,
figsize
:
tuple
[
int
,
int
]
=
(
900
,
300
)
)
->
go
.
Figure
:
"""Plot a custom seasonal component using Plotly.
See plot_plotly() for Plotly setup instructions
Parameters
----------
m: Prophet model.
name: Seasonality name, like 'daily', 'weekly'.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
figsize: Set the plot's size (in px).
Returns
-------
A Plotly Figure.
"""
props
=
get_seasonality_plotly_props
(
m
,
name
,
uncertainty
)
layout
=
go
.
Layout
(
width
=
figsize
[
0
],
height
=
figsize
[
1
],
showlegend
=
False
,
xaxis
=
props
[
'xaxis'
],
yaxis
=
props
[
'yaxis'
]
)
fig
=
go
.
Figure
(
data
=
props
[
'traces'
],
layout
=
layout
)
return
fig
def
get_forecast_component_plotly_props
(
m
:
Prophet
,
fcst
:
pd
.
DataFrame
,
name
:
str
,
uncertainty
:
bool
=
True
,
plot_cap
:
bool
=
False
,
)
->
_PlotlyProps
:
"""Prepares a dictionary for plotting the selected forecast component with Plotly
Parameters
----------
m: Prophet model.
fcst: pd.DataFrame output of m.predict.
name: Name of the component to plot.
uncertainty: Optional boolean to plot uncertainty intervals, which will
only be done if m.uncertainty_samples > 0.
plot_cap: Optional boolean indicating if the capacity should be shown
in the figure, if available.
Returns
-------
A dictionary with Plotly traces, xaxis and yaxis
"""
prediction_color
=
'#0072B2'
error_color
=
'rgba(0, 114, 178, 0.2)'
# '#0072B2' with 0.2 opacity
cap_color
=
'black'
zeroline_color
=
'#AAA'
line_width
=
2
range_margin
=
(
fcst
[
'ds'
].
max
()
-
fcst
[
'ds'
].
min
())
*
0.05
range_x
=
[
fcst
[
'ds'
].
min
()
-
range_margin
,
fcst
[
'ds'
].
max
()
+
range_margin
]
text
=
None
mode
=
'lines'
if
name
==
'holidays'
:
# Combine holidays into one hover text
holidays
=
m
.
construct_holiday_dataframe
(
fcst
[
'ds'
])
holiday_features
,
_
,
_
=
m
.
make_holiday_features
(
fcst
[
'ds'
],
holidays
)
holiday_features
.
columns
=
holiday_features
.
columns
.
str
.
replace
(
'_delim_'
,
''
,
regex
=
False
)
holiday_features
.
columns
=
holiday_features
.
columns
.
str
.
replace
(
'+0'
,
''
,
regex
=
False
)
text
=
pd
.
Series
(
data
=
''
,
index
=
holiday_features
.
index
)
for
holiday_feature
,
idxs
in
holiday_features
.
items
():
# https://github.com/facebook/pyrefly/issues/2248
# pyrefly:ignore[unsupported-operation]
text
[
idxs
.
astype
(
bool
)
&
(
text
!=
''
)]
+=
'<br>'
# Add newline if additional holiday
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL