prophet.plot

   1# Copyright (c) Facebook, Inc. and its affiliates.
   2
   3# This source code is licensed under the MIT license found in the
   4# LICENSE file in the root directory of this source tree.
   5
   6from __future__ import annotations
   7
   8import logging
   9from typing import TYPE_CHECKING, cast
  10
  11import numpy as np
  12import pandas as pd
  13
  14from prophet.metrics import performance_metrics
  15
  16if TYPE_CHECKING:
  17    from typing import Literal, Sequence, TypeVar, type_check_only
  18    from typing_extensions import TypedDict
  19    
  20    from prophet.forecaster import Prophet
  21    
  22    import matplotlib.pyplot as plt
  23    import plotly.graph_objs as go
  24
  25    _AxT = TypeVar('_AxT', bound=plt.Axes)
  26
  27    @type_check_only
  28    class _PlotlyProps(TypedDict):
  29        traces: list[go.Scatter]
  30        xaxis: go.layout.XAxis
  31        yaxis: go.layout.YAxis
  32
  33
  34logger: logging.Logger = logging.getLogger('prophet.plot')
  35
  36
  37try:
  38    from matplotlib import pyplot as plt
  39    from matplotlib.dates import (
  40        MonthLocator,
  41        num2date,
  42        AutoDateLocator,
  43        AutoDateFormatter,
  44    )
  45    from matplotlib.ticker import FuncFormatter
  46
  47    from pandas.plotting import deregister_matplotlib_converters
  48    deregister_matplotlib_converters()
  49except ImportError:
  50    logger.error('Importing matplotlib failed. Plotting will not work.')
  51
  52try:
  53    import plotly.graph_objs as go
  54    from plotly.subplots import make_subplots
  55except ImportError:
  56    logger.error('Importing plotly failed. Interactive plots will not work.')
  57
  58
  59def plot(
  60    m: Prophet,
  61    fcst: pd.DataFrame,
  62    ax: plt.Axes | None = None,
  63    uncertainty: bool = True,
  64    plot_cap: bool = True,
  65    xlabel: str = "ds",
  66    ylabel: str = "y",
  67    figsize: tuple[int, int] = (10, 6),
  68    include_legend: bool = False,
  69) -> plt.Figure:
  70    """Plot the Prophet forecast.
  71
  72    Parameters
  73    ----------
  74    m: Prophet model.
  75    fcst: pd.DataFrame output of m.predict.
  76    ax: Optional matplotlib axes on which to plot.
  77    uncertainty: Optional boolean to plot uncertainty intervals, which will
  78        only be done if m.uncertainty_samples > 0.
  79    plot_cap: Optional boolean indicating if the capacity should be shown
  80        in the figure, if available.
  81    xlabel: Optional label name on X-axis
  82    ylabel: Optional label name on Y-axis
  83    figsize: Optional tuple width, height in inches.
  84    include_legend: Optional boolean to add legend to the plot.
  85
  86    Returns
  87    -------
  88    A matplotlib figure.
  89    """
  90    user_provided_ax = False if ax is None else True
  91    if ax is None:
  92        fig = plt.figure(facecolor='w', figsize=figsize)
  93        ax = fig.add_subplot(111)
  94    else:
  95        fig = cast('plt.Figure', ax.get_figure())
  96    fcst_t = fcst['ds']
  97    history = cast('pd.DataFrame', m.history)
  98    ax.plot(history['ds'], history['y'], 'k.', label='Observed data points')
  99    ax.plot(fcst_t, fcst['yhat'], ls='-', c='#0072B2', label='Forecast')
 100    if 'cap' in fcst and plot_cap:
 101        ax.plot(fcst_t, fcst['cap'], ls='--', c='k', label='Maximum capacity')
 102    if m.logistic_floor and 'floor' in fcst and plot_cap:
 103        ax.plot(fcst_t, fcst['floor'], ls='--', c='k', label='Minimum capacity')
 104    if uncertainty and m.uncertainty_samples:
 105        ax.fill_between(fcst_t, fcst['yhat_lower'], fcst['yhat_upper'],
 106                        color='#0072B2', alpha=0.2, label='Uncertainty interval')
 107    # Specify formatting to workaround matplotlib issue #12925
 108    locator = AutoDateLocator(interval_multiples=False)
 109    formatter = AutoDateFormatter(locator)
 110    ax.xaxis.set_major_locator(locator)
 111    ax.xaxis.set_major_formatter(formatter)
 112    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
 113    ax.set_xlabel(xlabel)
 114    ax.set_ylabel(ylabel)
 115    if include_legend:
 116        ax.legend()
 117    if not user_provided_ax:
 118        try:
 119            if fig.get_layout_engine() is None:
 120                fig.tight_layout()
 121        except AttributeError:
 122            fig.tight_layout()
 123    return fig
 124
 125
 126def plot_components(
 127    m: Prophet,
 128    fcst: pd.DataFrame,
 129    uncertainty: bool = True,
 130    plot_cap: bool = True,
 131    weekly_start: int = 0,
 132    yearly_start: int = 0,
 133    figsize: tuple[int, int] | None = None,
 134) -> plt.Figure:
 135    """Plot the Prophet forecast components.
 136
 137    Will plot whichever are available of: trend, holidays, weekly
 138    seasonality, yearly seasonality, and additive and multiplicative extra
 139    regressors.
 140
 141    Parameters
 142    ----------
 143    m: Prophet model.
 144    fcst: pd.DataFrame output of m.predict.
 145    uncertainty: Optional boolean to plot uncertainty intervals, which will
 146        only be done if m.uncertainty_samples > 0.
 147    plot_cap: Optional boolean indicating if the capacity should be shown
 148        in the figure, if available.
 149    weekly_start: Optional int specifying the start day of the weekly
 150        seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
 151        by 1 day to Monday, and so on.
 152    yearly_start: Optional int specifying the start day of the yearly
 153        seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
 154        by 1 day to Jan 2, and so on.
 155    figsize: Optional tuple width, height in inches.
 156
 157    Returns
 158    -------
 159    A matplotlib figure.
 160    """
 161    # Identify components to be plotted
 162    components = ['trend']
 163    if m.train_holiday_names is not None and 'holidays' in fcst:
 164        components.append('holidays')
 165    # Plot weekly seasonality, if present
 166    if 'weekly' in m.seasonalities and 'weekly' in fcst:
 167        components.append('weekly')
 168    # Yearly if present
 169    if 'yearly' in m.seasonalities and 'yearly' in fcst:
 170        components.append('yearly')
 171    # Other seasonalities
 172    components.extend([
 173        name for name in sorted(m.seasonalities)
 174        if name in fcst and name not in ['weekly', 'yearly']
 175    ])
 176    regressors = {'additive': False, 'multiplicative': False}
 177    for name, props in m.extra_regressors.items():
 178        regressors[props['mode']] = True
 179    for mode in ['additive', 'multiplicative']:
 180        if regressors[mode] and 'extra_regressors_{}'.format(mode) in fcst:
 181            components.append('extra_regressors_{}'.format(mode))
 182    npanel = len(components)
 183
 184    figsize = figsize if figsize else (9, 3 * npanel)
 185    fig, axes = plt.subplots(npanel, 1, facecolor='w', figsize=figsize)
 186
 187    if npanel == 1:
 188        axes = [axes]
 189
 190    multiplicative_axes = []
 191
 192    dt = cast('pd.DataFrame', m.history)['ds'].diff()
 193    min_dt = dt.iloc[cast('np.ndarray', dt.values).nonzero()[0]].min() 
 194
 195    for ax, plot_name in zip(axes, components):
 196        if plot_name == 'trend':
 197            plot_forecast_component(
 198                m=m, fcst=fcst, name='trend', ax=ax, uncertainty=uncertainty,
 199                plot_cap=plot_cap,
 200            )
 201        elif plot_name in m.seasonalities:
 202            if (
 203                (plot_name == 'weekly' or m.seasonalities[plot_name]['period'] == 7)
 204                and (min_dt == pd.Timedelta(days=1))
 205            ):
 206                plot_weekly(
 207                    m=m, name=plot_name, ax=ax, uncertainty=uncertainty, weekly_start=weekly_start
 208                )
 209            elif plot_name == 'yearly' or m.seasonalities[plot_name]['period'] == 365.25:
 210                plot_yearly(
 211                    m=m, name=plot_name, ax=ax, uncertainty=uncertainty, yearly_start=yearly_start
 212                )
 213            else:
 214                plot_seasonality(
 215                    m=m, name=plot_name, ax=ax, uncertainty=uncertainty,
 216                )
 217        elif plot_name in [
 218            'holidays',
 219            'extra_regressors_additive',
 220            'extra_regressors_multiplicative',
 221        ]:
 222            plot_forecast_component(
 223                m=m, fcst=fcst, name=plot_name, ax=ax, uncertainty=uncertainty,
 224                plot_cap=False,
 225            )
 226        assert m.component_modes is not None
 227        if plot_name in m.component_modes['multiplicative']:
 228            multiplicative_axes.append(ax)
 229
 230    try:
 231        if fig.get_layout_engine() is None:
 232            fig.tight_layout()
 233    except AttributeError:
 234        fig.tight_layout()
 235    # Reset multiplicative axes labels after tight_layout adjustment
 236    for ax in multiplicative_axes:
 237        ax = set_y_as_percent(ax)
 238    return fig
 239
 240
 241def plot_forecast_component(
 242    m: Prophet,
 243    fcst: pd.DataFrame,
 244    name: str,
 245    ax: plt.Axes | None = None,
 246    uncertainty: bool = True,
 247    plot_cap: bool = False,
 248    figsize: tuple[int, int] = (10, 6),
 249) -> Sequence[plt.Artist]:
 250    """Plot a particular component of the forecast.
 251
 252    Parameters
 253    ----------
 254    m: Prophet model.
 255    fcst: pd.DataFrame output of m.predict.
 256    name: Name of the component to plot.
 257    ax: Optional matplotlib Axes to plot on.
 258    uncertainty: Optional boolean to plot uncertainty intervals, which will
 259        only be done if m.uncertainty_samples > 0.
 260    plot_cap: Optional boolean indicating if the capacity should be shown
 261        in the figure, if available.
 262    figsize: Optional tuple width, height in inches.
 263
 264    Returns
 265    -------
 266    a list of matplotlib artists
 267    """
 268    artists = []
 269    if not ax:
 270        fig = plt.figure(facecolor='w', figsize=figsize)
 271        ax = fig.add_subplot(111)
 272    fcst_t = fcst['ds']
 273    artists += ax.plot(fcst_t, fcst[name], ls='-', c='#0072B2')
 274    if 'cap' in fcst and plot_cap:
 275        artists += ax.plot(fcst_t, fcst['cap'], ls='--', c='k')
 276    if m.logistic_floor and 'floor' in fcst and plot_cap:
 277        ax.plot(fcst_t, fcst['floor'], ls='--', c='k')
 278    if uncertainty and m.uncertainty_samples:
 279        artists += [ax.fill_between(
 280            fcst_t, fcst[name + '_lower'], fcst[name + '_upper'],
 281            color='#0072B2', alpha=0.2)]
 282    # Specify formatting to workaround matplotlib issue #12925
 283    locator = AutoDateLocator(interval_multiples=False)
 284    formatter = AutoDateFormatter(locator)
 285    ax.xaxis.set_major_locator(locator)
 286    ax.xaxis.set_major_formatter(formatter)
 287    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
 288    ax.set_xlabel('ds')
 289    ax.set_ylabel(name)
 290    assert m.component_modes
 291    if name in m.component_modes['multiplicative']:
 292        ax = set_y_as_percent(ax)
 293    return artists
 294
 295
 296def seasonality_plot_df(
 297    m: Prophet,
 298    ds: Sequence[pd.Timestamp] | pd.DatetimeIndex,
 299) -> pd.DataFrame:
 300    """Prepare dataframe for plotting seasonal components.
 301
 302    Parameters
 303    ----------
 304    m: Prophet model.
 305    ds: List of dates for column ds.
 306
 307    Returns
 308    -------
 309    A dataframe with seasonal components on ds.
 310    """
 311    df_dict = {'ds': ds, 'cap': 1., 'floor': 0.}
 312    for name in m.extra_regressors:
 313        df_dict[name] = 0.
 314    # Activate all conditional seasonality columns
 315    for props in m.seasonalities.values():
 316        if props['condition_name'] is not None:
 317            df_dict[props['condition_name']] = True
 318    df = pd.DataFrame(df_dict)
 319    df = m.setup_dataframe(df)
 320    return df
 321
 322
 323def plot_weekly(
 324    m: Prophet,
 325    ax: plt.Axes | None = None,
 326    uncertainty: bool = True,
 327    weekly_start: int = 0,
 328    figsize: tuple[int, int] = (10, 6),
 329    name: str = 'weekly',
 330) -> Sequence[plt.Artist]:
 331    """Plot the weekly component of the forecast.
 332
 333    Parameters
 334    ----------
 335    m: Prophet model.
 336    ax: Optional matplotlib Axes to plot on. One will be created if this
 337        is not provided.
 338    uncertainty: Optional boolean to plot uncertainty intervals, which will
 339        only be done if m.uncertainty_samples > 0.
 340    weekly_start: Optional int specifying the start day of the weekly
 341        seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
 342        by 1 day to Monday, and so on.
 343    figsize: Optional tuple width, height in inches.
 344    name: Name of seasonality component if changed from default 'weekly'.
 345
 346    Returns
 347    -------
 348    a list of matplotlib artists
 349    """
 350    artists = []
 351    if not ax:
 352        fig = plt.figure(facecolor='w', figsize=figsize)
 353        ax = fig.add_subplot(111)
 354    # Compute weekly seasonality for a Sun-Sat sequence of dates.
 355    days = (pd.date_range(start='2017-01-01', periods=7) +
 356            pd.Timedelta(days=weekly_start))
 357    df_w = seasonality_plot_df(m, days)
 358    seas = m.predict_seasonal_components(df_w)
 359    days = days.day_name()
 360    artists += ax.plot(range(len(days)), seas[name], ls='-',
 361                    c='#0072B2')
 362    if uncertainty and m.uncertainty_samples:
 363        artists += [ax.fill_between(range(len(days)),
 364                                    seas[name + '_lower'], seas[name + '_upper'],
 365                                    color='#0072B2', alpha=0.2)]
 366    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
 367    ax.set_xticks(range(len(days)))
 368    ax.set_xticklabels(days)
 369    ax.set_xlabel('Day of week')
 370    ax.set_ylabel(name)
 371    if m.seasonalities[name]['mode'] == 'multiplicative':
 372        ax = set_y_as_percent(ax)
 373    return artists
 374
 375
 376def plot_yearly(
 377    m: Prophet,
 378    ax: plt.Axes | None = None,
 379    uncertainty: bool = True,
 380    yearly_start: int = 0,
 381    figsize: tuple[int, int] = (10, 6),
 382    name: str = 'yearly',
 383) -> Sequence[plt.Artist]:
 384    """Plot the yearly component of the forecast.
 385
 386    Parameters
 387    ----------
 388    m: Prophet model.
 389    ax: Optional matplotlib Axes to plot on. One will be created if
 390        this is not provided.
 391    uncertainty: Optional boolean to plot uncertainty intervals, which will
 392        only be done if m.uncertainty_samples > 0.
 393    yearly_start: Optional int specifying the start day of the yearly
 394        seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
 395        by 1 day to Jan 2, and so on.
 396    figsize: Optional tuple width, height in inches.
 397    name: Name of seasonality component if previously changed from default 'yearly'.
 398
 399    Returns
 400    -------
 401    a list of matplotlib artists
 402    """
 403    artists = []
 404    if not ax:
 405        fig = plt.figure(facecolor='w', figsize=figsize)
 406        ax = fig.add_subplot(111)
 407    # Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates.
 408    days = (pd.date_range(start='2017-01-01', periods=365) +
 409            pd.Timedelta(days=yearly_start))
 410    df_y = seasonality_plot_df(m, days)
 411    seas = m.predict_seasonal_components(df_y)
 412    artists += ax.plot(
 413        df_y['ds'], seas[name], ls='-', c='#0072B2')
 414    if uncertainty and m.uncertainty_samples:
 415        artists += [ax.fill_between(
 416            df_y['ds'], seas[name + '_lower'],
 417            seas[name + '_upper'], color='#0072B2', alpha=0.2)]
 418    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
 419    months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
 420    ax.xaxis.set_major_formatter(FuncFormatter(
 421        lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))
 422    ax.xaxis.set_major_locator(months)
 423    ax.set_xlabel('Day of year')
 424    ax.set_ylabel(name)
 425    if m.seasonalities[name]['mode'] == 'multiplicative':
 426        ax = set_y_as_percent(ax)
 427    return artists
 428
 429
 430def plot_seasonality(
 431    m: Prophet,
 432    name: str,
 433    ax: plt.Axes | None = None,
 434    uncertainty: bool = True,
 435    figsize: tuple[int, int] = (10, 6),
 436) -> Sequence[plt.Artist]:
 437    """Plot a custom seasonal component.
 438
 439    Parameters
 440    ----------
 441    m: Prophet model.
 442    name: Seasonality name, like 'daily', 'weekly'.
 443    ax: Optional matplotlib Axes to plot on. One will be created if
 444        this is not provided.
 445    uncertainty: Optional boolean to plot uncertainty intervals, which will
 446        only be done if m.uncertainty_samples > 0.
 447    figsize: Optional tuple width, height in inches.
 448
 449    Returns
 450    -------
 451    a list of matplotlib artists
 452    """
 453    artists = []
 454    if not ax:
 455        fig = plt.figure(facecolor='w', figsize=figsize)
 456        ax = fig.add_subplot(111)
 457    # Compute seasonality from Jan 1 through a single period.
 458    start = pd.to_datetime('2017-01-01 0000')
 459    period = m.seasonalities[name]['period']
 460    end = start + pd.Timedelta(days=period)
 461    plot_points = 200
 462    # https://github.com/pandas-dev/pandas-stubs/issues/1645
 463    days = pd.to_datetime(np.linspace(start.value, end.value, plot_points))  # pyrefly:ignore[no-matching-overload]
 464    df_y = seasonality_plot_df(m, days)
 465    seas = m.predict_seasonal_components(df_y)
 466    artists += ax.plot(df_y['ds'], seas[name], ls='-',
 467                        c='#0072B2')
 468    if uncertainty and m.uncertainty_samples:
 469        artists += [ax.fill_between(
 470            df_y['ds'], seas[name + '_lower'],
 471            seas[name + '_upper'], color='#0072B2', alpha=0.2)]
 472    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
 473    n_ticks = 8
 474    # https://github.com/pandas-dev/pandas-stubs/issues/1645
 475    xticks = pd.to_datetime(np.linspace(start.value, end.value, n_ticks)  # pyrefly:ignore[no-matching-overload]
 476        ).to_pydatetime()
 477    ax.set_xticks(xticks)
 478    if name == 'yearly':
 479        fmt = FuncFormatter(
 480            lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x)))
 481        ax.set_xlabel('Day of year')
 482    elif name == 'weekly':
 483        fmt = FuncFormatter(
 484            lambda x, pos=None: '{dt:%A}'.format(dt=num2date(x)))
 485        ax.set_xlabel('Day of Week')
 486    elif name == 'daily':
 487        fmt = FuncFormatter(
 488            lambda x, pos=None: '{dt:%T}'.format(dt=num2date(x)))
 489        ax.set_xlabel('Hour of day')
 490    elif period <= 2:
 491        fmt = FuncFormatter(
 492            lambda x, pos=None: '{dt:%T}'.format(dt=num2date(x)))
 493        ax.set_xlabel('Hours')
 494    else:
 495        fmt = FuncFormatter(
 496            lambda x, pos=None: '{:.0f}'.format(pos * period / (n_ticks - 1)))
 497        ax.set_xlabel('Days')
 498    ax.xaxis.set_major_formatter(fmt)
 499    ax.set_ylabel(name)
 500    if m.seasonalities[name]['mode'] == 'multiplicative':
 501        ax = set_y_as_percent(ax)
 502    return artists
 503
 504
 505def set_y_as_percent(ax: _AxT) -> _AxT:
 506    yticks = 100 * ax.get_yticks()
 507    yticklabels = ['{0:.4g}%'.format(y) for y in yticks]
 508    ax.set_yticks(ax.get_yticks().tolist())
 509    ax.set_yticklabels(yticklabels)
 510    return ax
 511
 512
 513def add_changepoints_to_plot(
 514    ax: plt.Axes,
 515    m: Prophet,
 516    fcst: pd.DataFrame,
 517    threshold: float = 0.01,
 518    cp_color: str = 'r',
 519    cp_linestyle: str = '--',
 520    trend: bool = True,
 521) -> list[plt.Line2D]:
 522    """Add markers for significant changepoints to prophet forecast plot.
 523
 524    Example:
 525    fig = m.plot(forecast)
 526    add_changepoints_to_plot(fig.gca(), m, forecast)
 527
 528    Parameters
 529    ----------
 530    ax: axis on which to overlay changepoint markers.
 531    m: Prophet model.
 532    fcst: Forecast output from m.predict.
 533    threshold: Threshold on trend change magnitude for significance.
 534    cp_color: Color of changepoint markers.
 535    cp_linestyle: Linestyle for changepoint markers.
 536    trend: If True, will also overlay the trend.
 537
 538    Returns
 539    -------
 540    a list of matplotlib artists
 541    """
 542    artists = []
 543    if trend:
 544        artists.extend(ax.plot(fcst['ds'], fcst['trend'], c=cp_color))
 545    
 546    assert m.changepoints is not None
 547    signif_changepoints = m.changepoints[
 548        np.abs(np.nanmean(m.params['delta'], axis=0)) >= threshold
 549    ] if len(m.changepoints) > 0 else []
 550    for cp in signif_changepoints:
 551        # Matplotlib stubs type axvline x as float; pandas Timestamp is accepted at runtime.
 552        artists.append(ax.axvline(x=cp, c=cp_color, ls=cp_linestyle))  # pyrefly:ignore[bad-argument-type]
 553    return artists
 554
 555
 556def plot_cross_validation_metric(
 557    df_cv: pd.DataFrame,
 558    metric: str,
 559    rolling_window: float = 0.1,
 560    ax: plt.Axes | None = None,
 561    figsize: tuple[int, int] = (10, 6),
 562    color: str = 'b',
 563    point_color: str = 'gray',
 564) -> plt.Figure:
 565    """Plot a performance metric vs. forecast horizon from cross validation.
 566
 567    Cross validation produces a collection of out-of-sample model predictions
 568    that can be compared to actual values, at a range of different horizons
 569    (distance from the cutoff). This computes a specified performance metric
 570    for each prediction, and aggregated over a rolling window with horizon.
 571
 572    This uses prophet.diagnostics.performance_metrics to compute the metrics.
 573    Valid values of metric are 'mse', 'rmse', 'mae', 'mape', 'mdape', 'smape', and 'coverage'.
 574
 575    rolling_window is the proportion of data included in the rolling window of
 576    aggregation. The default value of 0.1 means 10% of data are included in the
 577    aggregation for computing the metric.
 578
 579    As a concrete example, if metric='mse', then this plot will show the
 580    squared error for each cross validation prediction, along with the MSE
 581    averaged over rolling windows of 10% of the data.
 582
 583    Parameters
 584    ----------
 585    df_cv: The output from prophet.diagnostics.cross_validation.
 586    metric: Metric name, one of ['mse', 'rmse', 'mae', 'mape', 'mdape', 'smape', 'coverage'].
 587    rolling_window: Proportion of data to use for rolling average of metric.
 588        In [0, 1]. Defaults to 0.1.
 589    ax: Optional matplotlib axis on which to plot. If not given, a new figure
 590        will be created.
 591    figsize: Optional tuple width, height in inches.
 592    color: Optional color for plot and error points, useful when plotting
 593        multiple model performances on one axis for comparison.
 594
 595    Returns
 596    -------
 597    a matplotlib figure.
 598    """
 599    if ax is None:
 600        fig = plt.figure(facecolor='w', figsize=figsize)
 601        ax = fig.add_subplot(111)
 602    else:
 603        fig = cast('plt.Figure', ax.get_figure())
 604    # Get the metric at the level of individual predictions, and with the rolling window.
 605    df_none = performance_metrics(df_cv, metrics=[metric], rolling_window=-1)
 606    df_h = performance_metrics(df_cv, metrics=[metric], rolling_window=rolling_window)
 607    
 608    assert df_none is not None
 609    assert df_h is not None
 610
 611    # Some work because matplotlib does not handle timedelta
 612    # Target ~10 ticks.
 613    tick_w = max(df_none['horizon'].astype('timedelta64[ns]')) / 10.
 614    # Find the largest time resolution that has <1 unit per bin.
 615    dts: list[Literal["D", "h", "m", "s", "ms", "us", "ns"]]
 616    dts = ['D', 'h', 'm', 's', 'ms', 'us', 'ns']
 617    dt_names = [
 618        'days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds',
 619        'nanoseconds'
 620    ]
 621    dt_conversions = [
 622        24 * 60 * 60 * 10 ** 9,
 623        60 * 60 * 10 ** 9,
 624        60 * 10 ** 9,
 625        10 ** 9,
 626        10 ** 6,
 627        10 ** 3,
 628        1.,
 629    ]
 630    for i, dt in enumerate(dts):
 631        if np.timedelta64(1, dt) < np.timedelta64(tick_w, 'ns'):
 632            break
 633
 634    x_plt = np.asarray(df_none['horizon'].astype('timedelta64[ns]')).view(np.int64) / float(dt_conversions[i])
 635    x_plt_h = np.asarray(df_h['horizon'].astype('timedelta64[ns]')).view(np.int64) / float(dt_conversions[i])
 636
 637    ax.plot(x_plt, df_none[metric], '.', alpha=0.1, c=point_color)
 638    ax.plot(x_plt_h, df_h[metric], '-', c=color)
 639    ax.grid(True)
 640
 641    ax.set_xlabel('Horizon ({})'.format(dt_names[i]))
 642    ax.set_ylabel(metric)
 643    return fig
 644
 645
 646def plot_plotly(
 647    m: Prophet,
 648    fcst: pd.DataFrame,
 649    uncertainty: bool = True,
 650    plot_cap: bool = True,
 651    trend: bool = False,
 652    changepoints: bool = False,
 653    changepoints_threshold: float = 0.01,
 654    xlabel: str = 'ds',
 655    ylabel: str = 'y',
 656    figsize: tuple[int, int] = (900, 600)
 657) -> go.Figure:
 658    """Plot the Prophet forecast with Plotly offline.
 659
 660    Plotting in Jupyter Notebook requires initializing plotly.offline.init_notebook_mode():
 661    >>> import plotly.offline as py
 662    >>> py.init_notebook_mode()
 663    Then the figure can be displayed using plotly.offline.iplot(...):
 664    >>> fig = plot_plotly(m, fcst)
 665    >>> py.iplot(fig)
 666    see https://plot.ly/python/offline/ for details
 667
 668    Parameters
 669    ----------
 670    m: Prophet model.
 671    fcst: pd.DataFrame output of m.predict.
 672    uncertainty: Optional boolean to plot uncertainty intervals.
 673    plot_cap: Optional boolean indicating if the capacity should be shown
 674        in the figure, if available.
 675    trend: Optional boolean to plot trend
 676    changepoints: Optional boolean to plot changepoints
 677    changepoints_threshold: Threshold on trend change magnitude for significance.
 678    xlabel: Optional label name on X-axis
 679    ylabel: Optional label name on Y-axis
 680    figsize: The plot's size (in px).
 681
 682    Returns
 683    -------
 684    A Plotly Figure.
 685    """
 686    prediction_color = '#0072B2'
 687    error_color = 'rgba(0, 114, 178, 0.2)'  # '#0072B2' with 0.2 opacity
 688    actual_color = 'black'
 689    cap_color = 'black'
 690    trend_color = '#B23B00'
 691    line_width = 2
 692    marker_size = 4
 693
 694    data = []
 695    # Add actual
 696    assert m.history
 697    data.append(go.Scatter(
 698        name='Actual',
 699        x=m.history['ds'],
 700        y=m.history['y'],
 701        marker=dict(color=actual_color, size=marker_size),
 702        mode='markers'
 703    ))
 704    # Add lower bound
 705    if uncertainty and m.uncertainty_samples:
 706        data.append(go.Scatter(
 707            x=fcst['ds'],
 708            y=fcst['yhat_lower'],
 709            mode='lines',
 710            line=dict(width=0),
 711            hoverinfo='skip'
 712        ))
 713    # Add prediction
 714    data.append(go.Scatter(
 715        name='Predicted',
 716        x=fcst['ds'],
 717        y=fcst['yhat'],
 718        mode='lines',
 719        line=dict(color=prediction_color, width=line_width),
 720        fillcolor=error_color,
 721        fill='tonexty' if uncertainty and m.uncertainty_samples else 'none'
 722    ))
 723    # Add upper bound
 724    if uncertainty and m.uncertainty_samples:
 725        data.append(go.Scatter(
 726            x=fcst['ds'],
 727            y=fcst['yhat_upper'],
 728            mode='lines',
 729            line=dict(width=0),
 730            fillcolor=error_color,
 731            fill='tonexty',
 732            hoverinfo='skip'
 733        ))
 734    # Add caps
 735    if 'cap' in fcst and plot_cap:
 736        data.append(go.Scatter(
 737            name='Cap',
 738            x=fcst['ds'],
 739            y=fcst['cap'],
 740            mode='lines',
 741            line=dict(color=cap_color, dash='dash', width=line_width),
 742        ))
 743    if m.logistic_floor and 'floor' in fcst and plot_cap:
 744        data.append(go.Scatter(
 745            name='Floor',
 746            x=fcst['ds'],
 747            y=fcst['floor'],
 748            mode='lines',
 749            line=dict(color=cap_color, dash='dash', width=line_width),
 750        ))
 751    # Add trend
 752    if trend:
 753        data.append(go.Scatter(
 754            name='Trend',
 755            x=fcst['ds'],
 756            y=fcst['trend'],
 757            mode='lines',
 758            line=dict(color=trend_color, width=line_width),
 759        ))
 760    # Add changepoints
 761    assert m.changepoints
 762    if changepoints and len(m.changepoints) > 0:
 763        signif_changepoints = m.changepoints[
 764            np.abs(np.nanmean(m.params['delta'], axis=0)) >= changepoints_threshold
 765        ]
 766        data.append(go.Scatter(
 767            x=signif_changepoints,
 768            y=fcst.loc[fcst['ds'].isin(signif_changepoints), 'trend'],
 769            marker=dict(size=50, symbol='line-ns-open', color=trend_color,
 770                        line=dict(width=line_width)),
 771            mode='markers',
 772            hoverinfo='skip'
 773        ))
 774
 775    layout = dict(
 776        showlegend=False,
 777        width=figsize[0],
 778        height=figsize[1],
 779        yaxis=dict(
 780            title=ylabel
 781        ),
 782        xaxis=dict(
 783            title=xlabel,
 784            type='date',
 785            rangeselector=dict(
 786                buttons=list([
 787                    dict(count=7,
 788                         label='1w',
 789                         step='day',
 790                         stepmode='backward'),
 791                    dict(count=1,
 792                         label='1m',
 793                         step='month',
 794                         stepmode='backward'),
 795                    dict(count=6,
 796                         label='6m',
 797                         step='month',
 798                         stepmode='backward'),
 799                    dict(count=1,
 800                         label='1y',
 801                         step='year',
 802                         stepmode='backward'),
 803                    dict(step='all')
 804                ])
 805            ),
 806            rangeslider=dict(
 807                visible=True
 808            ),
 809        ),
 810    )
 811    fig = go.Figure(data=data, layout=layout)
 812    return fig
 813
 814
 815def plot_components_plotly(
 816    m: Prophet,
 817    fcst: pd.DataFrame,
 818    uncertainty: bool = True,
 819    plot_cap: bool = True,
 820    figsize: tuple[int, int] = (900, 200),
 821) -> go.Figure:
 822    """Plot the Prophet forecast components using Plotly.
 823    See plot_plotly() for Plotly setup instructions
 824
 825    Will plot whichever are available of: trend, holidays, weekly
 826    seasonality, yearly seasonality, and additive and multiplicative extra
 827    regressors.
 828
 829    Parameters
 830    ----------
 831    m: Prophet model.
 832    fcst: pd.DataFrame output of m.predict.
 833    uncertainty: Optional boolean to plot uncertainty intervals, which will
 834        only be done if m.uncertainty_samples > 0.
 835    plot_cap: Optional boolean indicating if the capacity should be shown
 836        in the figure, if available.
 837    figsize: Set the size for the subplots (in px).
 838
 839    Returns
 840    -------
 841    A Plotly Figure.
 842    """
 843
 844    # Identify components to plot and get their Plotly props
 845    components = {}
 846    components['trend'] = get_forecast_component_plotly_props(
 847        m, fcst, 'trend', uncertainty, plot_cap)
 848    if m.train_holiday_names is not None and 'holidays' in fcst:
 849        components['holidays'] = get_forecast_component_plotly_props(
 850            m, fcst, 'holidays', uncertainty)
 851
 852    regressors = {'additive': False, 'multiplicative': False}
 853    for name, props in m.extra_regressors.items():
 854        regressors[props['mode']] = True
 855    for mode in ['additive', 'multiplicative']:
 856        if regressors[mode] and 'extra_regressors_{}'.format(mode) in fcst:
 857            components['extra_regressors_{}'.format(mode)] = get_forecast_component_plotly_props(
 858                m, fcst, 'extra_regressors_{}'.format(mode))
 859    for seasonality in m.seasonalities:
 860        components[seasonality] = get_seasonality_plotly_props(m, seasonality)
 861
 862    # Create Plotly subplot figure and add the components to it
 863    fig = make_subplots(rows=len(components), cols=1, print_grid=False)
 864    fig['layout'].update(go.Layout(
 865        showlegend=False,
 866        width=figsize[0],
 867        height=figsize[1] * len(components)
 868    ))
 869    for i, name in enumerate(components):
 870        if i == 0:
 871            xaxis = fig['layout']['xaxis']
 872            yaxis = fig['layout']['yaxis']
 873        else:
 874            xaxis = fig['layout']['xaxis{}'.format(i + 1)]
 875            yaxis = fig['layout']['yaxis{}'.format(i + 1)]
 876        xaxis.update(components[name]['xaxis'])
 877        yaxis.update(components[name]['yaxis'])
 878        for trace in components[name]['traces']:
 879            fig.append_trace(trace, i + 1, 1)
 880    return fig
 881
 882
 883def plot_forecast_component_plotly(
 884    m: Prophet,
 885    fcst: pd.DataFrame,
 886    name: str,
 887    uncertainty: bool = True,
 888    plot_cap: bool = False,
 889    figsize: tuple[int, int] = (900, 300)
 890) -> go.Figure:
 891    """Plot a particular component of the forecast using Plotly.
 892    See plot_plotly() for Plotly setup instructions
 893
 894    Parameters
 895    ----------
 896    m: Prophet model.
 897    fcst: pd.DataFrame output of m.predict.
 898    name: Name of the component to plot.
 899    uncertainty: Optional boolean to plot uncertainty intervals, which will
 900        only be done if m.uncertainty_samples > 0.
 901    plot_cap: Optional boolean indicating if the capacity should be shown
 902        in the figure, if available.
 903    figsize: The plot's size (in px).
 904
 905    Returns
 906    -------
 907    A Plotly Figure.
 908    """
 909    props = get_forecast_component_plotly_props(m, fcst, name, uncertainty, plot_cap)
 910    layout = go.Layout(
 911        width=figsize[0],
 912        height=figsize[1],
 913        showlegend=False,
 914        xaxis=props['xaxis'],
 915        yaxis=props['yaxis']
 916    )
 917    fig = go.Figure(data=props['traces'], layout=layout)
 918    return fig
 919
 920
 921def plot_seasonality_plotly(
 922    m: Prophet,
 923    name: str,
 924    uncertainty: bool = True,
 925    figsize: tuple[int, int] = (900, 300)
 926) -> go.Figure:
 927    """Plot a custom seasonal component using Plotly.
 928    See plot_plotly() for Plotly setup instructions
 929
 930    Parameters
 931    ----------
 932    m: Prophet model.
 933    name: Seasonality name, like 'daily', 'weekly'.
 934    uncertainty: Optional boolean to plot uncertainty intervals, which will
 935        only be done if m.uncertainty_samples > 0.
 936    figsize: Set the plot's size (in px).
 937
 938    Returns
 939    -------
 940    A Plotly Figure.
 941    """
 942    props = get_seasonality_plotly_props(m, name, uncertainty)
 943    layout = go.Layout(
 944        width=figsize[0],
 945        height=figsize[1],
 946        showlegend=False,
 947        xaxis=props['xaxis'],
 948        yaxis=props['yaxis']
 949    )
 950    fig = go.Figure(data=props['traces'], layout=layout)
 951    return fig
 952
 953
 954def get_forecast_component_plotly_props(
 955    m: Prophet,
 956    fcst: pd.DataFrame,
 957    name: str,
 958    uncertainty: bool = True,
 959    plot_cap: bool = False,
 960) -> _PlotlyProps:
 961    """Prepares a dictionary for plotting the selected forecast component with Plotly
 962
 963    Parameters
 964    ----------
 965    m: Prophet model.
 966    fcst: pd.DataFrame output of m.predict.
 967    name: Name of the component to plot.
 968    uncertainty: Optional boolean to plot uncertainty intervals, which will
 969        only be done if m.uncertainty_samples > 0.
 970    plot_cap: Optional boolean indicating if the capacity should be shown
 971        in the figure, if available.
 972
 973    Returns
 974    -------
 975    A dictionary with Plotly traces, xaxis and yaxis
 976    """
 977    prediction_color = '#0072B2'
 978    error_color = 'rgba(0, 114, 178, 0.2)'  # '#0072B2' with 0.2 opacity
 979    cap_color = 'black'
 980    zeroline_color = '#AAA'
 981    line_width = 2
 982
 983    range_margin = (fcst['ds'].max() - fcst['ds'].min()) * 0.05
 984    range_x = [fcst['ds'].min() - range_margin, fcst['ds'].max() + range_margin]
 985
 986    text = None
 987    mode = 'lines'
 988    if name == 'holidays':
 989        
 990        # Combine holidays into one hover text
 991        holidays = m.construct_holiday_dataframe(fcst['ds'])
 992        holiday_features, _, _ = m.make_holiday_features(fcst['ds'], holidays)
 993        holiday_features.columns = holiday_features.columns.str.replace('_delim_', '', regex=False)
 994        holiday_features.columns = holiday_features.columns.str.replace('+0', '', regex=False)
 995        text = pd.Series(data='', index=holiday_features.index)
 996        for holiday_feature, idxs in holiday_features.items():
 997            # https://github.com/facebook/pyrefly/issues/2248
 998            # pyrefly:ignore[unsupported-operation]
 999            text[idxs.astype(bool) & (text != '')] += '<br>'  # Add newline if additional holiday
1000            text[idxs.astype(bool)] += holiday_feature  # pyrefly:ignore[unsupported-operation]
1001
1002    traces = []
1003    traces.append(go.Scatter(
1004        name=name,
1005        x=fcst['ds'],
1006        y=fcst[name],
1007        mode=mode,
1008        line=go.scatter.Line(color=prediction_color, width=line_width),
1009        text=text,
1010    ))
1011    if uncertainty and m.uncertainty_samples and (fcst[name + '_upper'] != fcst[name + '_lower']).any():
1012        if mode == 'markers':
1013            traces[0].update(
1014                error_y=dict(
1015                    type='data',
1016                    symmetric=False,
1017                    array=fcst[name + '_upper'],
1018                    arrayminus=fcst[name + '_lower'],
1019                    width=0,
1020                    color=error_color
1021                )
1022            )
1023        else:
1024            traces.append(go.Scatter(
1025                name=name + '_upper',
1026                x=fcst['ds'],
1027                y=fcst[name + '_upper'],
1028                mode=mode,
1029                line=go.scatter.Line(width=0, color=error_color)
1030            ))
1031            traces.append(go.Scatter(
1032                name=name + '_lower',
1033                x=fcst['ds'],
1034                y=fcst[name + '_lower'],
1035                mode=mode,
1036                line=go.scatter.Line(width=0, color=error_color),
1037                fillcolor=error_color,
1038                fill='tonexty'
1039            ))
1040    if 'cap' in fcst and plot_cap:
1041        traces.append(go.Scatter(
1042            name='Cap',
1043            x=fcst['ds'],
1044            y=fcst['cap'],
1045            mode='lines',
1046            line=go.scatter.Line(color=cap_color, dash='dash', width=line_width),
1047        ))
1048    if m.logistic_floor and 'floor' in fcst and plot_cap:
1049        traces.append(go.Scatter(
1050            name='Floor',
1051            x=fcst['ds'],
1052            y=fcst['floor'],
1053            mode='lines',
1054            line=go.scatter.Line(color=cap_color, dash='dash', width=line_width),
1055        ))
1056
1057    xaxis = go.layout.XAxis(
1058        type='date',
1059        range=range_x)
1060    yaxis = go.layout.YAxis(rangemode='normal' if name == 'trend' else 'tozero',
1061                            title=go.layout.yaxis.Title(text=name),
1062                            zerolinecolor=zeroline_color)
1063    assert m.component_modes
1064    if name in m.component_modes['multiplicative']:
1065        yaxis.update(tickformat='%', hoverformat='.2%')
1066    return {'traces': traces, 'xaxis': xaxis, 'yaxis': yaxis}
1067
1068
1069def get_seasonality_plotly_props(
1070    m: Prophet,
1071    name: str,
1072    uncertainty: bool = True,
1073) -> _PlotlyProps:
1074    """Prepares a dictionary for plotting the selected seasonality with Plotly
1075
1076    Parameters
1077    ----------
1078    m: Prophet model.
1079    name: Name of the component to plot.
1080    uncertainty: Optional boolean to plot uncertainty intervals, which will
1081        only be done if m.uncertainty_samples > 0.
1082
1083    Returns
1084    -------
1085    A dictionary with Plotly traces, xaxis and yaxis
1086    """
1087    prediction_color = '#0072B2'
1088    error_color = 'rgba(0, 114, 178, 0.2)'  # '#0072B2' with 0.2 opacity
1089    line_width = 2
1090    zeroline_color = '#AAA'
1091
1092    # Compute seasonality from Jan 1 through a single period.
1093    start = pd.to_datetime('2017-01-01 0000')
1094    period = m.seasonalities[name]['period']
1095    end = start + pd.Timedelta(days=period)
1096    assert m.history is not None
1097    if (m.history['ds'].dt.hour == 0).all():  # Day Precision
1098        plot_points = np.floor(period).astype(int)
1099    elif (m.history['ds'].dt.minute == 0).all():  # Hour Precision
1100        plot_points = np.floor(period * 24).astype(int)
1101    else:  # Minute Precision
1102        plot_points = np.floor(period * 24 * 60).astype(int)
1103    days = pd.to_datetime(np.linspace(start.value, end.value, plot_points, endpoint=False))
1104    df_y = seasonality_plot_df(m, days)
1105    seas = m.predict_seasonal_components(df_y)
1106
1107    traces = []
1108    traces.append(go.Scatter(
1109        name=name,
1110        x=df_y['ds'],
1111        y=seas[name],
1112        mode='lines',
1113        line=go.scatter.Line(color=prediction_color, width=line_width)
1114    ))
1115    if uncertainty and m.uncertainty_samples and (seas[name + '_upper'] != seas[name + '_lower']).any():
1116        traces.append(go.Scatter(
1117            name=name + '_upper',
1118            x=df_y['ds'],
1119            y=seas[name + '_upper'],
1120            mode='lines',
1121            line=go.scatter.Line(width=0, color=error_color)
1122        ))
1123        traces.append(go.Scatter(
1124            name=name + '_lower',
1125            x=df_y['ds'],
1126            y=seas[name + '_lower'],
1127            mode='lines',
1128            line=go.scatter.Line(width=0, color=error_color),
1129            fillcolor=error_color,
1130            fill='tonexty'
1131        ))
1132
1133    # Set tick formats (examples are based on 2017-01-06 21:15)
1134    if period <= 2:
1135        tickformat = '%H:%M'  # "21:15"
1136    elif period < 7:
1137        tickformat = '%A %H:%M'  # "Friday 21:15"
1138    elif period < 14:
1139        tickformat = '%A'  # "Friday"
1140    else:
1141        tickformat = '%B %e'  # "January  6"
1142
1143    range_margin = (df_y['ds'].max() - df_y['ds'].min()) * 0.05
1144    xaxis = go.layout.XAxis(
1145        tickformat=tickformat,
1146        type='date',
1147        range=[df_y['ds'].min() - range_margin, df_y['ds'].max() + range_margin]
1148    )
1149
1150    yaxis = go.layout.YAxis(title=go.layout.yaxis.Title(text=name),
1151                            zerolinecolor=zeroline_color)
1152    if m.seasonalities[name]['mode'] == 'multiplicative':
1153        yaxis.update(tickformat='%', hoverformat='.2%')
1154
1155    return {'traces': traces, 'xaxis': xaxis, 'yaxis': yaxis}
logger: logging.Logger = <Logger prophet.plot (INFO)>
def plot( m: 'Prophet', fcst: pandas.DataFrame, ax: matplotlib.axes._axes.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) -> matplotlib.figure.Figure:
 60def plot(
 61    m: Prophet,
 62    fcst: pd.DataFrame,
 63    ax: plt.Axes | None = None,
 64    uncertainty: bool = True,
 65    plot_cap: bool = True,
 66    xlabel: str = "ds",
 67    ylabel: str = "y",
 68    figsize: tuple[int, int] = (10, 6),
 69    include_legend: bool = False,
 70) -> plt.Figure:
 71    """Plot the Prophet forecast.
 72
 73    Parameters
 74    ----------
 75    m: Prophet model.
 76    fcst: pd.DataFrame output of m.predict.
 77    ax: Optional matplotlib axes on which to plot.
 78    uncertainty: Optional boolean to plot uncertainty intervals, which will
 79        only be done if m.uncertainty_samples > 0.
 80    plot_cap: Optional boolean indicating if the capacity should be shown
 81        in the figure, if available.
 82    xlabel: Optional label name on X-axis
 83    ylabel: Optional label name on Y-axis
 84    figsize: Optional tuple width, height in inches.
 85    include_legend: Optional boolean to add legend to the plot.
 86
 87    Returns
 88    -------
 89    A matplotlib figure.
 90    """
 91    user_provided_ax = False if ax is None else True
 92    if ax is None:
 93        fig = plt.figure(facecolor='w', figsize=figsize)
 94        ax = fig.add_subplot(111)
 95    else:
 96        fig = cast('plt.Figure', ax.get_figure())
 97    fcst_t = fcst['ds']
 98    history = cast('pd.DataFrame', m.history)
 99    ax.plot(history['ds'], history['y'], 'k.', label='Observed data points')
100    ax.plot(fcst_t, fcst['yhat'], ls='-', c='#0072B2', label='Forecast')
101    if 'cap' in fcst and plot_cap:
102        ax.plot(fcst_t, fcst['cap'], ls='--', c='k', label='Maximum capacity')
103    if m.logistic_floor and 'floor' in fcst and plot_cap:
104        ax.plot(fcst_t, fcst['floor'], ls='--', c='k', label='Minimum capacity')
105    if uncertainty and m.uncertainty_samples:
106        ax.fill_between(fcst_t, fcst['yhat_lower'], fcst['yhat_upper'],
107                        color='#0072B2', alpha=0.2, label='Uncertainty interval')
108    # Specify formatting to workaround matplotlib issue #12925
109    locator = AutoDateLocator(interval_multiples=False)
110    formatter = AutoDateFormatter(locator)
111    ax.xaxis.set_major_locator(locator)
112    ax.xaxis.set_major_formatter(formatter)
113    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
114    ax.set_xlabel(xlabel)
115    ax.set_ylabel(ylabel)
116    if include_legend:
117        ax.legend()
118    if not user_provided_ax:
119        try:
120            if fig.get_layout_engine() is None:
121                fig.tight_layout()
122        except AttributeError:
123            fig.tight_layout()
124    return fig

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.
def plot_components( m: 'Prophet', fcst: pandas.DataFrame, uncertainty: bool = True, plot_cap: bool = True, weekly_start: int = 0, yearly_start: int = 0, figsize: tuple[int, int] | None = None) -> matplotlib.figure.Figure:
127def plot_components(
128    m: Prophet,
129    fcst: pd.DataFrame,
130    uncertainty: bool = True,
131    plot_cap: bool = True,
132    weekly_start: int = 0,
133    yearly_start: int = 0,
134    figsize: tuple[int, int] | None = None,
135) -> plt.Figure:
136    """Plot the Prophet forecast components.
137
138    Will plot whichever are available of: trend, holidays, weekly
139    seasonality, yearly seasonality, and additive and multiplicative extra
140    regressors.
141
142    Parameters
143    ----------
144    m: Prophet model.
145    fcst: pd.DataFrame output of m.predict.
146    uncertainty: Optional boolean to plot uncertainty intervals, which will
147        only be done if m.uncertainty_samples > 0.
148    plot_cap: Optional boolean indicating if the capacity should be shown
149        in the figure, if available.
150    weekly_start: Optional int specifying the start day of the weekly
151        seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
152        by 1 day to Monday, and so on.
153    yearly_start: Optional int specifying the start day of the yearly
154        seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
155        by 1 day to Jan 2, and so on.
156    figsize: Optional tuple width, height in inches.
157
158    Returns
159    -------
160    A matplotlib figure.
161    """
162    # Identify components to be plotted
163    components = ['trend']
164    if m.train_holiday_names is not None and 'holidays' in fcst:
165        components.append('holidays')
166    # Plot weekly seasonality, if present
167    if 'weekly' in m.seasonalities and 'weekly' in fcst:
168        components.append('weekly')
169    # Yearly if present
170    if 'yearly' in m.seasonalities and 'yearly' in fcst:
171        components.append('yearly')
172    # Other seasonalities
173    components.extend([
174        name for name in sorted(m.seasonalities)
175        if name in fcst and name not in ['weekly', 'yearly']
176    ])
177    regressors = {'additive': False, 'multiplicative': False}
178    for name, props in m.extra_regressors.items():
179        regressors[props['mode']] = True
180    for mode in ['additive', 'multiplicative']:
181        if regressors[mode] and 'extra_regressors_{}'.format(mode) in fcst:
182            components.append('extra_regressors_{}'.format(mode))
183    npanel = len(components)
184
185    figsize = figsize if figsize else (9, 3 * npanel)
186    fig, axes = plt.subplots(npanel, 1, facecolor='w', figsize=figsize)
187
188    if npanel == 1:
189        axes = [axes]
190
191    multiplicative_axes = []
192
193    dt = cast('pd.DataFrame', m.history)['ds'].diff()
194    min_dt = dt.iloc[cast('np.ndarray', dt.values).nonzero()[0]].min() 
195
196    for ax, plot_name in zip(axes, components):
197        if plot_name == 'trend':
198            plot_forecast_component(
199                m=m, fcst=fcst, name='trend', ax=ax, uncertainty=uncertainty,
200                plot_cap=plot_cap,
201            )
202        elif plot_name in m.seasonalities:
203            if (
204                (plot_name == 'weekly' or m.seasonalities[plot_name]['period'] == 7)
205                and (min_dt == pd.Timedelta(days=1))
206            ):
207                plot_weekly(
208                    m=m, name=plot_name, ax=ax, uncertainty=uncertainty, weekly_start=weekly_start
209                )
210            elif plot_name == 'yearly' or m.seasonalities[plot_name]['period'] == 365.25:
211                plot_yearly(
212                    m=m, name=plot_name, ax=ax, uncertainty=uncertainty, yearly_start=yearly_start
213                )
214            else:
215                plot_seasonality(
216                    m=m, name=plot_name, ax=ax, uncertainty=uncertainty,
217                )
218        elif plot_name in [
219            'holidays',
220            'extra_regressors_additive',
221            'extra_regressors_multiplicative',
222        ]:
223            plot_forecast_component(
224                m=m, fcst=fcst, name=plot_name, ax=ax, uncertainty=uncertainty,
225                plot_cap=False,
226            )
227        assert m.component_modes is not None
228        if plot_name in m.component_modes['multiplicative']:
229            multiplicative_axes.append(ax)
230
231    try:
232        if fig.get_layout_engine() is None:
233            fig.tight_layout()
234    except AttributeError:
235        fig.tight_layout()
236    # Reset multiplicative axes labels after tight_layout adjustment
237    for ax in multiplicative_axes:
238        ax = set_y_as_percent(ax)
239    return fig

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.
def plot_forecast_component( m: 'Prophet', fcst: pandas.DataFrame, name: str, ax: matplotlib.axes._axes.Axes | None = None, uncertainty: bool = True, plot_cap: bool = False, figsize: tuple[int, int] = (10, 6)) -> Sequence[matplotlib.artist.Artist]:
242def plot_forecast_component(
243    m: Prophet,
244    fcst: pd.DataFrame,
245    name: str,
246    ax: plt.Axes | None = None,
247    uncertainty: bool = True,
248    plot_cap: bool = False,
249    figsize: tuple[int, int] = (10, 6),
250) -> Sequence[plt.Artist]:
251    """Plot a particular component of the forecast.
252
253    Parameters
254    ----------
255    m: Prophet model.
256    fcst: pd.DataFrame output of m.predict.
257    name: Name of the component to plot.
258    ax: Optional matplotlib Axes to plot on.
259    uncertainty: Optional boolean to plot uncertainty intervals, which will
260        only be done if m.uncertainty_samples > 0.
261    plot_cap: Optional boolean indicating if the capacity should be shown
262        in the figure, if available.
263    figsize: Optional tuple width, height in inches.
264
265    Returns
266    -------
267    a list of matplotlib artists
268    """
269    artists = []
270    if not ax:
271        fig = plt.figure(facecolor='w', figsize=figsize)
272        ax = fig.add_subplot(111)
273    fcst_t = fcst['ds']
274    artists += ax.plot(fcst_t, fcst[name], ls='-', c='#0072B2')
275    if 'cap' in fcst and plot_cap:
276        artists += ax.plot(fcst_t, fcst['cap'], ls='--', c='k')
277    if m.logistic_floor and 'floor' in fcst and plot_cap:
278        ax.plot(fcst_t, fcst['floor'], ls='--', c='k')
279    if uncertainty and m.uncertainty_samples:
280        artists += [ax.fill_between(
281            fcst_t, fcst[name + '_lower'], fcst[name + '_upper'],
282            color='#0072B2', alpha=0.2)]
283    # Specify formatting to workaround matplotlib issue #12925
284    locator = AutoDateLocator(interval_multiples=False)
285    formatter = AutoDateFormatter(locator)
286    ax.xaxis.set_major_locator(locator)
287    ax.xaxis.set_major_formatter(formatter)
288    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
289    ax.set_xlabel('ds')
290    ax.set_ylabel(name)
291    assert m.component_modes
292    if name in m.component_modes['multiplicative']:
293        ax = set_y_as_percent(ax)
294    return artists

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
def seasonality_plot_df( m: 'Prophet', ds: Union[Sequence[pandas.Timestamp], pandas.DatetimeIndex]) -> pandas.DataFrame:
297def seasonality_plot_df(
298    m: Prophet,
299    ds: Sequence[pd.Timestamp] | pd.DatetimeIndex,
300) -> pd.DataFrame:
301    """Prepare dataframe for plotting seasonal components.
302
303    Parameters
304    ----------
305    m: Prophet model.
306    ds: List of dates for column ds.
307
308    Returns
309    -------
310    A dataframe with seasonal components on ds.
311    """
312    df_dict = {'ds': ds, 'cap': 1., 'floor': 0.}
313    for name in m.extra_regressors:
314        df_dict[name] = 0.
315    # Activate all conditional seasonality columns
316    for props in m.seasonalities.values():
317        if props['condition_name'] is not None:
318            df_dict[props['condition_name']] = True
319    df = pd.DataFrame(df_dict)
320    df = m.setup_dataframe(df)
321    return df

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.
def plot_weekly( m: 'Prophet', ax: matplotlib.axes._axes.Axes | None = None, uncertainty: bool = True, weekly_start: int = 0, figsize: tuple[int, int] = (10, 6), name: str = 'weekly') -> Sequence[matplotlib.artist.Artist]:
324def plot_weekly(
325    m: Prophet,
326    ax: plt.Axes | None = None,
327    uncertainty: bool = True,
328    weekly_start: int = 0,
329    figsize: tuple[int, int] = (10, 6),
330    name: str = 'weekly',
331) -> Sequence[plt.Artist]:
332    """Plot the weekly component of the forecast.
333
334    Parameters
335    ----------
336    m: Prophet model.
337    ax: Optional matplotlib Axes to plot on. One will be created if this
338        is not provided.
339    uncertainty: Optional boolean to plot uncertainty intervals, which will
340        only be done if m.uncertainty_samples > 0.
341    weekly_start: Optional int specifying the start day of the weekly
342        seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
343        by 1 day to Monday, and so on.
344    figsize: Optional tuple width, height in inches.
345    name: Name of seasonality component if changed from default 'weekly'.
346
347    Returns
348    -------
349    a list of matplotlib artists
350    """
351    artists = []
352    if not ax:
353        fig = plt.figure(facecolor='w', figsize=figsize)
354        ax = fig.add_subplot(111)
355    # Compute weekly seasonality for a Sun-Sat sequence of dates.
356    days = (pd.date_range(start='2017-01-01', periods=7) +
357            pd.Timedelta(days=weekly_start))
358    df_w = seasonality_plot_df(m, days)
359    seas = m.predict_seasonal_components(df_w)
360    days = days.day_name()
361    artists += ax.plot(range(len(days)), seas[name], ls='-',
362                    c='#0072B2')
363    if uncertainty and m.uncertainty_samples:
364        artists += [ax.fill_between(range(len(days)),
365                                    seas[name + '_lower'], seas[name + '_upper'],
366                                    color='#0072B2', alpha=0.2)]
367    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
368    ax.set_xticks(range(len(days)))
369    ax.set_xticklabels(days)
370    ax.set_xlabel('Day of week')
371    ax.set_ylabel(name)
372    if m.seasonalities[name]['mode'] == 'multiplicative':
373        ax = set_y_as_percent(ax)
374    return artists

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
def plot_yearly( m: 'Prophet', ax: matplotlib.axes._axes.Axes | None = None, uncertainty: bool = True, yearly_start: int = 0, figsize: tuple[int, int] = (10, 6), name: str = 'yearly') -> Sequence[matplotlib.artist.Artist]:
377def plot_yearly(
378    m: Prophet,
379    ax: plt.Axes | None = None,
380    uncertainty: bool = True,
381    yearly_start: int = 0,
382    figsize: tuple[int, int] = (10, 6),
383    name: str = 'yearly',
384) -> Sequence[plt.Artist]:
385    """Plot the yearly component of the forecast.
386
387    Parameters
388    ----------
389    m: Prophet model.
390    ax: Optional matplotlib Axes to plot on. One will be created if
391        this is not provided.
392    uncertainty: Optional boolean to plot uncertainty intervals, which will
393        only be done if m.uncertainty_samples > 0.
394    yearly_start: Optional int specifying the start day of the yearly
395        seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
396        by 1 day to Jan 2, and so on.
397    figsize: Optional tuple width, height in inches.
398    name: Name of seasonality component if previously changed from default 'yearly'.
399
400    Returns
401    -------
402    a list of matplotlib artists
403    """
404    artists = []
405    if not ax:
406        fig = plt.figure(facecolor='w', figsize=figsize)
407        ax = fig.add_subplot(111)
408    # Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates.
409    days = (pd.date_range(start='2017-01-01', periods=365) +
410            pd.Timedelta(days=yearly_start))
411    df_y = seasonality_plot_df(m, days)
412    seas = m.predict_seasonal_components(df_y)
413    artists += ax.plot(
414        df_y['ds'], seas[name], ls='-', c='#0072B2')
415    if uncertainty and m.uncertainty_samples:
416        artists += [ax.fill_between(
417            df_y['ds'], seas[name + '_lower'],
418            seas[name + '_upper'], color='#0072B2', alpha=0.2)]
419    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
420    months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
421    ax.xaxis.set_major_formatter(FuncFormatter(
422        lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))
423    ax.xaxis.set_major_locator(months)
424    ax.set_xlabel('Day of year')
425    ax.set_ylabel(name)
426    if m.seasonalities[name]['mode'] == 'multiplicative':
427        ax = set_y_as_percent(ax)
428    return artists

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
def plot_seasonality( m: 'Prophet', name: str, ax: matplotlib.axes._axes.Axes | None = None, uncertainty: bool = True, figsize: tuple[int, int] = (10, 6)) -> Sequence[matplotlib.artist.Artist]:
431def plot_seasonality(
432    m: Prophet,
433    name: str,
434    ax: plt.Axes | None = None,
435    uncertainty: bool = True,
436    figsize: tuple[int, int] = (10, 6),
437) -> Sequence[plt.Artist]:
438    """Plot a custom seasonal component.
439
440    Parameters
441    ----------
442    m: Prophet model.
443    name: Seasonality name, like 'daily', 'weekly'.
444    ax: Optional matplotlib Axes to plot on. One will be created if
445        this is not provided.
446    uncertainty: Optional boolean to plot uncertainty intervals, which will
447        only be done if m.uncertainty_samples > 0.
448    figsize: Optional tuple width, height in inches.
449
450    Returns
451    -------
452    a list of matplotlib artists
453    """
454    artists = []
455    if not ax:
456        fig = plt.figure(facecolor='w', figsize=figsize)
457        ax = fig.add_subplot(111)
458    # Compute seasonality from Jan 1 through a single period.
459    start = pd.to_datetime('2017-01-01 0000')
460    period = m.seasonalities[name]['period']
461    end = start + pd.Timedelta(days=period)
462    plot_points = 200
463    # https://github.com/pandas-dev/pandas-stubs/issues/1645
464    days = pd.to_datetime(np.linspace(start.value, end.value, plot_points))  # pyrefly:ignore[no-matching-overload]
465    df_y = seasonality_plot_df(m, days)
466    seas = m.predict_seasonal_components(df_y)
467    artists += ax.plot(df_y['ds'], seas[name], ls='-',
468                        c='#0072B2')
469    if uncertainty and m.uncertainty_samples:
470        artists += [ax.fill_between(
471            df_y['ds'], seas[name + '_lower'],
472            seas[name + '_upper'], color='#0072B2', alpha=0.2)]
473    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
474    n_ticks = 8
475    # https://github.com/pandas-dev/pandas-stubs/issues/1645
476    xticks = pd.to_datetime(np.linspace(start.value, end.value, n_ticks)  # pyrefly:ignore[no-matching-overload]
477        ).to_pydatetime()
478    ax.set_xticks(xticks)
479    if name == 'yearly':
480        fmt = FuncFormatter(
481            lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x)))
482        ax.set_xlabel('Day of year')
483    elif name == 'weekly':
484        fmt = FuncFormatter(
485            lambda x, pos=None: '{dt:%A}'.format(dt=num2date(x)))
486        ax.set_xlabel('Day of Week')
487    elif name == 'daily':
488        fmt = FuncFormatter(
489            lambda x, pos=None: '{dt:%T}'.format(dt=num2date(x)))
490        ax.set_xlabel('Hour of day')
491    elif period <= 2:
492        fmt = FuncFormatter(
493            lambda x, pos=None: '{dt:%T}'.format(dt=num2date(x)))
494        ax.set_xlabel('Hours')
495    else:
496        fmt = FuncFormatter(
497            lambda x, pos=None: '{:.0f}'.format(pos * period / (n_ticks - 1)))
498        ax.set_xlabel('Days')
499    ax.xaxis.set_major_formatter(fmt)
500    ax.set_ylabel(name)
501    if m.seasonalities[name]['mode'] == 'multiplicative':
502        ax = set_y_as_percent(ax)
503    return artists

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
def set_y_as_percent(ax: '_AxT') -> '_AxT':
506def set_y_as_percent(ax: _AxT) -> _AxT:
507    yticks = 100 * ax.get_yticks()
508    yticklabels = ['{0:.4g}%'.format(y) for y in yticks]
509    ax.set_yticks(ax.get_yticks().tolist())
510    ax.set_yticklabels(yticklabels)
511    return ax
def add_changepoints_to_plot( ax: matplotlib.axes._axes.Axes, m: 'Prophet', fcst: pandas.DataFrame, threshold: float = 0.01, cp_color: str = 'r', cp_linestyle: str = '--', trend: bool = True) -> list[matplotlib.lines.Line2D]:
514def add_changepoints_to_plot(
515    ax: plt.Axes,
516    m: Prophet,
517    fcst: pd.DataFrame,
518    threshold: float = 0.01,
519    cp_color: str = 'r',
520    cp_linestyle: str = '--',
521    trend: bool = True,
522) -> list[plt.Line2D]:
523    """Add markers for significant changepoints to prophet forecast plot.
524
525    Example:
526    fig = m.plot(forecast)
527    add_changepoints_to_plot(fig.gca(), m, forecast)
528
529    Parameters
530    ----------
531    ax: axis on which to overlay changepoint markers.
532    m: Prophet model.
533    fcst: Forecast output from m.predict.
534    threshold: Threshold on trend change magnitude for significance.
535    cp_color: Color of changepoint markers.
536    cp_linestyle: Linestyle for changepoint markers.
537    trend: If True, will also overlay the trend.
538
539    Returns
540    -------
541    a list of matplotlib artists
542    """
543    artists = []
544    if trend:
545        artists.extend(ax.plot(fcst['ds'], fcst['trend'], c=cp_color))
546    
547    assert m.changepoints is not None
548    signif_changepoints = m.changepoints[
549        np.abs(np.nanmean(m.params['delta'], axis=0)) >= threshold
550    ] if len(m.changepoints) > 0 else []
551    for cp in signif_changepoints:
552        # Matplotlib stubs type axvline x as float; pandas Timestamp is accepted at runtime.
553        artists.append(ax.axvline(x=cp, c=cp_color, ls=cp_linestyle))  # pyrefly:ignore[bad-argument-type]
554    return artists

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
def plot_cross_validation_metric( df_cv: pandas.DataFrame, metric: str, rolling_window: float = 0.1, ax: matplotlib.axes._axes.Axes | None = None, figsize: tuple[int, int] = (10, 6), color: str = 'b', point_color: str = 'gray') -> matplotlib.figure.Figure:
557def plot_cross_validation_metric(
558    df_cv: pd.DataFrame,
559    metric: str,
560    rolling_window: float = 0.1,
561    ax: plt.Axes | None = None,
562    figsize: tuple[int, int] = (10, 6),
563    color: str = 'b',
564    point_color: str = 'gray',
565) -> plt.Figure:
566    """Plot a performance metric vs. forecast horizon from cross validation.
567
568    Cross validation produces a collection of out-of-sample model predictions
569    that can be compared to actual values, at a range of different horizons
570    (distance from the cutoff). This computes a specified performance metric
571    for each prediction, and aggregated over a rolling window with horizon.
572
573    This uses prophet.diagnostics.performance_metrics to compute the metrics.
574    Valid values of metric are 'mse', 'rmse', 'mae', 'mape', 'mdape', 'smape', and 'coverage'.
575
576    rolling_window is the proportion of data included in the rolling window of
577    aggregation. The default value of 0.1 means 10% of data are included in the
578    aggregation for computing the metric.
579
580    As a concrete example, if metric='mse', then this plot will show the
581    squared error for each cross validation prediction, along with the MSE
582    averaged over rolling windows of 10% of the data.
583
584    Parameters
585    ----------
586    df_cv: The output from prophet.diagnostics.cross_validation.
587    metric: Metric name, one of ['mse', 'rmse', 'mae', 'mape', 'mdape', 'smape', 'coverage'].
588    rolling_window: Proportion of data to use for rolling average of metric.
589        In [0, 1]. Defaults to 0.1.
590    ax: Optional matplotlib axis on which to plot. If not given, a new figure
591        will be created.
592    figsize: Optional tuple width, height in inches.
593    color: Optional color for plot and error points, useful when plotting
594        multiple model performances on one axis for comparison.
595
596    Returns
597    -------
598    a matplotlib figure.
599    """
600    if ax is None:
601        fig = plt.figure(facecolor='w', figsize=figsize)
602        ax = fig.add_subplot(111)
603    else:
604        fig = cast('plt.Figure', ax.get_figure())
605    # Get the metric at the level of individual predictions, and with the rolling window.
606    df_none = performance_metrics(df_cv, metrics=[metric], rolling_window=-1)
607    df_h = performance_metrics(df_cv, metrics=[metric], rolling_window=rolling_window)
608    
609    assert df_none is not None
610    assert df_h is not None
611
612    # Some work because matplotlib does not handle timedelta
613    # Target ~10 ticks.
614    tick_w = max(df_none['horizon'].astype('timedelta64[ns]')) / 10.
615    # Find the largest time resolution that has <1 unit per bin.
616    dts: list[Literal["D", "h", "m", "s", "ms", "us", "ns"]]
617    dts = ['D', 'h', 'm', 's', 'ms', 'us', 'ns']
618    dt_names = [
619        'days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds',
620        'nanoseconds'
621    ]
622    dt_conversions = [
623        24 * 60 * 60 * 10 ** 9,
624        60 * 60 * 10 ** 9,
625        60 * 10 ** 9,
626        10 ** 9,
627        10 ** 6,
628        10 ** 3,
629        1.,
630    ]
631    for i, dt in enumerate(dts):
632        if np.timedelta64(1, dt) < np.timedelta64(tick_w, 'ns'):
633            break
634
635    x_plt = np.asarray(df_none['horizon'].astype('timedelta64[ns]')).view(np.int64) / float(dt_conversions[i])
636    x_plt_h = np.asarray(df_h['horizon'].astype('timedelta64[ns]')).view(np.int64) / float(dt_conversions[i])
637
638    ax.plot(x_plt, df_none[metric], '.', alpha=0.1, c=point_color)
639    ax.plot(x_plt_h, df_h[metric], '-', c=color)
640    ax.grid(True)
641
642    ax.set_xlabel('Horizon ({})'.format(dt_names[i]))
643    ax.set_ylabel(metric)
644    return fig

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.
def plot_plotly( m: 'Prophet', fcst: pandas.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)) -> plotly.graph_objs._figure.Figure:
647def plot_plotly(
648    m: Prophet,
649    fcst: pd.DataFrame,
650    uncertainty: bool = True,
651    plot_cap: bool = True,
652    trend: bool = False,
653    changepoints: bool = False,
654    changepoints_threshold: float = 0.01,
655    xlabel: str = 'ds',
656    ylabel: str = 'y',
657    figsize: tuple[int, int] = (900, 600)
658) -> go.Figure:
659    """Plot the Prophet forecast with Plotly offline.
660
661    Plotting in Jupyter Notebook requires initializing plotly.offline.init_notebook_mode():
662    >>> import plotly.offline as py
663    >>> py.init_notebook_mode()
664    Then the figure can be displayed using plotly.offline.iplot(...):
665    >>> fig = plot_plotly(m, fcst)
666    >>> py.iplot(fig)
667    see https://plot.ly/python/offline/ for details
668
669    Parameters
670    ----------
671    m: Prophet model.
672    fcst: pd.DataFrame output of m.predict.
673    uncertainty: Optional boolean to plot uncertainty intervals.
674    plot_cap: Optional boolean indicating if the capacity should be shown
675        in the figure, if available.
676    trend: Optional boolean to plot trend
677    changepoints: Optional boolean to plot changepoints
678    changepoints_threshold: Threshold on trend change magnitude for significance.
679    xlabel: Optional label name on X-axis
680    ylabel: Optional label name on Y-axis
681    figsize: The plot's size (in px).
682
683    Returns
684    -------
685    A Plotly Figure.
686    """
687    prediction_color = '#0072B2'
688    error_color = 'rgba(0, 114, 178, 0.2)'  # '#0072B2' with 0.2 opacity
689    actual_color = 'black'
690    cap_color = 'black'
691    trend_color = '#B23B00'
692    line_width = 2
693    marker_size = 4
694
695    data = []
696    # Add actual
697    assert m.history
698    data.append(go.Scatter(
699        name='Actual',
700        x=m.history['ds'],
701        y=m.history['y'],
702        marker=dict(color=actual_color, size=marker_size),
703        mode='markers'
704    ))
705    # Add lower bound
706    if uncertainty and m.uncertainty_samples:
707        data.append(go.Scatter(
708            x=fcst['ds'],
709            y=fcst['yhat_lower'],
710            mode='lines',
711            line=dict(width=0),
712            hoverinfo='skip'
713        ))
714    # Add prediction
715    data.append(go.Scatter(
716        name='Predicted',
717        x=fcst['ds'],
718        y=fcst['yhat'],
719        mode='lines',
720        line=dict(color=prediction_color, width=line_width),
721        fillcolor=error_color,
722        fill='tonexty' if uncertainty and m.uncertainty_samples else 'none'
723    ))
724    # Add upper bound
725    if uncertainty and m.uncertainty_samples:
726        data.append(go.Scatter(
727            x=fcst['ds'],
728            y=fcst['yhat_upper'],
729            mode='lines',
730            line=dict(width=0),
731            fillcolor=error_color,
732            fill='tonexty',
733            hoverinfo='skip'
734        ))
735    # Add caps
736    if 'cap' in fcst and plot_cap:
737        data.append(go.Scatter(
738            name='Cap',
739            x=fcst['ds'],
740            y=fcst['cap'],
741            mode='lines',
742            line=dict(color=cap_color, dash='dash', width=line_width),
743        ))
744    if m.logistic_floor and 'floor' in fcst and plot_cap:
745        data.append(go.Scatter(
746            name='Floor',
747            x=fcst['ds'],
748            y=fcst['floor'],
749            mode='lines',
750            line=dict(color=cap_color, dash='dash', width=line_width),
751        ))
752    # Add trend
753    if trend:
754        data.append(go.Scatter(
755            name='Trend',
756            x=fcst['ds'],
757            y=fcst['trend'],
758            mode='lines',
759            line=dict(color=trend_color, width=line_width),
760        ))
761    # Add changepoints
762    assert m.changepoints
763    if changepoints and len(m.changepoints) > 0:
764        signif_changepoints = m.changepoints[
765            np.abs(np.nanmean(m.params['delta'], axis=0)) >= changepoints_threshold
766        ]
767        data.append(go.Scatter(
768            x=signif_changepoints,
769            y=fcst.loc[fcst['ds'].isin(signif_changepoints), 'trend'],
770            marker=dict(size=50, symbol='line-ns-open', color=trend_color,
771                        line=dict(width=line_width)),
772            mode='markers',
773            hoverinfo='skip'
774        ))
775
776    layout = dict(
777        showlegend=False,
778        width=figsize[0],
779        height=figsize[1],
780        yaxis=dict(
781            title=ylabel
782        ),
783        xaxis=dict(
784            title=xlabel,
785            type='date',
786            rangeselector=dict(
787                buttons=list([
788                    dict(count=7,
789                         label='1w',
790                         step='day',
791                         stepmode='backward'),
792                    dict(count=1,
793                         label='1m',
794                         step='month',
795                         stepmode='backward'),
796                    dict(count=6,
797                         label='6m',
798                         step='month',
799                         stepmode='backward'),
800                    dict(count=1,
801                         label='1y',
802                         step='year',
803                         stepmode='backward'),
804                    dict(step='all')
805                ])
806            ),
807            rangeslider=dict(
808                visible=True
809            ),
810        ),
811    )
812    fig = go.Figure(data=data, layout=layout)
813    return fig

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.
def plot_components_plotly( m: 'Prophet', fcst: pandas.DataFrame, uncertainty: bool = True, plot_cap: bool = True, figsize: tuple[int, int] = (900, 200)) -> plotly.graph_objs._figure.Figure:
816def plot_components_plotly(
817    m: Prophet,
818    fcst: pd.DataFrame,
819    uncertainty: bool = True,
820    plot_cap: bool = True,
821    figsize: tuple[int, int] = (900, 200),
822) -> go.Figure:
823    """Plot the Prophet forecast components using Plotly.
824    See plot_plotly() for Plotly setup instructions
825
826    Will plot whichever are available of: trend, holidays, weekly
827    seasonality, yearly seasonality, and additive and multiplicative extra
828    regressors.
829
830    Parameters
831    ----------
832    m: Prophet model.
833    fcst: pd.DataFrame output of m.predict.
834    uncertainty: Optional boolean to plot uncertainty intervals, which will
835        only be done if m.uncertainty_samples > 0.
836    plot_cap: Optional boolean indicating if the capacity should be shown
837        in the figure, if available.
838    figsize: Set the size for the subplots (in px).
839
840    Returns
841    -------
842    A Plotly Figure.
843    """
844
845    # Identify components to plot and get their Plotly props
846    components = {}
847    components['trend'] = get_forecast_component_plotly_props(
848        m, fcst, 'trend', uncertainty, plot_cap)
849    if m.train_holiday_names is not None and 'holidays' in fcst:
850        components['holidays'] = get_forecast_component_plotly_props(
851            m, fcst, 'holidays', uncertainty)
852
853    regressors = {'additive': False, 'multiplicative': False}
854    for name, props in m.extra_regressors.items():
855        regressors[props['mode']] = True
856    for mode in ['additive', 'multiplicative']:
857        if regressors[mode] and 'extra_regressors_{}'.format(mode) in fcst:
858            components['extra_regressors_{}'.format(mode)] = get_forecast_component_plotly_props(
859                m, fcst, 'extra_regressors_{}'.format(mode))
860    for seasonality in m.seasonalities:
861        components[seasonality] = get_seasonality_plotly_props(m, seasonality)
862
863    # Create Plotly subplot figure and add the components to it
864    fig = make_subplots(rows=len(components), cols=1, print_grid=False)
865    fig['layout'].update(go.Layout(
866        showlegend=False,
867        width=figsize[0],
868        height=figsize[1] * len(components)
869    ))
870    for i, name in enumerate(components):
871        if i == 0:
872            xaxis = fig['layout']['xaxis']
873            yaxis = fig['layout']['yaxis']
874        else:
875            xaxis = fig['layout']['xaxis{}'.format(i + 1)]
876            yaxis = fig['layout']['yaxis{}'.format(i + 1)]
877        xaxis.update(components[name]['xaxis'])
878        yaxis.update(components[name]['yaxis'])
879        for trace in components[name]['traces']:
880            fig.append_trace(trace, i + 1, 1)
881    return fig

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.
def plot_forecast_component_plotly( m: 'Prophet', fcst: pandas.DataFrame, name: str, uncertainty: bool = True, plot_cap: bool = False, figsize: tuple[int, int] = (900, 300)) -> plotly.graph_objs._figure.Figure:
884def plot_forecast_component_plotly(
885    m: Prophet,
886    fcst: pd.DataFrame,
887    name: str,
888    uncertainty: bool = True,
889    plot_cap: bool = False,
890    figsize: tuple[int, int] = (900, 300)
891) -> go.Figure:
892    """Plot a particular component of the forecast using Plotly.
893    See plot_plotly() for Plotly setup instructions
894
895    Parameters
896    ----------
897    m: Prophet model.
898    fcst: pd.DataFrame output of m.predict.
899    name: Name of the component to plot.
900    uncertainty: Optional boolean to plot uncertainty intervals, which will
901        only be done if m.uncertainty_samples > 0.
902    plot_cap: Optional boolean indicating if the capacity should be shown
903        in the figure, if available.
904    figsize: The plot's size (in px).
905
906    Returns
907    -------
908    A Plotly Figure.
909    """
910    props = get_forecast_component_plotly_props(m, fcst, name, uncertainty, plot_cap)
911    layout = go.Layout(
912        width=figsize[0],
913        height=figsize[1],
914        showlegend=False,
915        xaxis=props['xaxis'],
916        yaxis=props['yaxis']
917    )
918    fig = go.Figure(data=props['traces'], layout=layout)
919    return fig

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.
def plot_seasonality_plotly( m: 'Prophet', name: str, uncertainty: bool = True, figsize: tuple[int, int] = (900, 300)) -> plotly.graph_objs._figure.Figure:
922def plot_seasonality_plotly(
923    m: Prophet,
924    name: str,
925    uncertainty: bool = True,
926    figsize: tuple[int, int] = (900, 300)
927) -> go.Figure:
928    """Plot a custom seasonal component using Plotly.
929    See plot_plotly() for Plotly setup instructions
930
931    Parameters
932    ----------
933    m: Prophet model.
934    name: Seasonality name, like 'daily', 'weekly'.
935    uncertainty: Optional boolean to plot uncertainty intervals, which will
936        only be done if m.uncertainty_samples > 0.
937    figsize: Set the plot's size (in px).
938
939    Returns
940    -------
941    A Plotly Figure.
942    """
943    props = get_seasonality_plotly_props(m, name, uncertainty)
944    layout = go.Layout(
945        width=figsize[0],
946        height=figsize[1],
947        showlegend=False,
948        xaxis=props['xaxis'],
949        yaxis=props['yaxis']
950    )
951    fig = go.Figure(data=props['traces'], layout=layout)
952    return fig

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.
def get_forecast_component_plotly_props( m: 'Prophet', fcst: pandas.DataFrame, name: str, uncertainty: bool = True, plot_cap: bool = False) -> '_PlotlyProps':
 955def get_forecast_component_plotly_props(
 956    m: Prophet,
 957    fcst: pd.DataFrame,
 958    name: str,
 959    uncertainty: bool = True,
 960    plot_cap: bool = False,
 961) -> _PlotlyProps:
 962    """Prepares a dictionary for plotting the selected forecast component with Plotly
 963
 964    Parameters
 965    ----------
 966    m: Prophet model.
 967    fcst: pd.DataFrame output of m.predict.
 968    name: Name of the component to plot.
 969    uncertainty: Optional boolean to plot uncertainty intervals, which will
 970        only be done if m.uncertainty_samples > 0.
 971    plot_cap: Optional boolean indicating if the capacity should be shown
 972        in the figure, if available.
 973
 974    Returns
 975    -------
 976    A dictionary with Plotly traces, xaxis and yaxis
 977    """
 978    prediction_color = '#0072B2'
 979    error_color = 'rgba(0, 114, 178, 0.2)'  # '#0072B2' with 0.2 opacity
 980    cap_color = 'black'
 981    zeroline_color = '#AAA'
 982    line_width = 2
 983
 984    range_margin = (fcst['ds'].max() - fcst['ds'].min()) * 0.05
 985    range_x = [fcst['ds'].min() - range_margin, fcst['ds'].max() + range_margin]
 986
 987    text = None
 988    mode = 'lines'
 989    if name == 'holidays':
 990        
 991        # Combine holidays into one hover text
 992        holidays = m.construct_holiday_dataframe(fcst['ds'])
 993        holiday_features, _, _ = m.make_holiday_features(fcst['ds'], holidays)
 994        holiday_features.columns = holiday_features.columns.str.replace('_delim_', '', regex=False)
 995        holiday_features.columns = holiday_features.columns.str.replace('+0', '', regex=False)
 996        text = pd.Series(data='', index=holiday_features.index)
 997        for holiday_feature, idxs in holiday_features.items():
 998            # https://github.com/facebook/pyrefly/issues/2248
 999            # pyrefly:ignore[unsupported-operation]
1000            text[idxs.astype(bool) & (text != '')] += '<br>'  # Add newline if additional holiday
1001            text[idxs.astype(bool)] += holiday_feature  # pyrefly:ignore[unsupported-operation]
1002
1003    traces = []
1004    traces.append(go.Scatter(
1005        name=name,
1006        x=fcst['ds'],
1007        y=fcst[name],
1008        mode=mode,
1009        line=go.scatter.Line(color=prediction_color, width=line_width),
1010        text=text,
1011    ))
1012    if uncertainty and m.uncertainty_samples and (fcst[name + '_upper'] != fcst[name + '_lower']).any():
1013        if mode == 'markers':
1014            traces[0].update(
1015                error_y=dict(
1016                    type='data',
1017                    symmetric=False,
1018                    array=fcst[name + '_upper'],
1019                    arrayminus=fcst[name + '_lower'],
1020                    width=0,
1021                    color=error_color
1022                )
1023            )
1024        else:
1025            traces.append(go.Scatter(
1026                name=name + '_upper',
1027                x=fcst['ds'],
1028                y=fcst[name + '_upper'],
1029                mode=mode,
1030                line=go.scatter.Line(width=0, color=error_color)
1031            ))
1032            traces.append(go.Scatter(
1033                name=name + '_lower',
1034                x=fcst['ds'],
1035                y=fcst[name + '_lower'],
1036                mode=mode,
1037                line=go.scatter.Line(width=0, color=error_color),
1038                fillcolor=error_color,
1039                fill='tonexty'
1040            ))
1041    if 'cap' in fcst and plot_cap:
1042        traces.append(go.Scatter(
1043            name='Cap',
1044            x=fcst['ds'],
1045            y=fcst['cap'],
1046            mode='lines',
1047            line=go.scatter.Line(color=cap_color, dash='dash', width=line_width),
1048        ))
1049    if m.logistic_floor and 'floor' in fcst and plot_cap:
1050        traces.append(go.Scatter(
1051            name='Floor',
1052            x=fcst['ds'],
1053            y=fcst['floor'],
1054            mode='lines',
1055            line=go.scatter.Line(color=cap_color, dash='dash', width=line_width),
1056        ))
1057
1058    xaxis = go.layout.XAxis(
1059        type='date',
1060        range=range_x)
1061    yaxis = go.layout.YAxis(rangemode='normal' if name == 'trend' else 'tozero',
1062                            title=go.layout.yaxis.Title(text=name),
1063                            zerolinecolor=zeroline_color)
1064    assert m.component_modes
1065    if name in m.component_modes['multiplicative']:
1066        yaxis.update(tickformat='%', hoverformat='.2%')
1067    return {'traces': traces, 'xaxis': xaxis, 'yaxis': yaxis}

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
def get_seasonality_plotly_props(m: 'Prophet', name: str, uncertainty: bool = True) -> '_PlotlyProps':
1070def get_seasonality_plotly_props(
1071    m: Prophet,
1072    name: str,
1073    uncertainty: bool = True,
1074) -> _PlotlyProps:
1075    """Prepares a dictionary for plotting the selected seasonality with Plotly
1076
1077    Parameters
1078    ----------
1079    m: Prophet model.
1080    name: Name of the component to plot.
1081    uncertainty: Optional boolean to plot uncertainty intervals, which will
1082        only be done if m.uncertainty_samples > 0.
1083
1084    Returns
1085    -------
1086    A dictionary with Plotly traces, xaxis and yaxis
1087    """
1088    prediction_color = '#0072B2'
1089    error_color = 'rgba(0, 114, 178, 0.2)'  # '#0072B2' with 0.2 opacity
1090    line_width = 2
1091    zeroline_color = '#AAA'
1092
1093    # Compute seasonality from Jan 1 through a single period.
1094    start = pd.to_datetime('2017-01-01 0000')
1095    period = m.seasonalities[name]['period']
1096    end = start + pd.Timedelta(days=period)
1097    assert m.history is not None
1098    if (m.history['ds'].dt.hour == 0).all():  # Day Precision
1099        plot_points = np.floor(period).astype(int)
1100    elif (m.history['ds'].dt.minute == 0).all():  # Hour Precision
1101        plot_points = np.floor(period * 24).astype(int)
1102    else:  # Minute Precision
1103        plot_points = np.floor(period * 24 * 60).astype(int)
1104    days = pd.to_datetime(np.linspace(start.value, end.value, plot_points, endpoint=False))
1105    df_y = seasonality_plot_df(m, days)
1106    seas = m.predict_seasonal_components(df_y)
1107
1108    traces = []
1109    traces.append(go.Scatter(
1110        name=name,
1111        x=df_y['ds'],
1112        y=seas[name],
1113        mode='lines',
1114        line=go.scatter.Line(color=prediction_color, width=line_width)
1115    ))
1116    if uncertainty and m.uncertainty_samples and (seas[name + '_upper'] != seas[name + '_lower']).any():
1117        traces.append(go.Scatter(
1118            name=name + '_upper',
1119            x=df_y['ds'],
1120            y=seas[name + '_upper'],
1121            mode='lines',
1122            line=go.scatter.Line(width=0, color=error_color)
1123        ))
1124        traces.append(go.Scatter(
1125            name=name + '_lower',
1126            x=df_y['ds'],
1127            y=seas[name + '_lower'],
1128            mode='lines',
1129            line=go.scatter.Line(width=0, color=error_color),
1130            fillcolor=error_color,
1131            fill='tonexty'
1132        ))
1133
1134    # Set tick formats (examples are based on 2017-01-06 21:15)
1135    if period <= 2:
1136        tickformat = '%H:%M'  # "21:15"
1137    elif period < 7:
1138        tickformat = '%A %H:%M'  # "Friday 21:15"
1139    elif period < 14:
1140        tickformat = '%A'  # "Friday"
1141    else:
1142        tickformat = '%B %e'  # "January  6"
1143
1144    range_margin = (df_y['ds'].max() - df_y['ds'].min()) * 0.05
1145    xaxis = go.layout.XAxis(
1146        tickformat=tickformat,
1147        type='date',
1148        range=[df_y['ds'].min() - range_margin, df_y['ds'].max() + range_margin]
1149    )
1150
1151    yaxis = go.layout.YAxis(title=go.layout.yaxis.Title(text=name),
1152                            zerolinecolor=zeroline_color)
1153    if m.seasonalities[name]['mode'] == 'multiplicative':
1154        yaxis.update(tickformat='%', hoverformat='.2%')
1155
1156    return {'traces': traces, 'xaxis': xaxis, 'yaxis': yaxis}

Prepares a dictionary for plotting the selected seasonality with Plotly

Parameters
  • m (Prophet model.):

  • name (Name of the component to plot.):

  • uncertainty (Optional boolean to plot uncertainty intervals, which will): only be done if m.uncertainty_samples > 0.

Returns
  • A dictionary with Plotly traces, xaxis and yaxis