0
# Plotting and Visualization
1
2
Comprehensive plotting functionality for Prophet forecasts supporting both matplotlib and Plotly backends. Includes forecast visualization, component decomposition, seasonality analysis, and cross-validation metric plotting.
3
4
## Capabilities
5
6
### Matplotlib Plotting
7
8
Static plotting functions using matplotlib backend.
9
10
```python { .api }
11
def plot(
12
m, fcst, ax=None, uncertainty=True, plot_cap=True, xlabel='ds', ylabel='y',
13
figsize=(10, 6), include_legend=False
14
):
15
"""
16
Plot the Prophet forecast using matplotlib.
17
18
Parameters:
19
- m: Prophet, fitted Prophet object
20
- fcst: DataFrame, forecast output from Prophet.predict()
21
- ax: matplotlib axes, axes to plot on (optional)
22
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
23
- plot_cap: bool, whether to plot carrying capacity for logistic growth (default: True)
24
- xlabel: str, label for X-axis (default: 'ds')
25
- ylabel: str, label for Y-axis (default: 'y')
26
- figsize: tuple, figure size in inches (default: (10, 6))
27
- include_legend: bool, whether to add legend to the plot (default: False)
28
29
Returns:
30
- matplotlib Figure object
31
"""
32
33
def plot_components(
34
m, fcst, uncertainty=True, plot_cap=True, weekly_start=0, yearly_start=0,
35
figsize=None
36
):
37
"""
38
Plot the Prophet forecast components using matplotlib.
39
40
Parameters:
41
- m: Prophet, fitted Prophet object
42
- fcst: DataFrame, forecast output from Prophet.predict()
43
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
44
- plot_cap: bool, whether to plot carrying capacity (default: True)
45
- weekly_start: int, start day of weekly seasonality plot (0=Sunday, default: 0)
46
- yearly_start: int, start day of yearly seasonality plot (0=Jan 1, default: 0)
47
- figsize: tuple, figure size in inches (optional)
48
49
Returns:
50
- matplotlib Figure object with subplots for each component
51
"""
52
53
def plot_forecast_component(
54
m, fcst, name, ax=None, uncertainty=True, plot_cap=False, figsize=(10, 6)
55
):
56
"""
57
Plot an individual forecast component.
58
59
Parameters:
60
- m: Prophet, fitted Prophet object
61
- fcst: DataFrame, forecast output from Prophet.predict()
62
- name: str, name of component to plot
63
- ax: matplotlib axes, axes to plot on (optional)
64
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
65
- plot_cap: bool, whether to plot carrying capacity (default: False)
66
- figsize: tuple, figure size in inches (default: (10, 6))
67
68
Returns:
69
- list of matplotlib artists
70
"""
71
```
72
73
### Plotly Interactive Plotting
74
75
Interactive plotting functions using Plotly backend.
76
77
```python { .api }
78
def plot_plotly(m, fcst, uncertainty=True, plot_cap=True, trend=False, changepoints=False,
79
changepoints_threshold=0.01, xlabel='ds', ylabel='y', figsize=(900, 600)):
80
"""
81
Plot the Prophet forecast using Plotly.
82
83
Parameters:
84
- m: Prophet, fitted Prophet object
85
- fcst: DataFrame, forecast output from Prophet.predict()
86
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
87
- plot_cap: bool, whether to plot carrying capacity (default: True)
88
- trend: bool, whether to plot trend line (default: False)
89
- changepoints: bool, whether to plot changepoints (default: False)
90
- changepoints_threshold: float, threshold for changepoint significance (default: 0.01)
91
- xlabel: str, label for X-axis (default: 'ds')
92
- ylabel: str, label for Y-axis (default: 'y')
93
- figsize: tuple, plot size in pixels (default: (900, 600))
94
95
Returns:
96
- plotly Figure object
97
"""
98
99
def plot_components_plotly(
100
m, fcst, uncertainty=True, plot_cap=True, figsize=(900, 200)):
101
"""
102
Plot the Prophet forecast components using Plotly.
103
104
Parameters:
105
- m: Prophet, fitted Prophet object
106
- fcst: DataFrame, forecast output from Prophet.predict()
107
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
108
- plot_cap: bool, whether to plot carrying capacity (default: True)
109
- figsize: tuple, subplot size in pixels (default: (900, 200))
110
111
Returns:
112
- plotly Figure object with subplots for each component
113
"""
114
115
def plot_forecast_component_plotly(m, fcst, name, uncertainty=True, plot_cap=False, figsize=(900, 300)):
116
"""
117
Plot an individual forecast component using Plotly.
118
119
Parameters:
120
- m: Prophet, fitted Prophet object
121
- fcst: DataFrame, forecast output from Prophet.predict()
122
- name: str, name of component to plot
123
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
124
- plot_cap: bool, whether to plot carrying capacity (default: False)
125
- figsize: tuple, plot size in pixels (default: (900, 300))
126
127
Returns:
128
- plotly Figure object
129
"""
130
```
131
132
### Seasonality Plotting
133
134
Specialized plotting functions for seasonality analysis.
135
136
```python { .api }
137
def plot_weekly(m, ax=None, uncertainty=True, weekly_start=0, figsize=(10, 6), name='weekly'):
138
"""
139
Plot the weekly seasonality component.
140
141
Parameters:
142
- m: Prophet, fitted Prophet object
143
- ax: matplotlib axes, axes to plot on (optional)
144
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
145
- weekly_start: int, start day of weekly plot (0=Sunday, default: 0)
146
- figsize: tuple, figure size in inches (default: (10, 6))
147
- name: str, name of seasonality component (default: 'weekly')
148
149
Returns:
150
- list of matplotlib artists
151
"""
152
153
def plot_yearly(m, ax=None, uncertainty=True, yearly_start=0, figsize=(10, 6), name='yearly'):
154
"""
155
Plot the yearly seasonality component.
156
157
Parameters:
158
- m: Prophet, fitted Prophet object
159
- ax: matplotlib axes, axes to plot on (optional)
160
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
161
- yearly_start: int, start day of yearly plot (0=Jan 1, default: 0)
162
- figsize: tuple, figure size in inches (default: (10, 6))
163
- name: str, name of seasonality component (default: 'yearly')
164
165
Returns:
166
- list of matplotlib artists
167
"""
168
169
def plot_seasonality(m, name, ax=None, uncertainty=True, figsize=(10, 6)):
170
"""
171
Plot a custom seasonality component.
172
173
Parameters:
174
- m: Prophet, fitted Prophet object
175
- name: str, name of seasonality component to plot
176
- ax: matplotlib axes, axes to plot on (optional)
177
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
178
- figsize: tuple, figure size in inches (default: (10, 6))
179
180
Returns:
181
- list of matplotlib artists
182
"""
183
184
def plot_seasonality_plotly(m, name, uncertainty=True, figsize=(900, 300)):
185
"""
186
Plot a custom seasonality component using Plotly.
187
188
Parameters:
189
- m: Prophet, fitted Prophet object
190
- name: str, name of seasonality component to plot
191
- uncertainty: bool, whether to plot uncertainty intervals (default: True)
192
- figsize: tuple, plot size in pixels (default: (900, 300))
193
194
Returns:
195
- plotly Figure object
196
"""
197
```
198
199
### Enhanced Plotting Features
200
201
Additional plotting functionality for changepoints and cross-validation metrics.
202
203
```python { .api }
204
def add_changepoints_to_plot(ax, m, fcst, threshold=0.01, **kwargs):
205
"""
206
Add changepoint indicators to an existing plot.
207
208
Parameters:
209
- ax: matplotlib axes, axes to add changepoints to
210
- m: Prophet, fitted Prophet object
211
- fcst: DataFrame, forecast output from Prophet.predict()
212
- threshold: float, minimum changepoint significance to plot (default: 0.01)
213
- **kwargs: additional arguments for changepoint styling
214
215
Returns:
216
- matplotlib axes with added changepoint indicators
217
"""
218
219
def plot_cross_validation_metric(
220
df_cv, metric, rolling_window=0.1, ax=None, figsize=(10, 6), color='b',
221
point_color='gray'
222
):
223
"""
224
Plot a cross-validation performance metric vs forecast horizon.
225
226
Parameters:
227
- df_cv: DataFrame, cross-validation results from cross_validation()
228
- metric: str, metric name to plot ('mse', 'rmse', 'mae', 'mape', 'mdape', 'smape', 'coverage')
229
- rolling_window: float, rolling window proportion for smoothing (default: 0.1)
230
- ax: matplotlib axes, axes to plot on (optional)
231
- figsize: tuple, figure size in inches (default: (10, 6))
232
- color: str, color for the rolling average line (default: 'b')
233
- point_color: str, color for individual data points (default: 'gray')
234
235
Returns:
236
- matplotlib axes
237
"""
238
```
239
240
### Utility Functions
241
242
Helper functions for plot data preparation and formatting.
243
244
```python { .api }
245
def seasonality_plot_df(m, ds):
246
"""
247
Prepare DataFrame for seasonality plotting.
248
249
Parameters:
250
- m: Prophet, fitted Prophet object
251
- ds: datetime or Series, dates for seasonality evaluation
252
253
Returns:
254
- DataFrame with seasonality values
255
"""
256
257
def set_y_as_percent(ax):
258
"""
259
Format y-axis as percentages.
260
261
Parameters:
262
- ax: matplotlib axes, axes to format
263
264
Returns:
265
- None (modifies axes in-place)
266
"""
267
268
def get_forecast_component_plotly_props(m, fcst, name):
269
"""
270
Get Plotly properties for forecast components.
271
272
Parameters:
273
- m: Prophet, fitted Prophet object
274
- fcst: DataFrame, forecast output
275
- name: str, component name
276
277
Returns:
278
- dict, Plotly properties for the component
279
"""
280
281
def get_seasonality_plotly_props(m, name):
282
"""
283
Get Plotly properties for seasonality components.
284
285
Parameters:
286
- m: Prophet, fitted Prophet object
287
- name: str, seasonality name
288
289
Returns:
290
- dict, Plotly properties for the seasonality
291
"""
292
```
293
294
## Usage Examples
295
296
### Basic Forecast Plotting
297
298
```python
299
from prophet import Prophet
300
from prophet.plot import plot, plot_components
301
302
# Fit model and generate forecast
303
model = Prophet()
304
model.fit(df)
305
forecast = model.predict(future)
306
307
# Plot main forecast
308
fig1 = plot(model, forecast)
309
fig1.show()
310
311
# Plot components breakdown
312
fig2 = plot_components(model, forecast)
313
fig2.show()
314
```
315
316
### Interactive Plotly Visualization
317
318
```python
319
from prophet.plot import plot_plotly, plot_components_plotly
320
321
# Create interactive plots
322
fig_interactive = plot_plotly(model, forecast)
323
fig_interactive.show()
324
325
fig_components = plot_components_plotly(model, forecast)
326
fig_components.show()
327
```
328
329
### Seasonality Analysis
330
331
```python
332
from prophet.plot import plot_yearly, plot_weekly, plot_seasonality
333
334
# Plot built-in seasonalities
335
fig_yearly = plot_yearly(model)
336
fig_weekly = plot_weekly(model)
337
338
# Plot custom seasonality (if added)
339
fig_custom = plot_seasonality(model, 'monthly')
340
```
341
342
### Changepoint Visualization
343
344
```python
345
import matplotlib.pyplot as plt
346
from prophet.plot import add_changepoints_to_plot
347
348
# Create base forecast plot
349
fig, ax = plt.subplots(figsize=(12, 8))
350
plot(model, forecast, ax=ax)
351
352
# Add changepoint indicators
353
add_changepoints_to_plot(ax, model, forecast, threshold=0.01)
354
plt.show()
355
```