Skip to content

plots

main.plots ¤

Plots for displaying database data.

Classes¤

AnalyticsFigure(plot, group) dataclass ¤

A plot to show in a group on the analytics page.

Attributes¤
group instance-attribute ¤

The group to which the plot belongs.

plot instance-attribute ¤

The plot to be displayed.

Functions:¤

add_varea_glyph(plot, df, upper_trace, lower_trace, colour) ¤

Adds a varea glyph to add shading between traces.

The shading is applied when the upper trace is above the lower trace. If below, no shading is applied. VArea creates this shading between two sets of y-values: the element-wise maximum of the two traces and the lower trace. Otherwise, the shading is applied whenever either trace is above the other.

Parameters:

Name Type Description Default
plot figure

the plot to add the glyph to

required
df DataFrame

pandas DataFrame containing trace data

required
upper_trace str

the label of the upper trace

required
lower_trace str

the label of the lower trace

required
colour str

the colour to apply to the shading

required
Source code in main/plots.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def add_varea_glyph(
    plot: figure, df: pd.DataFrame, upper_trace: str, lower_trace: str, colour: str
) -> None:
    """Adds a varea glyph to add shading between traces.

    The shading is applied when the upper trace is above the lower trace. If below,
    no shading is applied. VArea creates this shading between two sets of y-values:
    the element-wise maximum of the two traces and the lower trace. Otherwise, the
    shading is applied whenever either trace is above the other.

    Args:
        plot: the plot to add the glyph to
        df: pandas DataFrame containing trace data
        upper_trace: the label of the upper trace
        lower_trace: the label of the lower trace
        colour: the colour to apply to the shading
    """
    source = ColumnDataSource(
        {
            "index": df["index"],
            "y1": df[lower_trace],
            "y2": df[upper_trace].combine(df[lower_trace], max),
        }
    )
    plot.add_glyph(
        source, VArea(x="index", y1="y1", y2="y2", fill_color=colour, fill_alpha=0.3)
    )

create_allocation_plot_for_project(project, x_range) ¤

Create an allocation plot for the detail project page.

Always shown when the project has a date range, even with zero allocations, so there's an initial idea of the required FTE before anyone is assigned.

Source code in main/plots.py
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
def create_allocation_plot_for_project(
    project: models.Project, x_range: Range | None
) -> figure | None:
    """Create an allocation plot for the detail project page.

    Always shown when the project has a date range, even with zero
    allocations, so there's an initial idea of the required FTE before
    anyone is assigned.
    """
    if project.start_date is None or project.end_date is None:
        return None

    fte = project.fte(include_excess=False)
    traces = [{"timeseries": fte, "label": "Project FTE", "colour": "green"}]
    colours = cycle(["red", "purple", "yellow", "navy"])
    for allocation in models.Allocation.objects.filter(project=project):
        traces.append(
            {
                "timeseries": allocation.trace(fte.index),  # type: ignore[arg-type]
                "label": str(allocation.user),
                "colour": next(colours),
            }
        )

    plot = create_timeseries_plot(
        "Allocations",
        traces,
        height=200,
        legend_loc="bottom_right",
    )
    plot.yaxis.axis_label = "FTE"
    plot.legend.nrows = 1
    if x_range:
        plot.x_range = x_range
    return plot

create_analytics_layout() ¤

Create the analytics charts in a layout with widgets.

Obtains the analytics charts for projects in the last 12 months and arranges them into a grid of tab-grouped plots.

Returns:

Type Description
figure

A layout containing each of the analytics plots.

Source code in main/plots.py
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
def create_analytics_layout() -> figure:
    """Create the analytics charts in a layout with widgets.

    Obtains the analytics charts for projects in the last 12 months and arranges them
    into a grid of tab-grouped plots.

    Returns:
        A layout containing each of the analytics plots.
    """
    # Get projects active in past 12 months
    today = date.today()
    one_year_ago = today - timedelta(days=365)
    projects_this_year = analytics.get_projects_active_between(one_year_ago, today)

    # Generate the list of plots we wish to display
    figures = _create_analytics_plots(projects_this_year)

    # Hide titles to avoid duplication
    for fig in figures:
        fig.plot.title.visible = False  # type: ignore[union-attr]

    # Arrange into tabbed groups of related plots
    groups = ("projects", "funding", "budget", "funder")
    all_tabs = []
    for group in groups:
        all_tabs.append(
            Tabs(
                tabs=[
                    TabPanel(title=fig.plot.title.text, child=fig.plot)  # type: ignore
                    for fig in figures
                    if fig.group == group
                ],
                sizing_mode="stretch_width",
            )
        )

    # Arrange the plots into a two-column grid layout
    layout = column(  # type: ignore[call-overload]
        [
            gridplot(  # type: ignore[call-overload]
                all_tabs,
                ncols=2,
                sizing_mode="stretch_width",
            ),
        ],
        sizing_mode="stretch_width",
    )
    return layout

create_bar_plot(title, months, values, x_range=None) ¤

Creates a bar plot with dates versus values.

Parameters:

Name Type Description Default
title str

plot title

required
months list[str]

a list of months to display on the x-axis

required
values list[float]

a list of total charge values for the bar height indicate on the y-axis

required
x_range list[str] | None

(optional) list of values to use as the x_range for the displayed plot

None

Returns:

Type Description
figure

Bokeh figure for the bar chart.

Source code in main/plots.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def create_bar_plot(
    title: str,
    months: list[str],
    values: list[float],
    x_range: list[str] | None = None,
) -> figure:
    """Creates a bar plot with dates versus values.

    Args:
        title: plot title
        months: a list of months to display on the x-axis
        values: a list of total charge values for the bar height indicate on the y-axis
        x_range: (optional) list of values to use as the x_range for the displayed plot

    Returns:
        Bokeh figure for the bar chart.
    """
    source = ColumnDataSource(data=dict(months=months, values=values))
    plot = figure(
        x_range=months,  # type: ignore[arg-type]
        title=title,
        height=500,
        background_fill_color="#efefef",
        sizing_mode="stretch_width",
    )
    plot.yaxis.axis_label = "Total charge (£)"
    plot.xaxis.axis_label = "Month-Year"
    plot.vbar(x="months", top="values", width=0.5, source=source)
    if x_range:
        plot.x_range.factors = x_range  # type: ignore[attr-defined]
    # Add basic tooltips to show monthly totals
    hover = HoverTool()
    hover.tooltips = [
        ("Month", "@months"),
        ("Total", "£@values"),
    ]
    plot.add_tools(hover)
    return plot

create_capacity_planning_layout() ¤

Create the capacity planning plot in layout with widgets.

Creates the capacity planning plot plus the associated widgets used to control the data displayed in the plot.

Returns:

Type Description
Row

A Row object (the Row containing a Column of widgets and the plot).

Source code in main/plots.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def create_capacity_planning_layout() -> Row:
    """Create the capacity planning plot in layout with widgets.

    Creates the capacity planning plot plus the associated widgets used to control the
    data displayed in the plot.

    Returns:
        A Row object (the Row containing a Column of widgets and the plot).
    """
    start, end = timezone.now(), timezone.now() + timedelta(days=365)
    # Min and max dates are three years before and ahead of current date
    min_date, max_date = start - timedelta(days=1095), start + timedelta(days=1095)

    # Get the plot to display (it is created with all data, but only the dates
    # in the x_range provided are shown)
    plot, individual_plots = create_capacity_planning_plot(
        start_date=min_date, end_date=max_date, x_range=(start, end)
    )
    plot.title.text_font_size = "20px"  # type: ignore[union-attr]
    plot.yaxis.axis_label = "Capacity and Effort (FTE)"

    # Create a crosshair to show in all plots, synchronised
    height = Span(dimension="height", line_dash="dotted", line_width=2)
    crosshair = CrosshairTool(overlay=height, dimensions="height")

    plot.add_tools(crosshair)
    for i, plt in enumerate(individual_plots):
        plt.add_tools(crosshair)

        plt.y_range = Range1d(0, 1)  # type: ignore[arg-type]
        plt.yaxis.axis_label = "Cap&Eff (FTE)"
        plt.xaxis.axis_label = None
        plt.title.text_font_size = "20px"  # type: ignore[union-attr]

        # --- Remove internal border padding to eliminate the visual gap ---
        plt.min_border_top = 0
        plt.min_border_bottom = 0

        # --- Hide x-axis on all plots except the last two ---
        if i < len(individual_plots) - 2:
            plt.xaxis.major_label_text_font_size = "0pt"  # Hide tick labels
            plt.xaxis.major_tick_line_color = None  # Hide tick marks
            plt.xaxis.minor_tick_line_color = None  # Hide minor ticks

    # Create layout with common plot at the top and individual ones in a grid
    # below
    plot_layout = column(  # type: ignore[call-overload]
        [
            plot,
            gridplot(  # type: ignore[call-overload]
                individual_plots, ncols=2, sizing_mode="stretch_width"
            ),
        ],
        sizing_mode="stretch_width",
    )
    return plot_layout

create_capacity_planning_plot(start_date, end_date, x_range=None) ¤

Generates all the time series data and creates the capacity planning plot.

Includes all business days between the selected start and end date, inclusive of the start date. Timeseries for the effort (separate traces depending on project status) and capacity (aggregated over all users) are calculated.

Parameters:

Name Type Description Default
start_date datetime

datetime object representing the start of the plotting period

required
end_date datetime

datetime object representing the end of the plotting period

required
x_range tuple[datetime, datetime] | None

(optional) tuple of datetimes to use as the x_range for the displayed plot

None

Returns:

Type Description
tuple[figure, list[figure]]

Bokeh figure containing timeseries data.

Source code in main/plots.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def create_capacity_planning_plot(
    start_date: datetime,
    end_date: datetime,
    x_range: tuple[datetime, datetime] | None = None,
) -> tuple[figure, list[figure]]:
    """Generates all the time series data and creates the capacity planning plot.

    Includes all business days between the selected start and end date, inclusive of
    the start date. Timeseries for the effort (separate traces depending on project
    status) and capacity (aggregated over all users) are calculated.

    Args:
        start_date: datetime object representing the start of the plotting period
        end_date: datetime object representing the end of the plotting period
        x_range: (optional) tuple of datetimes to use as the x_range for the displayed
            plot

    Returns:
        Bokeh figure containing timeseries data.
    """
    # Create overall capacity timeseries
    capacities = timeseries.get_capacity_timeseries(start_date, end_date)
    aggregated_capacity = capacities.sum(axis=1)
    traces = [
        {"timeseries": aggregated_capacity, "colour": "darkgreen", "label": "Capacity"}
    ]

    # Create individual effort timeseries according to project status
    projects = (  # Traces are cumulative
        ("Tentative", "firebrick", ["Tentative", "Confirmed", "Active", "Maintenance"]),
        ("Confirmed", "orange", ["Confirmed", "Active", "Maintenance"]),
        ("Maintenance", "purple", ["Active", "Maintenance"]),
        ("Active", "navy", ["Active"]),
    )
    for status, colour, filter in projects:
        effort_timeseries = timeseries.get_effort_timeseries(
            start_date, end_date, filter
        )
        traces.append(
            {
                "timeseries": effort_timeseries,
                "colour": colour,
                "label": f"{status} project effort",
            },
        )

    # Apply area shading between select traces
    vareas: tuple[tuple[tuple[str, str], str], ...] = (
        (("Capacity", "Confirmed project effort"), "green"),
        (("Maintenance project effort", "Active project effort"), "purple"),
        (("Confirmed project effort", "Maintenance project effort"), "yellow"),
        (("Tentative project effort", "Confirmed project effort"), "red"),
    )

    plot = create_timeseries_plot(
        title="Project effort and team capacity over time",
        traces=traces,
        x_range=x_range,
        vareas=vareas,
    )

    allocations = timeseries.get_allocation_timeseries(start_date, end_date)
    individual_plots = []
    vareas = (
        (("Capacity", ""), "green"),
        (("", "Capacity"), "red"),
    )

    for name in capacities.columns:
        traces = [
            {
                "timeseries": capacities[name],
                "colour": "darkgreen",
                "label": "Capacity",
            }
        ]
        allocation = allocations[name]
        all_projects = allocation.sum(axis=1)
        traces.append(
            {
                "timeseries": all_projects,
                "colour": None,
                "label": "",
            }
        )

        colours = cycle(["red", "purple", "yellow", "navy"])
        for project in allocation.columns:
            traces.append(
                {
                    "timeseries": allocation[project],
                    "colour": next(colours),
                    "label": project,
                }
            )
        individual_plots.append(
            create_timeseries_plot(
                title=name,
                traces=traces,
                x_range=x_range,
                vareas=vareas,
                height=150,
                legend_loc="top_right",
            )
        )

    return plot, individual_plots

create_cost_recovery_layout() ¤

Create the cost recovery plots in layout with widgets.

Creates the cost recovery timeseries plot and bar plot for monthly charges, plus the associated widgets used to control the data displayed in the plots.

Returns:

Type Description
Row

A Row object (the Row containing a Column of widgets and a Column of plots).

Source code in main/plots.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def create_cost_recovery_layout() -> Row:
    """Create the cost recovery plots in layout with widgets.

    Creates the cost recovery timeseries plot and bar plot for monthly charges, plus the
    associated widgets used to control the data displayed in the plots.

    Returns:
        A Row object (the Row containing a Column of widgets and a Column of plots).
    """
    dates = get_month_dates_for_previous_years()

    # Get start and end date as datetimes for capacity timeseries
    min_date = datetime.combine(dates[0][0], time.min)
    max_date = datetime.combine(dates[-1][1], time.min)
    start = datetime.combine(dates[-12][0], time.min)

    # Get x-axis values for bar plot
    chart_months = [f"{date[0].strftime('%b')} {date[0].year}" for date in dates]

    # Plots are initialised with data for last 3 years but only the last year is shown
    # by default
    timeseries_plot, bar_plot = create_cost_recovery_plots(
        dates=dates,
        start_date=min_date,
        end_date=max_date,
        x_range=(start, max_date),
        chart_months=chart_months,
    )

    # Create button to set plots to default year
    last_year_button = Button(
        label="Last year",
    )
    widgets.add_callback_to_button(
        button=last_year_button,
        dates=(start, max_date),
        plot=timeseries_plot,
        include_future_dates=False,
    )
    widgets.add_bar_callback_to_button(
        button=last_year_button,
        dates=get_calendar_year_dates(),
        plot=bar_plot,
        chart_months=chart_months,
    )

    # Create button to set plots to calendar year
    calendar_button = Button(
        label="Current calendar year",
    )
    widgets.add_callback_to_button(
        button=calendar_button,
        dates=get_calendar_year_dates(),
        plot=timeseries_plot,
        include_future_dates=False,
    )
    widgets.add_bar_callback_to_button(
        button=calendar_button,
        dates=get_calendar_year_dates(),
        plot=bar_plot,
        chart_months=chart_months,
    )

    # Create button to set plots to financial year
    financial_button = Button(
        label="Current financial year",
    )
    widgets.add_callback_to_button(
        button=financial_button,
        dates=get_financial_year_dates(),
        plot=timeseries_plot,
        include_future_dates=False,
    )
    widgets.add_bar_callback_to_button(
        button=financial_button,
        dates=get_financial_year_dates(),
        plot=bar_plot,
        chart_months=chart_months,
    )

    # Create layout to display widgets aligned as a column next to the plot
    plot_layout = row(
        column(last_year_button, calendar_button, financial_button),
        column(
            timeseries_plot,
            bar_plot,
            sizing_mode="stretch_width",
        ),
        sizing_mode="stretch_width",
    )
    return plot_layout

create_cost_recovery_plots(dates, start_date, end_date, x_range, chart_months) ¤

Creates the cost recovery plot for the last year.

Provides an overview of team capacity over the past year and the project charging.

Parameters:

Name Type Description Default
dates list[tuple[date, date]]

list of tuples (from oldest to most recent) containing dates for all months of the last 3 years; each tuple contains two dates for the first and last date of the month

required
start_date datetime

datetime object representing the start of the timeseries plotting period

required
end_date datetime

datetime object representing the end of the timeseries plotting period

required
x_range tuple[datetime, datetime]

(optional) tuple of datetimes to use as the x_range for the displayed plot

required
chart_months list[str]

list of months for x-axis in bar chart

required

Returns:

Type Description
tuple[figure, figure]

Tuple of Bokeh figures containing cost recovery data timeseries data and monthly charges for the past year.

Source code in main/plots.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
def create_cost_recovery_plots(
    dates: list[tuple[date, date]],
    start_date: datetime,
    end_date: datetime,
    x_range: tuple[datetime, datetime],
    chart_months: list[str],
) -> tuple[figure, figure]:
    """Creates the cost recovery plot for the last year.

    Provides an overview of team capacity over the past year and the project charging.

    Args:
        dates: list of tuples (from oldest to most recent) containing dates for all
            months of the last 3 years; each tuple contains two dates for the first
            and last date of the month
        start_date: datetime object representing the start of the timeseries plotting
            period
        end_date: datetime object representing the end of the timeseries plotting
            period
        x_range: (optional) tuple of datetimes to use as the x_range for the displayed
            plot
        chart_months: list of months for x-axis in bar chart

    Returns:
        Tuple of Bokeh figures containing cost recovery data timeseries data and
            monthly charges for the past year.
    """
    # Create timeseries plot
    cost_recovery_timeseries, monthly_totals = timeseries.get_cost_recovery_timeseries(
        dates
    )
    capacities = timeseries.get_capacity_timeseries(
        start_date=start_date, end_date=end_date
    )
    capacity_timeseries = capacities.sum(axis=1)

    internal_effort_timeseries = timeseries.get_internal_effort_timeseries(
        start_date=start_date, end_date=end_date
    )

    number_team_members = timeseries.get_team_members_timeseries(
        start_date=start_date, end_date=end_date
    )

    internal_project_effort = internal_effort_timeseries / number_team_members

    # charged project effort using cost recovery timeseries divided by team members
    charged_project_effort = cost_recovery_timeseries / number_team_members

    # total project effort for all projects
    total_project_effort = charged_project_effort + internal_project_effort

    # in %
    avg_project_capacity_pct = capacity_timeseries / number_team_members * 100

    total_capacity_used_pct = total_project_effort * 100

    charged_capacity_used_pct = charged_project_effort * 100

    traces = [
        {
            "timeseries": avg_project_capacity_pct,
            "colour": "gold",
            "label": "Average capacity for project work %",
        },
        {
            "timeseries": total_capacity_used_pct,
            "colour": "navy",
            "label": "Fraction of capacity used for all projects %",
        },
        {
            "timeseries": charged_capacity_used_pct,
            "colour": "green",
            "label": "Fraction of capacity used for charged projects %",
        },
    ]
    timeseries_plot = create_timeseries_plot(
        title=("Team capacity and project charging over time"),
        traces=traces,
        x_range=x_range,
    )

    # Create bar plot for monthly charges
    bar_plot = create_bar_plot(
        title=("Total monthly charges"),
        months=chart_months,
        values=monthly_totals,
        x_range=(chart_months[-12:]),
    )
    return timeseries_plot, bar_plot

create_pie_chart(title, data, tooltip_fmt='@value') ¤

Create a pie chart.

Parameters:

Name Type Description Default
title str

The title to display above the pie chart.

required
data Mapping[str, int | float]

The data being displayed.

required
tooltip_fmt str

The format string for the tooltip.

'@value'

Returns:

Type Description
figure

The Bokeh figure for the pie chart.

Source code in main/plots.py
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
def create_pie_chart(
    title: str, data: Mapping[str, int | float], tooltip_fmt: str = "@value"
) -> figure:
    """Create a pie chart.

    Args:
        title: The title to display above the pie chart.
        data: The data being displayed.
        tooltip_fmt: The format string for the tooltip.

    Returns:
        The Bokeh figure for the pie chart.
    """
    # Manually select the palette colours, needed if less than 3 projects
    palette = [c for c in Category20c[max(len(data), 3)]][: len(data)]

    category_name = title.replace(" ", "_")
    source = (
        pd.Series(data)
        .reset_index(name="value")
        .rename(columns={"index": category_name})
    )
    source = source.sort_values(by=category_name)
    source["angle"] = source["value"] / source["value"].sum() * 2 * pi
    source["colour"] = palette

    plot = figure(
        title=title,
        toolbar_location=None,
        x_range=(-0.5, 1.0),  # type: ignore[arg-type]
        sizing_mode="stretch_width",
    )

    plot.wedge(
        x=0,
        y=1,
        start_angle=cumsum("angle", include_zero=True),
        end_angle=cumsum("angle"),
        radius=0.4,
        line_color="white",
        fill_color="colour",
        legend_field=category_name,
        source=source,
    )

    plot.add_tools(HoverTool(tooltips=f"@{category_name}: {tooltip_fmt}"))

    plot.axis.axis_label = None
    plot.axis.visible = False
    plot.grid.grid_line_color = None

    return plot

create_project_evolution_layout(project) ¤

Add the evolution plot to a layout.

Parameters:

Name Type Description Default
project Project

Project object the layout is about.

required

Returns:

Type Description
Row | None

The layout with the plot.

Source code in main/plots.py
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
def create_project_evolution_layout(project: models.Project) -> Row | None:
    """Add the evolution plot to a layout.

    Args:
        project: Project object the layout is about.

    Returns:
        The layout with the plot.
    """
    evolution_plot = create_project_evolution_plot(project)
    allocation_plot = create_allocation_plot_for_project(
        project, evolution_plot.x_range if evolution_plot else None
    )

    plots = []
    if evolution_plot:
        plots.append(evolution_plot)
    if allocation_plot:
        plots.append(allocation_plot)
    if not plots:
        return None

    if len(plots) == 2:
        assert evolution_plot is not None
        evolution_plot.xaxis.axis_label = None
        evolution_plot.xaxis.major_label_text_font_size = "0pt"  # Hide tick labels
        evolution_plot.xaxis.major_tick_line_color = None  # Hide tick marks
        evolution_plot.xaxis.minor_tick_line_color = None  # Hide minor ticks

    plot_layout = row(
        column(*plots, sizing_mode="stretch_width"), sizing_mode="stretch_width"
    )
    return plot_layout

create_project_evolution_plot(project) ¤

Create plot with the time evolution of usage and charges.

Source code in main/plots.py
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
def create_project_evolution_plot(project: models.Project) -> figure | None:
    """Create plot with the time evolution of usage and charges."""
    # Expected, commulative use, homogeneous over each phase
    traces = []
    if not (expected := _expected_days_used(project)).empty:
        traces.append(
            {
                "timeseries": expected,
                "label": "Expected trend",
                "colour": "red",
            },
        )

    # Actual usage, based on time records, if any
    if not (actual := _actual_days_used(project)).empty:
        traces.append({"timeseries": actual, "label": "Actual usage", "colour": "blue"})

    # Charges made, for those projects with charges
    if not (charges := _actual_days_charged(project)).empty:
        traces.append(
            {"timeseries": charges, "label": "Charged days", "colour": "green"}
        )

    if not traces:
        return None

    plot = create_timeseries_plot(
        "Project evolution",
        traces,
        height=350,
        legend_loc="bottom_right",
    )
    plot.yaxis.axis_label = "Days"

    for phase in project.phases.all():
        plot.add_layout(get_time_vertical_line(pd.to_datetime(phase.start_date)))
    assert project.end_date
    plot.add_layout(get_time_vertical_line(pd.to_datetime(project.end_date)))
    plot.add_layout(get_time_vertical_line(datetime.now(), colour="grey"))

    return plot

create_timeseries_plot(title, traces, x_range=None, vareas=None, height=500, legend_loc='bottom_left') ¤

Creates a generic timeseries plot.

Parameters:

Name Type Description Default
title str

plot title

required
traces list[dict[str, Any]]

a list of dictionaries with keys for the 'timeseries' data, 'label' and 'colour'

required
x_range tuple[datetime, datetime] | None

(optional) tuple of datetimes to use as the x_range for the displayed plot

None
vareas tuple[tuple[tuple[str, str], str], ...] | None

(optional) tuple of tuples, containing a tuple of trace labels to apply shading between and the colour to use, e.g. ((("Capacity", "Project effort"), "Green"), ...)

None
height int

Height of the plot in pixels. Defaults to 500.

500
legend_loc str

(optional) Location of the legend within the plot. Check Bokeh docs for valid options. Defaults to 'bottom_left'

'bottom_left'

Returns:

Type Description
figure

Bokeh figure containing timeseries data.

Source code in main/plots.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def create_timeseries_plot(  # type: ignore[explicit-any]
    title: str,
    traces: list[dict[str, Any]],
    x_range: tuple[datetime, datetime] | None = None,
    vareas: tuple[tuple[tuple[str, str], str], ...] | None = None,
    height: int = 500,
    legend_loc: str = "bottom_left",
) -> figure:
    """Creates a generic timeseries plot.

    Args:
        title: plot title
        traces: a list of dictionaries with keys for the 'timeseries' data, 'label' and
            'colour'
        x_range: (optional) tuple of datetimes to use as the x_range for the displayed
            plot
        vareas: (optional) tuple of tuples, containing a tuple of trace labels to apply
            shading between and the colour to use, e.g.
            ((("Capacity", "Project effort"), "Green"), ...)
        height: Height of the plot in pixels. Defaults to 500.
        legend_loc: (optional) Location of the legend within the plot. Check Bokeh docs
            for valid options. Defaults to 'bottom_left'

    Returns:
        Bokeh figure containing timeseries data.
    """
    # Create ColumnDataSource from trace data
    df = pd.DataFrame({trace["label"]: trace["timeseries"] for trace in traces})
    df.index.name = "index"
    df.reset_index(inplace=True)
    df["index"] = pd.to_datetime(df["index"]).dt.date
    source = ColumnDataSource(df)

    plot = figure(
        title=title,
        height=height,
        background_fill_color="#efefef",
        x_axis_type="datetime",
        tools="save,xpan,xwheel_zoom,reset",
        sizing_mode="stretch_width",
    )
    if x_range:
        plot.x_range = Range1d(x_range[0], x_range[1])  # type: ignore[arg-type]

    plot.yaxis.axis_label = "Value"
    plot.xaxis.axis_label = "Date"

    # Now we add the data
    lines = []
    tooltips = [
        ("Date", "@{index}{%F}"),
    ]
    hover_renderer = []
    for trace in traces:
        label = trace["label"]

        # If there's no label, that's the mark of a ghost trace used for area filling
        # and hover tooltips only. Should not appear in the legend
        if not label:
            hover_renderer = [plot.line("index", label, source=source, alpha=0)]
            continue

        # The other traces are plotted and included in the legend
        lines.append(
            plot.line(
                "index",
                label,
                source=source,
                line_width=2,
                color=trace["colour"],
                legend_label=label,
            )
        )
        tooltips.append((label, f"@{{{label}}}{{0.00}}"))

    # If provided, add varea shading between traces
    if vareas:
        for labels, colour in vareas:
            add_varea_glyph(plot, df, labels[0], labels[1], colour)

    # The tooltip appears in the hover rendered ghost trace, if any, or the first trace
    # otherwise
    hover = HoverTool(
        tooltips=tooltips,
        formatters={"@{index}": "datetime"},
        renderers=hover_renderer or lines[:1],  # type: ignore[arg-type]
        mode="vline",
    )

    plot.add_tools(hover)
    plot.legend.click_policy = "hide"  # hides traces when clicked in legend
    plot.legend.location = legend_loc  # type: ignore[assignment]

    return plot

get_time_vertical_line(location, colour='black') ¤

Create a vertical line to indicate the specified time on the plots.

Parameters:

Name Type Description Default
location datetime

The timestamp to position the vertical line.

required
colour str

Colour for the lne. Defaults to black.

'black'

Returns:

Type Description
Span

A Span object representing the vertical line for the specified time.

Source code in main/plots.py
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
def get_time_vertical_line(location: datetime, colour: str = "black") -> Span:
    """Create a vertical line to indicate the specified time on the plots.

    Args:
        location: The timestamp to position the vertical line.
        colour: Colour for the lne. Defaults to black.

    Returns:
        A Span object representing the vertical line for the specified time.
    """
    now_line = Span(
        location=location,
        dimension="height",
        line_color=colour,
        line_dash="dashed",
        line_width=1,
    )
    return now_line

html_components_from_plot(plot, prefix=None) ¤

Generate HTML components from a Bokeh plot that can be added to the context.

Parameters:

Name Type Description Default
plot figure | Row

Bokeh figure to be added to the context

required
prefix str | None

optional prefix to use in the context keys

None
Source code in main/plots.py
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
def html_components_from_plot(
    plot: figure | Row, prefix: str | None = None
) -> dict[str, str]:
    """Generate HTML components from a Bokeh plot that can be added to the context.

    Args:
        plot: Bokeh figure to be added to the context
        prefix: optional prefix to use in the context keys
    """
    script, div = components(plot)
    if prefix:
        return {
            f"{prefix}_script": script,
            f"{prefix}_div": div,
        }

    return {
        "script": script,
        "div": div,
    }