MovingBubbles

D3Blocks.movingbubbles(df, datetime: str = 'datetime', sample_id: str = 'sample_id', state: str = 'state', center: str = None, size=5, color=None, opacity=0.6, stroke='#000000', shape: str = None, tooltip: str = None, label: str = None, cmap: str = 'Set1', color_method: str = 'auto', dt_format: str = '%d-%m-%Y %H:%M:%S', damper: float = 1, collision: float = 0.15, fontsize: int = 14, timedelta: str = 'minutes', standardize: str = 'samplewise', timelines: str = None, speed: dict = {'fast': 25, 'medium': 250, 'slow': 750, 'superfast': 5}, figsize=[1024, 768], note: str = None, time_notes: str = None, show_side_panel: bool = True, show_top_panel: bool = True, dark_mode: bool = True, color_background=None, node_text_inside: bool = True, title: str = 'Movingbubbles - D3Blocks', filepath: str = 'movingbubbles.html', showfig: bool = True, overwrite: bool = True, notebook: bool = False, save_button: bool = True, return_html: bool = False, reset_properties: bool = True)

Movingbubbles block.

The MovingBubbles provides insights into when one action follows the other across time. It can help to understand the movements of entities, and whether clusters occur at specific time points and state(s). It may not be the most visually efficient method, but it is one of the more visually satisfying ones with force-directed and colliding nodes. The function d3.import_example(‘random_time’) is created to generate a randomized dataset with various states. The input dataset should contain 3 columns;

  • DateTime column: Describes the data-time when an event occurs.

  • State column: Describes what the particular state was at that point of time of the specific sample_id.

  • Sample_id column: A sample can have multiple states at various time points but can not have two states at exactly the same point in time.

Parameters:
  • df (Input data, pd.DataFrame()) – Input data.

  • datetime (str, (default: 'datetime')) – Name of the column with the datetime.

  • sample_id (str, (default: 'sample_id')) – Name of the column with the sample ids.

  • state (str, (default: 'state')) – Name of the column with the states.

  • center (String, (default: None)) – Center this category.

  • size (int, list/array/Series, or dictionary. (default: 5)) –

    Size the nodes.
    • 5: set all nodes to this size.

    • ’weight’: name of a column in df with the (numeric) sizes. Same as passing df['weight'].

    • [4, 10, 5, …]: array-like of the same length as df, aligned positionally with its rows (same convention as d3.scatter’s size).

    • {‘0’: 4, ‘1’: 10, ‘2’: 5, ..}: dict keyed by sample_id value.

  • color (str, list/array/Series, or dictionary. (default: None)) –

    Color the nodes.
    • ’#000FFF’: set all nodes to this color.

    • ’age’: name of a column in df. Same as passing df['age']: hex colors are used as is, other values are mapped to colors using cmap.

    • [‘#808080’, ‘#FFF000’, …]: array-like hex colors of the same length as df, aligned positionally with its rows.

    • [‘Netherlands’, ‘Germany’, …]: array-like category labels of the same length as df; labels are mapped to colors using cmap.

    • {‘0’: ‘#808080’, ‘1’: ‘#FFF000’, ‘3’: ‘#000000’, ..}: dict keyed by sample_id value with hex colors.

    • {‘0’: ‘NL’, ‘1’: ‘DE’, ..}: dict keyed by sample_id value with category labels; labels are mapped to colors using cmap.

    • None: Colors are based on sample_id using cmap.

  • opacity (float, list/array/Series, or dictionary, (default: 0.6)) –

    Opacity of the bubbles [0-1].
    • 0.6: set all nodes to this opacity.

    • ’opacity’: name of a column in df with the (numeric) opacities. Same as passing df['opacity'].

    • [0.4, 0.9, …]: array-like of the same length as df, aligned positionally with its rows.

    • {‘0’: 0.4, ‘1’: 0.9, ..}: dict keyed by sample_id value.

  • stroke (str, list/array/Series, or dictionary, (default: '#000000')) –

    Stroke color of the bubbles.
    • ’#000000’: set all nodes to this stroke color.

    • ’country’: name of a column in df. Hex colors are used as is, other values (labels) are mapped to colors using cmap.

    • [‘#000000’, ‘#ffffff’, …]: array-like of the same length as df, aligned positionally with its rows.

    • {‘0’: ‘#000000’, ‘1’: ‘#ffffff’, ..}: dict keyed by sample_id value.

  • color_method (str) –

    Coloring mode of the nodes.
    • ’auto’ (default): if color is provided, use node colors (‘node’); otherwise use state colors (‘state’).

    • ’state’: Use the colors defined per state (d3.node_properties), so bubble colors change with activity/state.

    • ’node’: Use the colors defined on nodes (from color / d3.edge_properties), so each sample keeps its assigned color.

  • dt_format (str) –

    Date time format.
    • ’%d-%m-%Y %H:%M:%S’.

  • damper (float, (default: 1)) –

    Movement of samples. A smaller number is slower/smoother movement.
    • 0.1: min

    • 10: max

    Sets the initial value of the “Damper” slider in the Physics panel.

  • collision (float, (default: 0.15)) –

    Strength of the push-apart between overlapping bubbles [0-1].
    • 0: no collision (bubbles may overlap freely; cheapest for large datasets).

    • 0.15: default. Calm, settles quickly also with hundreds of bubbles.

    • 0.5 and higher: bubbles are pushed apart strongly; dense clusters can start to pulse.

    Sets the initial value of the “Collision strength” slider in the Physics panel.

  • fontsize (int, (default: 14)) – Fontsize of the states.

  • timedelta (String, (default: 'minutes')) –

    The time delta between states. Change accordingly.
    • ’seconds’

    • ’minutes’

    • ’days’

  • standardize (str. (default: None)) –

    Method to standardize the data.
    • None: standardize over the entire timeframe. Sample_ids are dependent to each other.

    • ’samplewise’: Standardize per sample_id by substracting the minimum time per sample_id.

    • ’relative’: Standardize across the entire dataframe after sorting on time. Each action is relative to the previous one in time without considering sample_id.

    • ’minimum’: Movements are relative to the minimum time in the dataset.

  • timelines (str, (default: None)) – Optional column name (e.g. ‘age’, ‘country’) that defines separate timelines. None (default) = one shared timeline over the full dataframe. When set, the chosen standardize method is applied independently inside each group of that column, so a joint multi-group dataframe behaves like running the same method on each group subset separately. The column must exist in df; otherwise an error is raised. Use this to avoid the “averaging out” effect of a shared global timeline across groups.

  • speed (dict, (default: {"slow": 1000, "medium": 200, "fast": 50, "superfast": 20})) – Reference delays (ms) for the playback speed continuum. Lower values move time faster. Keys map to slider regions; slow is the slowest non-stopped delay and superfast is the fastest (right end of the slider).

  • note (str, (default: None)) –

    A specific note, such as project description can be put on the html page.
    • None: Default text will be provided about the simulation, and states.

  • time_notes (dict, (default: None)) –

    The time notes will be shown between specific time points.

    Example:

    time_notes = [{"start_minute": 1,
                   "stop_minute": 5,
                   "note": "Enter your note here and it is shown between 1 min and 5 min."}]
    time_notes.append({"start_minute": 6, "stop_minute": 10, "note": "Enter your second note here and it is shown between 6 min and 10 min."})
    

  • show_side_panel (bool, (default: True)) – True: Show left side panels (Export / Save, Layout, Physics, Variables, Filtering). False: Hide left side panels.

  • show_top_panel (bool, (default: True)) – True: Show the top bar (logo, time scrubber, play/pause, theme). False: Hide the top bar.

  • dark_mode (bool, (default: True)) – True: Start in dark theme. False: Start in light theme.

  • color_background (list of str, str, or None, (default: None)) – Backgrounds for center / top / side panels as [dark_hex, light_hex]. Named themes: 'streamlit', 'darkblue'. None → ['#222222', '#ffffff'].

  • node_text_inside (bool, (default: True)) – True: Per-bubble labels (Layout -> Label) are centered inside the node, with the text color automatically switched between black/white for contrast against the node’s fill color. False: Labels are placed above the node, matching the theme’s text color (this was the only behavior previously).

  • shape (str, (default: None)) – Name of a categorical column in df that is mapped to bubble shapes (circle, square, triangle, diamond). Sets the initial value of Layout -> Shape in the left side panel. Default (None): all bubbles are circles. Use e.g. 'country' for one shape per unique value in the country column.

  • tooltip (str, (default: None)) – Name of a column in df (or the state column) of which the value is shown when hovering a bubble. Sets the initial value of Layout -> Tooltip in the left side panel. Default (None): no tooltip.

  • label (str, (default: None)) – Name of a column in df (or the state column) that is written on each bubble. Sets the initial value of Layout -> Label in the left side panel. Default (None): no label.

  • cmap (String, (default: 'Set1')) –

    All colors can be reversed with ‘_r’, e.g. ‘binary’ to ‘binary_r’
    • ’tab20c’, ‘Set1’, ‘Set2’

    • ’rainbow’, ‘bwr’, ‘binary’, ‘seismic’

    • ’Blues’, ‘Reds’, ‘Pastel1’, ‘Paired’

    • ’twilight’, ‘hsv’, ‘inferno’

  • title (String, (default: None)) –

    Title of the figure.
    • ’Movingbubbles’

  • filepath (String, (Default: user temp directory)) –

    File path to save the output.
    • Temporarily path: ‘d3blocks.html’

    • Relative path: ‘./d3blocks.html’

    • Absolute path: ‘c://temp//d3blocks.html’

    • None: Return HTML

  • figsize (tuple) –

    Size of the figure in the browser, [width, height].
    • [780, 800]

  • showfig (bool, (default: True)) –

    • True: Open browser-window.

    • False: Do not open browser-window.

  • overwrite (bool, (default: True)) –

    • True: Overwrite the html in the destination directory.

    • False: Do not overwrite destination file but show warning instead.

  • notebook (bool) –

    • True: Use IPython to show chart in notebook.

    • False: Do not use IPython.

  • save_button (bool, (default: True)) –

    • True: Save button is shown in the HTML to save the image in svg.

    • False: No save button is shown in the HTML.

  • return_html (bool, (default: False)) –

    • True: Return html

    • False: Nothing is returned

  • reset_properties (bool, (default: True)) –

    • True: Reset the node_properties at each run.

    • False: Use the d3.node_properties()

Returns:

  • d3.node_properties (DataFrame of dictionary) – Contains properties of the unique input label/nodes/samples.

  • d3.edge_properties (DataFrame of dictionary) – Contains properties of the unique input edges/links.

  • d3.config (dictionary) – Contains configuration properties.

Examples

>>> # Load d3blocks
>>> from d3blocks import D3Blocks
>>> #
>>> # Initialize
>>> d3 = D3Blocks()
>>> #
>>> # Load example data
>>> df = d3.import_example('random_time', n=10000, c=300, date_start="1-1-2000 00:10:05", date_stop="1-1-2000 23:59:59")
>>> #
>>> # Plot
>>> d3.movingbubbles(df, speed={"slow": 1000, "medium": 200, "fast": 50, "superfast": 20}, filepath='movingbubbles.html')
>>> #

Examples

>>> # Load d3blocks
>>> from d3blocks import D3Blocks
>>> #
>>> # Initialize
>>> d3 = D3Blocks(chart='movingbubbles', frame=False)
>>> #
>>> # Import example
>>> df = d3.import_example('random_time', n=1000, c=100, date_start="1-1-2000 00:10:05", date_stop="1-1-2000 23:59:59")
>>> #
>>> # Coloring the states.
>>> d3.set_node_properties(df['state'])
>>> print(d3.node_properties)
>>> # Color the sleeping state black
>>> d3.node_properties.get('Sleeping')['color']='#000000'
>>> #
>>> d3.set_edge_properties(df)
>>> print(d3.edge_properties)
>>> #
>>> # Show
>>> d3.show(title='Movingbubbles with adjusted configurations')

Examples

>>> # Load d3blocks
>>> import random
>>> from d3blocks import D3Blocks
>>> #
>>> # Initialize
>>> d3 = D3Blocks(chart='movingbubbles')
>>> #
>>> # Import example
>>> df = d3.import_example('random_time', n=10000, c=300, date_start="1-1-2000 00:10:05", date_stop="1-1-2000 23:59:59")
>>> #
>>> # Specify the colors and node sizes for the specific sample_id or for demonstration, generated randomly
>>> # size = {1: 15, 3: 30, 5: 25}
>>> size = {i: random.randint(2, 15) for i in range(1, 100)}
>>> color = {1: '#FF0000', 3: '#000FFF'}
>>> #
>>> # Show
>>> d3.movingbubbles(df, color=color, size=size)

References

Input Data (MovingBubbles)

The input data is a dataframe that should contain the columns datatime, sample_id and state. If the column names are different, then the column name can be specified.

#                 datetime sample_id     state
# 0    2000-01-01 00:10:32        30      Sick
# 1    2000-01-01 00:10:36        23      Work
# 2    2000-01-01 00:11:16       179  Sleeping
# 3    2000-01-01 00:11:28       122     Sport
# 4    2000-01-01 00:13:02       226  Sleeping
#                  ...       ...       ...
# 9994 2000-01-01 23:59:56       300  Sleeping
# 9995 2000-01-01 23:59:57       217      Home
# 9996 2000-01-01 23:59:57        89  Sleeping
# 9997 2000-01-01 23:59:58        42  Sleeping
# 9998 2000-01-01 23:59:58       237      Work

# [9999 rows x 3 columns]

Chart (MovingBubbles)

Daily life of European