Source code for lecilab_behavior_analysis.plots.occupancy

"""Plots of when the box was used, and transitions between events."""

import matplotlib.colors as mcolors
import networkx as nx
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator

from lecilab_behavior_analysis.style import cmap, color, title


[docs] def plot_percentage_of_occupancy_per_day(daily_percentages: pd.Series, ax: plt.Axes = None) -> plt.Axes: if ax is None: ax = plt.gca() # Plot the percentage of time for each day daily_percentages.plot(kind="line", ax=ax) ax.set_xlabel("Date") ax.set_ylabel("Percentage of time (%)") title(ax, "Percentage of time that task is running per day") ax.tick_params(axis="x", rotation=45) ax.set_ylim(0, 100) ax.grid(True) return ax
[docs] def plot_training_times_heatmap(heatmap_vector: np.ndarray, ax: plt.Axes = None) -> plt.Axes: if ax is None: ax = plt.gca() # Plot the heatmap vector sns.heatmap( heatmap_vector.reshape(1, -1), cmap=cmap("intensity"), cbar=True, xticklabels=60, vmin=0, vmax=np.max(heatmap_vector), ax=ax, ) ax.set_xlabel("Hour of the Day") ax.set_ylabel("Event Occurrences") title(ax, "Training times") # Set the x-ticks to show every hour ax.set_xticks(np.arange(0, 1440, 60)) ax.set_xticklabels([f"{i // 60:02d}:00" for i in range(0, 1440, 60)], rotation=45) ax.set_yticks([]) ax.set_ylabel("") ax.grid(False) plt.tight_layout() return ax
[docs] def plot_training_times_clock_heatmap(heatmap_vector: np.ndarray, ax: plt.Axes = None, **kwargs) -> plt.Axes: """ When the box is used through the day, as a clock (midnight on top): the bar of each minute is the fraction of days the box was in use then (from metrics.occupancy.get_occupancy_heatmap). The radius is the square root of that fraction, so that the area of the bars is proportional to the time (with a linear radius, a peak twice as high looks four times as big); the scale shows the fraction as a percentage of days. The night (20:00 to 8:00) is shaded. Args: heatmap_vector: 1440 values, one per minute of the day. ax: a polar axes (default: a new figure). ylim: (kwarg) the range of the fraction of days, e.g. (0, 1) to compare plots. """ if ax is None: _, ax = plt.subplots(figsize=(3, 3), subplot_kw={"projection": "polar"}) theta = np.linspace(0, 2 * np.pi, 1440) # 1440 minutes in a day values = np.clip(np.asarray(heatmap_vector, dtype=float), 0, None) top = values.max() if values.max() > 0 else 1 if "ylim" in kwargs: top = kwargs["ylim"][1] ax.bar( theta, np.sqrt(values), width=2 * np.pi / 1440, color=plt.get_cmap(cmap("intensity"))(values / top), edgecolor="none", ) ax.set_ylim(0, np.sqrt(top) * 1.05) # the night, from 20:00 to 8:00, shaded behind the bars max_radius = ax.get_ylim()[1] ax.fill_between( theta, 0, max_radius, where=(theta >= 20 * np.pi / 12) | (theta <= 8 * np.pi / 12), color="lightgray", alpha=0.5, zorder=0, ) try: ax.set_theta_zero_location("N") # midnight at the top ax.set_theta_direction(-1) # clockwise except AttributeError: print("initialize your figure with subplot_kw={'projection': 'polar'} to make it circular") ax.set_xticks(np.linspace(0, 2 * np.pi, 12, endpoint=False)) ax.set_xticklabels([f"{i}:00" for i in range(0, 24, 2)]) # the scale, in % of days, at the square root of each value ticks = [t for t in MaxNLocator(nbins=3, steps=[1, 2, 2.5, 5, 10]).tick_values(0, top) if 0 < t <= top] ax.set_yticks(np.sqrt(ticks)) ax.set_yticklabels([f"{t * 100:.0f}%" if t * 100 >= 1 else f"{t * 100:.1g}%" for t in ticks], fontsize="x-small") ax.set_rlabel_position(135) ax.yaxis.grid(True, color=color("reference"), linewidth=0.5, alpha=0.5) title(ax, "Training Times (% of days)", pad=25) return ax
[docs] def plot_transition_matrix(transition_matrix: pd.DataFrame, figsize: tuple = (5, 5)) -> plt.Figure: # plot the heatmap of the transition matrix with clustering # if ax is None: # ax = plt.gca() # sns.heatmap(transition_matrix, annot=True, fmt='d', cmap='YlGnBu') fig = sns.clustermap( transition_matrix, annot=True, fmt="d", cmap=cmap("intensity"), cbar=True, xticklabels=transition_matrix.columns, yticklabels=transition_matrix.index, figsize=figsize, dendrogram_ratio=(0.2, 0.2), cbar_kws={"shrink": 0.8}, ) # get the axis of the clustermap ax = fig.ax_heatmap # set the title and labels title(ax, "Transition Matrix Heatmap", fontsize=16) ax.set_xlabel("To Item") ax.set_ylabel("From Item") return fig
[docs] def plot_transition_network_with_curved_edges( transition_matrix: pd.DataFrame, threshold: int = 0, figsize: tuple = (10, 10), ax: plt.Axes = None, node_colors: dict = None, colorbar_label: str = "Transition Frequency", ) -> plt.Figure: """ The transitions as a network: an arrow from each row to each column, wider and darker the more transitions (e.g. from metrics.occupancy.get_followers_matrix: which subject used the box after which). Transitions of an item to itself are not drawn. Args: transition_matrix: counts, the same items in rows (from) and columns (to). threshold: leave out the arrows with less than this percentage of all the transitions. figsize: of the new figure, if ax is None. ax: draw here (default: a new figure). node_colors: {item: colour} (default: one colour for all). colorbar_label: the label of the colour scale of the arrows. Returns: The figure. """ values = transition_matrix.to_numpy(copy=True) np.fill_diagonal(values, 0) matrix = pd.DataFrame(values, index=transition_matrix.index, columns=transition_matrix.columns) G = nx.from_pandas_adjacency(matrix, create_using=nx.DiGraph) G.add_nodes_from(matrix.index) pos = nx.circular_layout(G) if len(G) <= 12 else nx.spring_layout(G, seed=42) # in a panel of a bigger figure, smaller nodes and labels small = ax is not None if ax is None: _, ax = plt.subplots(figsize=figsize) # Calculate total edge weight and filter edges above the threshold total_weight = sum(G[u][v]["weight"] for u, v in G.edges()) min_weight = threshold * total_weight / 100 # Calculate the minimum weight based on % threshold filtered_edges = [(u, v) for u, v in G.edges() if G[u][v]["weight"] >= min_weight and G[u][v]["weight"] > 0] edge_weights = [G[u][v]["weight"] for u, v in filtered_edges] max_weight = max(edge_weights, default=1) # Prevent division by zero if no edges remain base_width = 1 if small else 2 edge_widths = [base_width + (4 * G[u][v]["weight"] / max_weight) for u, v in filtered_edges] edge_alphas = [0.3 + (0.7 * G[u][v]["weight"] / max_weight) for u, v in filtered_edges] # Apply a colormap to the edges based on normalized weights norm = mcolors.Normalize(vmin=0, vmax=max_weight) edge_colors = [plt.get_cmap(cmap("intensity"))(norm(G[u][v]["weight"])) for u, v in filtered_edges] node_size = 500 if small else 1000 nodes = list(G.nodes()) colors = [node_colors.get(n, "lightblue") for n in nodes] if node_colors else "lightblue" nx.draw_networkx_nodes(G, pos, nodelist=nodes, node_size=node_size, node_color=colors, alpha=1.0, ax=ax) # Draw curved edges (both ways between two items: one on each side), ending at the nodes for i, (u, v) in enumerate(filtered_edges): nx.draw_networkx_edges( G, pos, edgelist=[(u, v)], width=edge_widths[i], alpha=edge_alphas[i], edge_color=[edge_colors[i]], connectionstyle="arc3,rad=0.2" if G.has_edge(v, u) else "arc3,rad=0", arrows=True, arrowsize=10 if small else 15, arrowstyle="-|>", node_size=node_size, ax=ax, ) # the names outside the nodes, away from the centre label_pos = {node: xy * 1.3 for node, xy in pos.items()} nx.draw_networkx_labels(G, label_pos, font_size=8 if small else 10, ax=ax) ax.set_axis_off() ax.margins(0.2) sm = plt.cm.ScalarMappable(cmap=cmap("intensity"), norm=norm) sm.set_array([]) cbar = ax.figure.colorbar(sm, ax=ax, orientation="vertical", fraction=0.046, pad=0.04) cbar.set_label(colorbar_label) if threshold: title(ax, f"Transition Network (Edges above {threshold}% of total weight)") return ax.figure