From 59ef9e8412d5dc414994654b036304c917edc01a Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:39:03 +0530 Subject: [PATCH 01/34] new: Add `bokeh-0.py` - `line-plot` --- marimo/_snippets/data/bokeh-0.py | 62 ++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-0.py diff --git a/marimo/_snippets/data/bokeh-0.py b/marimo/_snippets/data/bokeh-0.py new file mode 100644 index 00000000000..174541936ec --- /dev/null +++ b/marimo/_snippets/data/bokeh-0.py @@ -0,0 +1,62 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Bokeh: Interactive Line Plot + + Create an interactive line plot with pan, zoom, and hover tools. + Common usage: `figure(tools='pan,box_zoom,reset,save')`. + Commonly used in: time series analysis, trend visualization. + """ + ) + return + + +@app.cell +def _(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource + import numpy as np + + # Generate sample data + x = np.linspace(0, 10, 100) + y = np.sin(x) + np.random.normal(0, 0.1, 100) + + # Create data source + source = ColumnDataSource(data=dict(x=x, y=y)) + + # Create figure with tools + p = figure( + height=400, + width=700, + tools='pan,box_zoom,wheel_zoom,reset,save,hover', + title='Interactive Line Plot' + ) + + # Add line with hover tooltips + p.line('x', 'y', line_width=2, source=source) + p.hover.tooltips = [ + ('x', '@x{0.00}'), + ('y', '@y{0.00}') + ] + + p + return ColumnDataSource, figure, np, p, source, x, y + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From 23cafedea66cf5786bca36f291bdaebd4f309527 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:39:54 +0530 Subject: [PATCH 02/34] new: Add `bokeh-1.py` - `scatter-plot` --- marimo/_snippets/data/bokeh-1.py | 87 ++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-1.py diff --git a/marimo/_snippets/data/bokeh-1.py b/marimo/_snippets/data/bokeh-1.py new file mode 100644 index 00000000000..66e7dd0ff00 --- /dev/null +++ b/marimo/_snippets/data/bokeh-1.py @@ -0,0 +1,87 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Bokeh: Interactive Scatter Plot + + Create a scatter plot with interactive tools and color mapping. + Common usage: `figure(tools='box_select,lasso_select,reset')`. + Commonly used in: data exploration, cluster analysis, outlier detection. + """ + ) + return + + +@app.cell +def __(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource, ColorBar + from bokeh.transform import linear_cmap + import numpy as np + + # Generate sample clustered data + np.random.seed(42) + N = 500 + x = np.random.normal(size=N) + y = np.random.normal(size=N) + color_value = np.random.uniform(size=N) # Value for color mapping + + # Create data source + source = ColumnDataSource(data=dict( + x=x, + y=y, + color=color_value, + )) + + # Create figure with selection tools + p = figure( + height=400, + width=700, + tools='box_select,lasso_select,wheel_zoom,pan,reset,save', + title='Interactive Scatter Plot' + ) + + # Add points with color mapping + mapper = linear_cmap('color', 'Viridis256', 0, 1) + scatter = p.scatter('x', 'y', + size=8, + source=source, + fill_color=mapper, + line_color='white', + alpha=0.6, + selection_color='red', + nonselection_alpha=0.1) + + # Add colorbar + color_bar = ColorBar(color_mapper=mapper['transform'], + width=8, + location=(0,0)) + p.add_layout(color_bar, 'right') + + # Add hover tooltips + p.hover.tooltips = [ + ('x', '@x{0.00}'), + ('y', '@y{0.00}'), + ('value', '@color{0.00}') + ] + + p + return (ColorBar, ColumnDataSource, color_bar, color_value, figure, linear_cmap, + mapper, np, p, scatter, source, x, y) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From dddda2412889376f3e61659a2ae15e72ba6b7433 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:40:46 +0530 Subject: [PATCH 03/34] new: Add `bokeh-2.py` - `layout` --- marimo/_snippets/data/bokeh-2.py | 111 +++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-2.py diff --git a/marimo/_snippets/data/bokeh-2.py b/marimo/_snippets/data/bokeh-2.py new file mode 100644 index 00000000000..d416598aab5 --- /dev/null +++ b/marimo/_snippets/data/bokeh-2.py @@ -0,0 +1,111 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Bokeh: Linked Brushing and Selection + + Create linked plots with synchronized selection. + Common usage: `layout([p1, p2])` with shared `ColumnDataSource`. + Commonly used in: exploratory data analysis, correlation analysis, outlier detection. + """ + ) + return + + +@app.cell +def __(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource + from bokeh.layouts import row + import numpy as np + + # Generate sample data + np.random.seed(42) + N = 1000 + x = np.random.normal(0, 1, N) + y = x * 0.5 + np.random.normal(0, 0.5, N) # Positive correlation with x + z = x * -0.2 + np.random.normal(0, 0.2, N) # Negative correlation with x + + # Create data source + source = ColumnDataSource(data=dict(x=x, y=y, z=z)) + + # Common figure properties + plot_config = dict( + height=400, + width=400, + tools='box_select,lasso_select,wheel_zoom,pan,reset,hover', + background_fill_color='#f5f5f5' + ) + + # Create first plot + p1 = figure( + title='Y vs X (Positive Correlation)', + **plot_config + ) + p1.circle('x', 'y', + source=source, + size=8, + fill_color='navy', + fill_alpha=0.5, + line_color='white', + selection_color='red', + nonselection_alpha=0.1) + + # Create second plot + p2 = figure( + title='Z vs X (Negative Correlation)', + **plot_config + ) + p2.circle('x', 'z', + source=source, + size=8, + fill_color='navy', + fill_alpha=0.5, + line_color='white', + selection_color='red', + nonselection_alpha=0.1) + + # Add hover tooltips + tooltip_config = [ + ('x', '@x{0.00}'), + ('y', '@y{0.00}'), + ('z', '@z{0.00}') + ] + p1.hover.tooltips = tooltip_config + p2.hover.tooltips = tooltip_config + + # Add grid styling + for p in [p1, p2]: + p.grid.grid_line_color = 'white' + p.grid.grid_line_width = 2 + p.axis.axis_label_text_font_size = '12pt' + p.axis.axis_label_text_font_style = 'bold' + + # Add axis labels + p1.xaxis.axis_label = 'X Value' + p1.yaxis.axis_label = 'Y Value' + p2.xaxis.axis_label = 'X Value' + p2.yaxis.axis_label = 'Z Value' + + # Layout plots side by side + layout = row(p1, p2) + + layout + return (ColumnDataSource, figure, layout, np, p1, p2, row, source, x, y, z) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From a71f75e47b4693919f2cba9a6236872fa1903786 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:41:54 +0530 Subject: [PATCH 04/34] new: Add `bokeh-3.py` - `RT-DS` --- marimo/_snippets/data/bokeh-3.py | 105 +++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-3.py diff --git a/marimo/_snippets/data/bokeh-3.py b/marimo/_snippets/data/bokeh-3.py new file mode 100644 index 00000000000..6de5e6cbb5a --- /dev/null +++ b/marimo/_snippets/data/bokeh-3.py @@ -0,0 +1,105 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Bokeh: Real-time Data Streaming + + Create a real-time streaming visualization with rolling window. + Common usage: `ColumnDataSource` with periodic updates. + Commonly used in: system monitoring, IoT dashboards, live analytics. + """ + ) + return + + +@app.cell +def __(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource, DatetimeTickFormatter + import numpy as np + from datetime import datetime, timedelta + import pandas as pd + + # Initialize data with rolling window + window_size = 100 + now = datetime.now() + times = [(now + timedelta(seconds=i)) for i in range(-window_size, 0)] + + # Simulate metric data (e.g., system metrics) + values = np.random.normal(100, 10, window_size) + values_smooth = pd.Series(values).rolling(window=5).mean() + + # Create data source + source = ColumnDataSource(data=dict( + time=times, + value=values, + value_smooth=values_smooth + )) + + # Create figure + p = figure( + height=400, + width=800, + title='Real-time Metric Monitoring', + x_axis_type='datetime', + tools='pan,box_zoom,wheel_zoom,reset,save' + ) + + # Add raw data line + p.line('time', 'value', + line_color='lightgray', + line_alpha=0.5, + line_width=1, + legend_label='Raw Data', + source=source) + + # Add smoothed line + p.line('time', 'value_smooth', + line_color='navy', + line_width=2, + legend_label='Smoothed (5-point MA)', + source=source) + + # Style the plot + p.grid.grid_line_alpha = 0.3 + p.xaxis.formatter = DatetimeTickFormatter( + seconds="%Y-%m-%d %H:%M:%S", + minsec="%Y-%m-%d %H:%M:%S", + minutes="%Y-%m-%d %H:%M:%S", + hourmin="%Y-%m-%d %H:%M" + ) + p.xaxis.axis_label = 'Time' + p.yaxis.axis_label = 'Value' + + # Add hover tool + p.hover.tooltips = [ + ('Time', '@time{%Y-%m-%d %H:%M:%S}'), + ('Value', '@value{0.00}'), + ('Smoothed', '@value_smooth{0.00}') + ] + p.hover.formatters = {'@time': 'datetime'} + + # Configure legend + p.legend.location = 'top_left' + p.legend.click_policy = 'hide' + + p + return (ColumnDataSource, DatetimeTickFormatter, datetime, figure, now, np, p, + pd, source, timedelta, times, values, values_smooth, window_size) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 7cba5e2028eb7d7cb802354c92d657fad786fc68 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:42:15 +0530 Subject: [PATCH 05/34] new: Add `bokeh-4.py` - `dashboard` --- marimo/_snippets/data/bokeh-4.py | 117 +++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-4.py diff --git a/marimo/_snippets/data/bokeh-4.py b/marimo/_snippets/data/bokeh-4.py new file mode 100644 index 00000000000..5e358c7c6fe --- /dev/null +++ b/marimo/_snippets/data/bokeh-4.py @@ -0,0 +1,117 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Bokeh: Interactive Dashboard Layout + + Create a multi-panel dashboard with different visualization types. + Common usage: `column(row(p1, p2), p3)` for complex layouts. + Commonly used in: business analytics, KPI monitoring, data reporting. + """ + ) + return + + +@app.cell +def __(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource + from bokeh.layouts import column, row + import numpy as np + import pandas as pd + + # Generate sample data + np.random.seed(42) + dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') + + data = pd.DataFrame({ + 'date': dates, + 'metric1': np.random.normal(100, 15, len(dates)).cumsum(), + 'metric2': np.random.normal(50, 10, len(dates)).cumsum(), + 'category': np.random.choice(['A', 'B', 'C'], len(dates)), + 'value': np.random.uniform(20, 80, len(dates)) + }) + + # Create data sources + ts_source = ColumnDataSource(data) + cat_source = data.groupby('category')['value'].mean().reset_index() + cat_source = ColumnDataSource(cat_source) + + # Time series plot + p1 = figure( + height=300, + width=800, + title='Metrics Over Time', + x_axis_type='datetime', + tools='pan,box_zoom,wheel_zoom,reset' + ) + + p1.line('date', 'metric1', line_color='navy', legend_label='Metric 1', + source=ts_source) + p1.line('date', 'metric2', line_color='crimson', legend_label='Metric 2', + source=ts_source) + p1.legend.click_policy = 'hide' + + # Bar chart + p2 = figure( + height=300, + width=400, + title='Average by Category', + x_range=list(data.category.unique()), + tools='pan,box_zoom,wheel_zoom,reset' + ) + + p2.vbar(x='category', top='value', width=0.8, source=cat_source, + fill_color='navy', line_color=None) + + # Distribution plot + hist, edges = np.histogram(data.value, bins=20) + hist_data = pd.DataFrame({ + 'count': hist, + 'left': edges[:-1], + 'right': edges[1:] + }) + hist_source = ColumnDataSource(hist_data) + + p3 = figure( + height=300, + width=400, + title='Value Distribution', + tools='pan,box_zoom,wheel_zoom,reset' + ) + + p3.quad(top='count', bottom=0, left='left', right='right', + source=hist_source, fill_color='navy', line_color='white') + + # Style all plots + for p in [p1, p2, p3]: + p.grid.grid_line_alpha = 0.3 + p.axis.axis_label_text_font_size = '12pt' + + # Create layout + layout = column( + p1, + row(p2, p3) + ) + + layout + return (ColumnDataSource, cat_source, column, data, dates, edges, figure, + hist, hist_data, hist_source, layout, np, p1, p2, p3, pd, row, + ts_source) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 8cd45f88a44ada771e84382483b7d2a7084b6c06 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:43:27 +0530 Subject: [PATCH 06/34] new: Add `bokeh-5.py` - `stats-viz` --- marimo/_snippets/data/bokeh-5.py | 130 +++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-5.py diff --git a/marimo/_snippets/data/bokeh-5.py b/marimo/_snippets/data/bokeh-5.py new file mode 100644 index 00000000000..45feab4d2d7 --- /dev/null +++ b/marimo/_snippets/data/bokeh-5.py @@ -0,0 +1,130 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Bokeh: Statistical Visualization + + Create box plots and violin plots for statistical analysis. + Common usage: Box plots for distribution comparison across categories. + Commonly used in: research analysis, quality control, performance comparison. + """ + ) + return + + +@app.cell +def __(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource, FactorRange + from bokeh.transform import factor_cmap + import numpy as np + import pandas as pd + + # Generate sample data for different groups + np.random.seed(42) + groups = ['Group A', 'Group B', 'Group C', 'Group D'] + data = [] + + for group in groups: + if group == 'Group A': + values = np.random.normal(100, 15, 100) + elif group == 'Group B': + values = np.random.normal(85, 10, 100) + elif group == 'Group C': + values = np.random.normal(110, 20, 100) + else: + values = np.random.normal(95, 12, 100) + + # Calculate statistics + q1 = np.percentile(values, 25) + q2 = np.percentile(values, 50) + q3 = np.percentile(values, 75) + iqr = q3 - q1 + upper = min(q3 + 1.5*iqr, np.max(values)) + lower = max(q1 - 1.5*iqr, np.min(values)) + + # Store outliers + outliers = values[(values < lower) | (values > upper)] + + data.append({ + 'group': group, + 'lower': lower, + 'q1': q1, + 'q2': q2, + 'q3': q3, + 'upper': upper, + 'outliers': list(outliers) + }) + + df = pd.DataFrame(data) + source = ColumnDataSource(df) + + # Create figure + p = figure( + height=400, + width=600, + title='Distribution Comparison Across Groups', + x_range=groups, + tools='pan,box_zoom,wheel_zoom,reset,save,hover' + ) + + # Add box glyphs + p.vbar(x='group', top='q3', bottom='q1', width=0.7, + fill_color=factor_cmap('group', 'Blues4', groups), + line_color='black', source=source, + legend_field='group') + + # Add whiskers + p.segment(x0='group', y0='upper', x1='group', y1='q3', + line_color='black', source=source) + p.segment(x0='group', y0='lower', x1='group', y1='q1', + line_color='black', source=source) + + # Add outlier points + for i, group in enumerate(groups): + outliers = df.iloc[i]['outliers'] + if len(outliers) > 0: + p.circle([group]*len(outliers), outliers, + size=6, fill_alpha=0.6, + line_color='black', fill_color='red') + + # Style the plot + p.xgrid.grid_line_color = None + p.ygrid.grid_line_alpha = 0.1 + p.xaxis.axis_label = 'Groups' + p.yaxis.axis_label = 'Values' + + # Configure hover tooltips + p.hover.tooltips = [ + ('Group', '@group'), + ('Median', '@q2{0.0}'), + ('Q1', '@q1{0.0}'), + ('Q3', '@q3{0.0}'), + ('Upper', '@upper{0.0}'), + ('Lower', '@lower{0.0}') + ] + + # Configure legend + p.legend.click_policy = 'hide' + p.legend.location = 'top_right' + + p + return (ColumnDataSource, FactorRange, data, df, factor_cmap, figure, group, + groups, np, p, pd, source, values) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 6be1dea12ea1d5c07055b8e92d85445882803dd6 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:44:06 +0530 Subject: [PATCH 07/34] new: Add `bokeh-6.py` - `TS` --- marimo/_snippets/data/bokeh-6.py | 121 +++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-6.py diff --git a/marimo/_snippets/data/bokeh-6.py b/marimo/_snippets/data/bokeh-6.py new file mode 100644 index 00000000000..07f05c29467 --- /dev/null +++ b/marimo/_snippets/data/bokeh-6.py @@ -0,0 +1,121 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Bokeh: Time Series with Range Tool + + Create a time series plot with range selection tool. + Common usage: Financial analysis, trend analysis with zoom capability. + Commonly used in: stock analysis, sensor data analysis, trend investigation. + """ + ) + return + + +@app.cell +def __(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource, RangeTool + import numpy as np + import pandas as pd + + # Generate sample time series data + np.random.seed(42) + dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') + + # Simulate stock price with trend and volatility + base = 100 + trend = np.linspace(0, 20, len(dates)) + volatility = np.random.normal(0, 1, len(dates)).cumsum() + price = base + trend + volatility + volume = np.random.uniform(50000, 200000, len(dates)) + + # Create DataFrame + df = pd.DataFrame({ + 'date': dates, + 'price': price, + 'volume': volume, + 'ma20': pd.Series(price).rolling(window=20).mean(), + 'ma50': pd.Series(price).rolling(window=50).mean() + }) + + source = ColumnDataSource(df) + + # Create main figure + p = figure( + height=400, + width=800, + title='Interactive Time Series Analysis', + x_axis_type='datetime', + tools='pan,wheel_zoom,box_zoom,reset,save' + ) + + # Add price and moving averages + p.line('date', 'price', line_color='gray', line_alpha=0.6, + legend_label='Price', source=source) + p.line('date', 'ma20', line_color='blue', line_width=2, + legend_label='20-day MA', source=source) + p.line('date', 'ma50', line_color='red', line_width=2, + legend_label='50-day MA', source=source) + + # Create range tool figure + select = figure( + height=150, + width=800, + y_axis_type=None, + x_axis_type='datetime', + tools='', + toolbar_location=None + ) + + range_tool = RangeTool(x_range=p.x_range) + range_tool.overlay.fill_color = 'navy' + range_tool.overlay.fill_alpha = 0.2 + + select.line('date', 'price', source=source) + select.ygrid.grid_line_color = None + select.add_tools(range_tool) + + # Style the plots + p.grid.grid_line_alpha = 0.3 + p.xaxis.axis_label = 'Date' + p.yaxis.axis_label = 'Price' + + # Add hover tooltips + p.hover.tooltips = [ + ('Date', '@date{%F}'), + ('Price', '@price{0.00}'), + ('MA20', '@ma20{0.00}'), + ('MA50', '@ma50{0.00}'), + ('Volume', '@volume{0,0}') + ] + p.hover.formatters = {'@date': 'datetime'} + + # Configure legend + p.legend.location = 'top_left' + p.legend.click_policy = 'hide' + + from bokeh.layouts import column + layout = column(p, select) + + layout + return (ColumnDataSource, RangeTool, base, column, dates, df, figure, layout, + np, p, pd, price, range_tool, select, source, trend, volatility, + volume) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 5de0e3ff459c37915cd244ff0f9c0b6d2d59367e Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:44:38 +0530 Subject: [PATCH 08/34] new: Add `bokeh-7.py` - `categorical data` --- marimo/_snippets/data/bokeh-7.py | 93 ++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-7.py diff --git a/marimo/_snippets/data/bokeh-7.py b/marimo/_snippets/data/bokeh-7.py new file mode 100644 index 00000000000..7084768ea64 --- /dev/null +++ b/marimo/_snippets/data/bokeh-7.py @@ -0,0 +1,93 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Bokeh: Categorical Data Analysis + + Create interactive bar charts and heatmaps for categorical data. + Common usage: Comparing metrics across categories and subcategories. + """ + ) + return + + +@app.cell +def __(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource, FactorRange + from bokeh.transform import factor_cmap + import numpy as np + import pandas as pd + + # Sample data + categories = ['A', 'B', 'C'] + regions = ['North', 'South', 'East'] + + data = [] + np.random.seed(42) + + for cat in categories: + for region in regions: + data.append({ + 'category': cat, + 'region': region, + 'sales': np.random.randint(50, 150) + }) + + df = pd.DataFrame(data) + factors = [(cat, region) for cat in categories for region in regions] + + # Create bar chart + p = figure( + height=400, + width=600, + title='Sales by Category and Region', + x_range=FactorRange(*factors), + tools='pan,box_zoom,reset,hover' + ) + + # Add bars + p.vbar( + x='category_region', + top='sales', + width=0.9, + source=ColumnDataSource(df.assign( + category_region=list(zip(df.category, df.region)) + )), + fill_color=factor_cmap( + 'category_region', + ['#1f77b4', '#ff7f0e', '#2ca02c']*3, + factors + ) + ) + + # Style + p.xgrid.grid_line_color = None + p.xaxis.major_label_orientation = 0.7 + + # Tooltips + p.hover.tooltips = [ + ('Category', '@category'), + ('Region', '@region'), + ('Sales', '@sales') + ] + + p + return ColumnDataSource, FactorRange, df, factor_cmap, factors, figure, p + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 785e19cbddc029cb8e61d404281057830b1c1d3d Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:45:38 +0530 Subject: [PATCH 09/34] new: Add `bokeh-8.py` - `heatmap` --- marimo/_snippets/data/bokeh-8.py | 131 +++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-8.py diff --git a/marimo/_snippets/data/bokeh-8.py b/marimo/_snippets/data/bokeh-8.py new file mode 100644 index 00000000000..34fe861bf7b --- /dev/null +++ b/marimo/_snippets/data/bokeh-8.py @@ -0,0 +1,131 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Bokeh: Interactive Heatmap with Clustering + + Create a heatmap with hierarchical clustering for correlation analysis. + Common usage: Feature correlation analysis, pattern detection. + Commonly used in: data science, bioinformatics, financial analysis. + """ + ) + return + + +@app.cell +def __(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource, LinearColorMapper, ColorBar + from bokeh.transform import transform + import numpy as np + import pandas as pd + from scipy.cluster import hierarchy + from scipy.spatial.distance import pdist + + # Generate correlated data + np.random.seed(42) + n_features = 10 + n_samples = 1000 + + # Create feature names + features = [f'Feature_{i+1}' for i in range(n_features)] + + # Generate data with some correlations + data = np.random.randn(n_samples, n_features) + data[:, 1] = data[:, 0] + np.random.randn(n_samples) * 0.3 + data[:, 4] = data[:, 3] - np.random.randn(n_samples) * 0.2 + + df = pd.DataFrame(data, columns=features) + + # Compute correlation matrix + corr = df.corr() + + # Perform hierarchical clustering + linkage = hierarchy.linkage(pdist(corr), method='ward') + order = hierarchy.leaves_list(linkage) + + # Reorder correlation matrix + corr = corr.iloc[order, order] + + # Prepare data for heatmap + source = ColumnDataSource(data=dict( + x=[(i+0.5) for i in range(n_features) for _ in range(n_features)], + y=[(i+0.5) for _ in range(n_features) for i in range(n_features)], + correlation=corr.values.flatten(), + xname=[corr.index[i] for i in range(n_features) for _ in range(n_features)], + yname=[corr.columns[i] for _ in range(n_features) for i in range(n_features)] + )) + + # Create color mapper + mapper = LinearColorMapper( + palette='RdBu11', + low=-1, + high=1 + ) + + # Create figure + p = figure( + width=600, + height=600, + title='Feature Correlation Heatmap', + x_range=list(corr.index), + y_range=list(reversed(corr.columns)), + tools='pan,box_zoom,wheel_zoom,reset,save,hover', + x_axis_location='above' + ) + + # Add heatmap rectangles + p.rect( + x='x', + y='y', + width=1, + height=1, + source=source, + fill_color=transform('correlation', mapper), + line_color=None + ) + + # Add color bar + color_bar = ColorBar( + color_mapper=mapper, + location=(0, 0), + title='Correlation', + orientation='horizontal' + ) + + p.add_layout(color_bar, 'below') + + # Style the plot + p.grid.grid_line_color = None + p.axis.axis_line_color = None + p.axis.major_tick_line_color = None + p.xaxis.major_label_orientation = 0.7 + p.yaxis.major_label_orientation = 0 + + # Add hover tooltips + p.hover.tooltips = [ + ('Features', '@xname vs @yname'), + ('Correlation', '@correlation{0.00}') + ] + + p + return (ColorBar, ColumnDataSource, LinearColorMapper, corr, data, df, + features, figure, hierarchy, linkage, mapper, n_features, n_samples, + np, order, p, pd, pdist, source, transform) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 08bb7d30ea47b4be3a1147a1574f692015000a86 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:47:17 +0530 Subject: [PATCH 10/34] new: Add `bokeh-9.py` - `networkx x bokeh` --- marimo/_snippets/data/bokeh-9.py | 120 +++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 marimo/_snippets/data/bokeh-9.py diff --git a/marimo/_snippets/data/bokeh-9.py b/marimo/_snippets/data/bokeh-9.py new file mode 100644 index 00000000000..a4206aa07e7 --- /dev/null +++ b/marimo/_snippets/data/bokeh-9.py @@ -0,0 +1,120 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Bokeh: Network Graph Visualization + + Create interactive network graphs with hover information. + Common usage: Relationship analysis, dependency graphs, social networks. + """ + ) + return + + +@app.cell +def _(): + from bokeh.plotting import figure + from bokeh.models import ColumnDataSource, NodesAndLinkedEdges + from bokeh.layouts import column + import networkx as nx + import numpy as np + + # Create sample network + G = nx.random_geometric_graph(20, 0.3, seed=42) + + # Get node positions + pos = nx.spring_layout(G, seed=42) + + # Prepare node data + node_x = [pos[node][0] for node in G.nodes()] + node_y = [pos[node][1] for node in G.nodes()] + node_size = [3 + 2*len(list(G.neighbors(node))) for node in G.nodes()] + + # Prepare edge data + edge_x = [] + edge_y = [] + for edge in G.edges(): + x0, y0 = pos[edge[0]] + x1, y1 = pos[edge[1]] + edge_x.extend([x0, x1, None]) + edge_y.extend([y0, y1, None]) + + # Create figure + p = figure( + width=500, + height=500, + title='Network Graph', + tools='pan,wheel_zoom,box_zoom,reset,hover', + active_scroll='wheel_zoom' + ) + + # Add edges + p.line(edge_x, edge_y, line_color='gray', line_alpha=0.5) + + # Add nodes + node_source = ColumnDataSource({ + 'x': node_x, + 'y': node_y, + 'size': node_size, + 'connections': [len(list(G.neighbors(node))) for node in G.nodes()] + }) + + p.scatter('x', 'y', + size='size', + source=node_source, + fill_color='navy', + fill_alpha=0.6, + hover_fill_color='red', + line_color='white') + + # Add hover tooltips + p.hover.tooltips = [ + ('Node ID', '$index'), + ('Connections', '@connections') + ] + + # Style + p.grid.visible = False + p.axis.visible = False + + p + return ( + ColumnDataSource, + G, + NodesAndLinkedEdges, + column, + edge, + edge_x, + edge_y, + figure, + node_size, + node_source, + node_x, + node_y, + np, + nx, + p, + pos, + x0, + x1, + y0, + y1, + ) + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From 38afa56e52b6974cbbd098facb322f754bf29407 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:47:49 +0530 Subject: [PATCH 11/34] new: Add `holoviews-0.py` - `hist + scatter` --- marimo/_snippets/data/holoviews-0.py | 80 ++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-0.py diff --git a/marimo/_snippets/data/holoviews-0.py b/marimo/_snippets/data/holoviews-0.py new file mode 100644 index 00000000000..3ac82e71f99 --- /dev/null +++ b/marimo/_snippets/data/holoviews-0.py @@ -0,0 +1,80 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Interactive Data Exploration + + Create interactive visualizations with linked views. + Common usage: Exploratory data analysis with linked selections. + Commonly used in: Data science workflows, interactive dashboards. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + + # Enable Bokeh backend + hv.extension('bokeh') + + # Generate sample data + np.random.seed(42) + n_points = 1000 + + df = pd.DataFrame({ + 'x': np.random.normal(0, 1, n_points), + 'y': np.random.normal(0, 1, n_points), + 'category': np.random.choice(['A', 'B', 'C'], n_points), + 'value': np.random.uniform(0, 100, n_points) + }) + + # Create scatter plot with hover + scatter = hv.Points(df, kdims=['x', 'y'], vdims=['category', 'value']) + scatter.opts( + tools=['hover', 'box_select'], + size=8, + color='category', + cmap='Category10', + width=400, + height=400, + title='Interactive Scatter Plot' + ) + + # Create linked histogram + hist = hv.operation.histogram(scatter, dimension='value', normed=False) + hist.opts( + tools=['hover'], + width=400, + height=200, + title='Value Distribution' + ) + + # Layout plots + layout = (scatter + hist).cols(1) + layout.opts( + title='Data Exploration Dashboard' + ) + + layout + return df, hist, hv, layout, n_points, np, pd, scatter + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 0ff35bec43c264c98859721469d4e8dd47128cb6 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:50:11 +0530 Subject: [PATCH 12/34] new: Add `holoviews-1.py` - `TS analysis` --- marimo/_snippets/data/holoviews-1.py | 104 +++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-1.py diff --git a/marimo/_snippets/data/holoviews-1.py b/marimo/_snippets/data/holoviews-1.py new file mode 100644 index 00000000000..df9f369b30f --- /dev/null +++ b/marimo/_snippets/data/holoviews-1.py @@ -0,0 +1,104 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Time Series Analysis + + Create interactive time series visualizations with linked views. + Common usage: Financial analysis, sensor data monitoring. + Commonly used in: Trading analysis, IoT monitoring, performance tracking. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + + # Enable Bokeh backend + hv.extension('bokeh') + + # Generate sample time series data + np.random.seed(42) + dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') + n_points = len(dates) + + # Create multiple metrics (e.g., stock data) + df = pd.DataFrame({ + 'date': dates, + 'price': 100 + np.random.randn(n_points).cumsum(), + 'volume': np.random.randint(1000, 5000, n_points), + 'volatility': np.abs(np.random.randn(n_points)) + }) + + # Calculate moving averages + df['MA20'] = df['price'].rolling(window=20).mean() + df['MA50'] = df['price'].rolling(window=50).mean() + + # Create main price plot + price_plot = hv.Curve(df, 'date', 'price', label='Price') + ma20_plot = hv.Curve(df, 'date', 'MA20', label='20-day MA') + ma50_plot = hv.Curve(df, 'date', 'MA50', label='50-day MA') + + # Combine price plots + price_overlay = (price_plot * ma20_plot * ma50_plot).opts( + width=800, + height=300, + tools=['hover', 'box_zoom', 'wheel_zoom', 'pan', 'reset'], + title='Price and Moving Averages', + legend_position='top_left', + show_grid=True + ) + + # Create volume bars + volume_plot = hv.Bars(df, 'date', 'volume').opts( + width=800, + height=150, + tools=['hover'], + title='Trading Volume', + color='navy', + alpha=0.5 + ) + + # Create volatility heatmap + volatility_plot = hv.HeatMap( + df.assign(month=df.date.dt.month, + day=df.date.dt.day)[['month', 'day', 'volatility']] + ).opts( + width=400, + height=300, + tools=['hover'], + title='Volatility Heatmap', + colorbar=True, + cmap='RdYlBu_r' + ) + + # Layout all plots + layout = (price_overlay + volume_plot + volatility_plot).cols(1) + layout.opts( + title='Interactive Time Series Analysis' + ) + + layout + return (df, dates, hv, layout, ma20_plot, ma50_plot, n_points, np, pd, + price_overlay, price_plot, volume_plot, volatility_plot) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From cfbf036da99d85d9e82e1e1d4573c599f5b39a1e Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:51:32 +0530 Subject: [PATCH 13/34] new: Add `holoviews-2.py` - `overlapping analysis` --- marimo/_snippets/data/holoviews-2.py | 78 ++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-2.py diff --git a/marimo/_snippets/data/holoviews-2.py b/marimo/_snippets/data/holoviews-2.py new file mode 100644 index 00000000000..faaa1d56d01 --- /dev/null +++ b/marimo/_snippets/data/holoviews-2.py @@ -0,0 +1,78 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Dynamic Selection Analysis + + Create interactive plots with dynamic statistics. + Common usage: Real-time analysis of selected data points. + Commonly used in: Exploratory data analysis, outlier detection. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + from holoviews import streams + + hv.extension('bokeh') + + # Generate sample data + np.random.seed(42) + points = hv.Points(np.random.multivariate_normal( + (0, 0), [[1, 0.1], [0.1, 1]], (1000,) + )) + + # Create selection stream + selection = streams.Selection1D(source=points) + + # Dynamic computation of statistics for selected points + def selected_info(index): + selected = points.iloc[index] + if index: + mean_vals = selected.array().mean(axis=0) + label = f'Selection Mean: ({mean_vals[0]:.2f}, {mean_vals[1]:.2f})' + return selected.relabel(label).opts( + color='red', + size=8, + alpha=0.6 + ) + return hv.Points([]).relabel('No Selection') + + # Create dynamic map for selection + dmap = hv.DynamicMap(selected_info, streams=[selection]) + + # Combine original points with selection + plot = (points * dmap).opts( + hv.opts.Points( + tools=['box_select', 'lasso_select'], + size=4, + alpha=0.6, + width=500, + height=400, + title='Interactive Point Selection' + ) + ) + + plot + return dmap, plot, points, selection + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 244dd8ab7c3521a54c8c83bc264ade012f91e97c Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:51:53 +0530 Subject: [PATCH 14/34] new: Add `holoviews-3.py` - `geodata` --- marimo/_snippets/data/holoviews-3.py | 83 ++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-3.py diff --git a/marimo/_snippets/data/holoviews-3.py b/marimo/_snippets/data/holoviews-3.py new file mode 100644 index 00000000000..9048ccefcfd --- /dev/null +++ b/marimo/_snippets/data/holoviews-3.py @@ -0,0 +1,83 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Geographic Data Visualization + + Create interactive maps with dynamic overlays. + Common usage: Geospatial analysis, location-based analytics. + Commonly used in: GIS analysis, location intelligence. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + + hv.extension('bokeh') + + # Generate sample location data + np.random.seed(42) + n_points = 100 + + # Sample data for US locations + data = pd.DataFrame({ + 'latitude': np.random.uniform(25, 48, n_points), + 'longitude': np.random.uniform(-125, -70, n_points), + 'value': np.random.normal(100, 15, n_points), + 'category': np.random.choice(['A', 'B', 'C'], n_points) + }) + + # Create tile source and points + tiles = hv.element.tiles.OSM() + points = hv.Points( + data, + ['longitude', 'latitude'], + ['value', 'category'] + ) + + # Create map view with options + map_view = (tiles * points).options( + width=700, + height=500, + title='Geographic Distribution' + ) + + # Style the points with tooltips + points.options( + color='value', + cmap='viridis', + size=8, + tools=['hover', 'box_select'], + colorbar=True, + alpha=0.6, + hover_tooltips=[ + ('Category', '@category'), + ('Value', '@value{0.00}'), + ('Location', '(@longitude, @latitude)') + ] + ) + + map_view + return data, hv, map_view, n_points, np, pd, points, tiles + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From be5d00792fe649bfbff4541398af859ccb99656d Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:52:12 +0530 Subject: [PATCH 15/34] new: Add `holoviews-4.py` - `linked` --- marimo/_snippets/data/holoviews-4.py | 101 +++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-4.py diff --git a/marimo/_snippets/data/holoviews-4.py b/marimo/_snippets/data/holoviews-4.py new file mode 100644 index 00000000000..4b41af8e7bc --- /dev/null +++ b/marimo/_snippets/data/holoviews-4.py @@ -0,0 +1,101 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Linked Selection Analysis + + Create linked views with dynamic statistics. + Common usage: Multi-dimensional data exploration. + Commonly used in: Feature analysis, correlation studies. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + from holoviews import streams + + hv.extension('bokeh') + + # Generate sample data + np.random.seed(42) + n_points = 1000 + + # Create correlated features + x = np.random.normal(0, 1, n_points) + y = x * 0.5 + np.random.normal(0, 0.5, n_points) + z = x * -0.2 + y * 0.3 + np.random.normal(0, 0.3, n_points) + + data = pd.DataFrame({ + 'x': x, + 'y': y, + 'z': z + }) + + # Create scatter plot with selection stream + scatter = hv.Points(data, ['x', 'y']) + selection = streams.Selection1D(source=scatter) + + # Create initial histogram + hist = hv.Histogram(np.histogram(data['z'], bins=20)) + + # Dynamic histogram of selected points + def selected_hist(index): + if len(index): + selected = data.iloc[index]['z'] + return hv.Histogram(np.histogram(selected, bins=20)).options( + fill_color='navy' + ) + return hist.options(fill_color='gray') + + dmap = hv.DynamicMap(selected_hist, streams=[selection]) + + # Layout with styling + layout = (scatter + dmap).cols(2) + + # Style scatter plot + scatter.options( + tools=['box_select', 'lasso_select', 'hover'], + width=400, + height=400, + color='navy', + alpha=0.6, + title='Select Points', + hover_tooltips=[ + ('x', '@x{0.2f}'), + ('y', '@y{0.2f}') + ] + ) + + # Style histogram + dmap.options( + width=400, + height=400, + title='Distribution (Selected vs All)', + xlabel='z value', + ylabel='Count' + ) + + layout + return data, dmap, hist, hv, layout, n_points, np, pd, scatter, selection, streams + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 490d29a864334be3cc3e8a449129988adeb2b926 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:52:28 +0530 Subject: [PATCH 16/34] new: Add `holoviews-5.py` - `TS` --- marimo/_snippets/data/holoviews-5.py | 89 ++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-5.py diff --git a/marimo/_snippets/data/holoviews-5.py b/marimo/_snippets/data/holoviews-5.py new file mode 100644 index 00000000000..b1a501146fa --- /dev/null +++ b/marimo/_snippets/data/holoviews-5.py @@ -0,0 +1,89 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Time Series Analysis + + Create interactive time series with dynamic updates. + Common usage: Real-time monitoring, financial analysis. + Commonly used in: Trading systems, IoT monitoring, performance tracking. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + from datetime import datetime, timedelta + + hv.extension('bokeh') + + # Generate time series data + np.random.seed(42) + now = datetime.now() + dates = [now - timedelta(minutes=i) for i in range(100, 0, -1)] + + # Simulate multiple metrics (e.g., system metrics) + data = pd.DataFrame({ + 'time': dates, + 'value1': np.random.normal(100, 10, 100).cumsum(), + 'value2': np.random.normal(50, 5, 100).cumsum(), + 'anomaly': np.random.choice([0, 1], 100, p=[0.95, 0.05]) + }) + + # Create main time series plot + curve1 = hv.Curve( + data, kdims=['time'], vdims=['value1'], + label='Metric 1' + ) + curve2 = hv.Curve( + data, kdims=['time'], vdims=['value2'], + label='Metric 2' + ) + + # Add anomaly points + anomalies = data[data['anomaly'] == 1] + points = hv.Points( + anomalies, kdims=['time', 'value1'], + label='Anomalies' + ) + + # Style the plots + curve1 = curve1.options(color='navy', line_width=2) + curve2 = curve2.options(color='green', line_width=2) + points = points.options(color='red', size=10) + + # Combine plots with styling + plot = (curve1 * curve2 * points).options( + width=800, + height=400, + title='Real-time Metrics with Anomaly Detection', + tools=['hover', 'box_zoom', 'wheel_zoom', 'reset'], + legend_position='top_right', + xlabel='Time', + ylabel='Value' + ) + + plot + return (anomalies, curve1, curve2, data, dates, datetime, hv, now, np, pd, + plot, points, timedelta) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() \ No newline at end of file From a4e495eb0338c19a7f997ab4a0cd7e1cd720543b Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:52:44 +0530 Subject: [PATCH 17/34] new: Add `holoviews-6.py` - `stat` --- marimo/_snippets/data/holoviews-6.py | 96 ++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-6.py diff --git a/marimo/_snippets/data/holoviews-6.py b/marimo/_snippets/data/holoviews-6.py new file mode 100644 index 00000000000..db9ac34aeb6 --- /dev/null +++ b/marimo/_snippets/data/holoviews-6.py @@ -0,0 +1,96 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Statistical Analysis with Faceting + + Create comparative statistical visualizations. + Common usage: A/B testing, multi-group analysis. + Commonly used in: Research analysis, experiment evaluation. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + + hv.extension('bokeh') + + # Generate experimental data + np.random.seed(42) + n_samples = 200 + + # Simulate A/B test results across different segments + segments = ['Segment A', 'Segment B', 'Segment C'] + variants = ['Control', 'Treatment'] + + data = [] + for segment in segments: + # Control group + control_mean = np.random.uniform(20, 30) + control_data = np.random.normal(control_mean, 5, n_samples) + + # Treatment group (with effect) + effect = np.random.uniform(2, 5) + treatment_data = np.random.normal(control_mean + effect, 5, n_samples) + + data.extend([ + {'segment': segment, 'variant': 'Control', 'value': v} + for v in control_data + ]) + data.extend([ + {'segment': segment, 'variant': 'Treatment', 'value': v} + for v in treatment_data + ]) + + df = pd.DataFrame(data) + + # Create violin plots by segment + violin = hv.Violin(df, ['segment', 'variant'], 'value').options( + alpha=0.6, + violin_fill_color='variant', + cmap=['#1f77b4', '#ff7f0e'] + ) + + # Add box plots overlay + box = hv.BoxWhisker(df, ['segment', 'variant'], 'value').options( + box_fill_alpha=0.4, + box_color='white', + whisker_color='black' + ) + + # Combine and style + plot = (violin * box).options( + width=800, + height=400, + title='Treatment Effect by Segment', + tools=['hover'], + xlabel='Segment', + ylabel='Value', + legend_position='top_right', + show_grid=True + ) + + plot + return box, df, hv, n_samples, np, pd, plot, segments, variants, violin + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() \ No newline at end of file From 2088992fcdbf4ab70a99a7690c709c77b01885ab Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:53:04 +0530 Subject: [PATCH 18/34] new: Add `holoviews-7.py` - `adv data analysis` --- marimo/_snippets/data/holoviews-7.py | 115 +++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-7.py diff --git a/marimo/_snippets/data/holoviews-7.py b/marimo/_snippets/data/holoviews-7.py new file mode 100644 index 00000000000..9b6cb178ca8 --- /dev/null +++ b/marimo/_snippets/data/holoviews-7.py @@ -0,0 +1,115 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Advanced Data Analysis Suite + + Create interactive visualizations for comprehensive data analysis. + Common usage: Multi-dimensional analysis, pattern discovery. + Domains: Data Science, Research, Business Intelligence. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + from holoviews import opts + from sklearn.preprocessing import StandardScaler + from sklearn.cluster import KMeans + + hv.extension('bokeh') + + # Generate sample dataset + np.random.seed(42) + n_samples = 1000 + + # Create multi-dimensional dataset + data = pd.DataFrame({ + 'feature1': np.random.normal(0, 1, n_samples), + 'feature2': np.random.normal(0, 1, n_samples), + 'feature3': np.random.normal(0, 1, n_samples), + 'target': np.random.normal(0, 1, n_samples) + }) + + # Add correlations + data['feature2'] += data['feature1'] * 0.5 + data['feature3'] += data['feature2'] * 0.3 + data['target'] += data['feature1'] * 0.6 + data['feature2'] * 0.3 + + # Create bivariate distribution plot + bivariate = hv.Bivariate( + (data['feature1'], data['feature2']) + ).options( + width=300, + height=300, + cmap='viridis', + title='Feature Distribution' + ) + + # Create scatter with marginal distributions + scatter = hv.Points((data['feature1'], data['target'])).options( + color='navy', + alpha=0.6, + width=300, + height=300, + tools=['box_select', 'lasso_select'] + ) + + marginal_x = hv.Histogram(np.histogram(data['feature1'], bins=30)) + marginal_y = hv.Histogram(np.histogram(data['target'], bins=30)) + + # Cluster the data + scaler = StandardScaler() + scaled_data = scaler.fit_transform(data) + kmeans = KMeans(n_clusters=3, random_state=42) + clusters = kmeans.fit_predict(scaled_data) + + # Create cluster visualization + cluster_viz = hv.Points( + pd.DataFrame({ + 'x': data['feature1'], + 'y': data['feature2'], + 'Cluster': clusters.astype(str) + }), + kdims=['x', 'y'], + vdims=['Cluster'] + ).options( + color='Cluster', + cmap='Category10', + width=300, + height=300, + title='Cluster Analysis', + tools=['hover'] + ) + + # Combine visualizations + layout = ( + bivariate + + (scatter << marginal_x << marginal_y) + + cluster_viz + ).cols(3) + + layout + return (bivariate, cluster_viz, clusters, data, hv, kmeans, layout, marginal_x, + marginal_y, n_samples, np, opts, pd, scaler, scaled_data, scatter) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() \ No newline at end of file From 9dbcecb88c6e0b4c5c065943142c4aa4fe9b6679 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:53:34 +0530 Subject: [PATCH 19/34] new: Add `holoviews-8.py` - `mixed` --- marimo/_snippets/data/holoviews-8.py | 103 +++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-8.py diff --git a/marimo/_snippets/data/holoviews-8.py b/marimo/_snippets/data/holoviews-8.py new file mode 100644 index 00000000000..7c967f62691 --- /dev/null +++ b/marimo/_snippets/data/holoviews-8.py @@ -0,0 +1,103 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Core Plotting with `holoviews` + + Create essential visualizations using the `holoviews` library (imported as `hv`). + Common usage: Data visualization, exploratory analysis, statistical plotting. + Commonly used in: Data science, research, interactive dashboards. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + + hv.extension('bokeh') + + # Generate sample data + np.random.seed(42) + + # 1. Basic Scatter with Path overlay + x = np.linspace(0, 10, 100) + y = np.sin(x) + np.random.normal(0, 0.1, 100) + scatter = hv.Scatter((x, y)).options( + color='navy', size=8, tools=['hover'] + ) + path = hv.Path((x, y)).options( + line_color='red', line_width=2 + ) + + # 2. QuadMesh plot (instead of Surface) + x_range = np.linspace(-2, 2, 20) + y_range = np.linspace(-2, 2, 20) + xx, yy = np.meshgrid(x_range, y_range) + zz = np.sin(xx) * np.cos(yy) + quadmesh = hv.QuadMesh((x_range, y_range, zz)).options( + cmap='viridis', + width=300, + height=300, + tools=['hover'], + title='QuadMesh Plot' + ) + + # 3. Contour plot + contours = hv.Contours((x_range, y_range, zz)).options( + width=300, + height=300, + tools=['hover'], + title='Contour Plot', + cmap='viridis' + ) + + # 4. Points with color mapping + points_data = pd.DataFrame({ + 'x': np.random.normal(0, 1, 100), + 'y': np.random.normal(0, 1, 100), + 'color': np.random.uniform(0, 1, 100) + }) + points = hv.Points(points_data, ['x', 'y'], 'color').options( + color='color', + cmap='RdYlBu', + size=8, + tools=['hover'], + width=300, + height=300, + title='Colored Points' + ) + + # Combine plots in layout + layout = ( + (scatter * path) + + quadmesh + + contours + + points + ).cols(4).options( + title='HoloViews Plot Gallery' + ) + + layout + return (contours, hv, layout, np, path, pd, points, points_data, quadmesh, + scatter, x, x_range, xx, y, y_range, yy, zz) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 20b83e54a7d2bf0cce392c3e218731fb40da420f Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:53:58 +0530 Subject: [PATCH 20/34] new: Add `holoviews-9.py` - `stats layout` --- marimo/_snippets/data/holoviews-9.py | 75 ++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-9.py diff --git a/marimo/_snippets/data/holoviews-9.py b/marimo/_snippets/data/holoviews-9.py new file mode 100644 index 00000000000..8e77678f6be --- /dev/null +++ b/marimo/_snippets/data/holoviews-9.py @@ -0,0 +1,75 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Essential Plot Types with `holoviews` + + Create fundamental visualizations using the `holoviews` library. + Common usage: Basic data visualization, statistical plotting. + Commonly used in: Data analysis, research, reporting. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + + hv.extension('bokeh') + + # Generate sample data + np.random.seed(42) + x = np.linspace(0, 10, 50) + y = np.sin(x) + np.random.normal(0, 0.1, 50) + categories = ['A', 'B', 'C', 'D'] + values = np.random.normal(10, 2, len(categories)) + + # Create basic plots + curve = hv.Curve((x, y), 'x', 'y').options( + width=300, height=200, color='navy', + title='Curve Plot' + ) + + bars = hv.Bars(({'category': categories, 'value': values}), + 'category', 'value').options( + width=300, height=200, color='green', + title='Bar Plot' + ) + + area = hv.Area((x, y)).options( + width=300, height=200, color='purple', alpha=0.5, + title='Area Plot' + ) + + spikes = hv.Spikes((x, np.abs(y))).options( + width=300, height=200, color='red', + title='Spike Plot' + ) + + # Combine in layout + layout = (curve + bars + area + spikes).cols(2).options( + title='Basic Plot Types' + ) + + layout + return area, bars, categories, curve, hv, layout, np, pd, spikes, values, x, y + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From f817858835d74a925a63707231aa58a171888682 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:55:06 +0530 Subject: [PATCH 21/34] new: Add `holoviews-10.py` - `error` --- marimo/_snippets/data/holoviews-10.py | 78 +++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-10.py diff --git a/marimo/_snippets/data/holoviews-10.py b/marimo/_snippets/data/holoviews-10.py new file mode 100644 index 00000000000..e7d47995083 --- /dev/null +++ b/marimo/_snippets/data/holoviews-10.py @@ -0,0 +1,78 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # HoloViews: Error Analysis with `holoviews` + + Create visualizations with error bars and range overlays using `hv.ErrorBars` and `hv.VSpan`. + Common usage: Uncertainty visualization, confidence intervals, data ranges. + Commonly used in: Scientific research, statistical analysis, experimental data. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + + hv.extension('bokeh') + + # Generate sample data with uncertainty + x = np.linspace(0, 10, 30) + y = np.sin(x) + 0.1 + yerr = np.random.uniform(0.1, 0.2, len(x)) + + # Create error bars plot + errorbars = hv.ErrorBars((x, y, yerr)).options( + width=400, height=300, + title='Measurement with Uncertainty' + ) + + curve = hv.Curve((x, y)).options( + color='navy', + xlabel='X', + ylabel='Value' + ) + error_plot = (curve * errorbars) + + # Create range visualization + spans = [] + for i in range(3): + x1, x2 = np.random.uniform(0, 10, 2) + x1, x2 = min(x1, x2), max(x1, x2) + spans.append(hv.VSpan(x1, x2).options( + alpha=0.2, + fill_color=['blue', 'green', 'red'][i] + )) + + range_plot = hv.Curve((x, y)) * hv.Overlay(spans).options( + width=400, height=300, + title='Regions of Interest' + ) + + # Combine visualizations + layout = (error_plot + range_plot).cols(2) + + layout + return (curve, error_plot, errorbars, hv, layout, np, pd, range_plot, spans, + x, y, yerr) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 33a6ed8060395af1f32d971525ec6c27b4053e14 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:55:28 +0530 Subject: [PATCH 22/34] new: Add `holoviews-11.py` - `curve ranges` --- marimo/_snippets/data/holoviews-11.py | 73 +++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 marimo/_snippets/data/holoviews-11.py diff --git a/marimo/_snippets/data/holoviews-11.py b/marimo/_snippets/data/holoviews-11.py new file mode 100644 index 00000000000..603a92aed94 --- /dev/null +++ b/marimo/_snippets/data/holoviews-11.py @@ -0,0 +1,73 @@ +# Copyright 2024 Marimo. All rights reserved. +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # `holoviews`: Scientific Data Visualization + + Create interactive scientific plots with error bars and ranges using `holoviews`. + Common usage: Error analysis, uncertainty visualization, region highlighting. + Commonly used in: Research, data science, scientific computing. + """ + ) + return + + +@app.cell +def __(): + import holoviews as hv + import numpy as np + import pandas as pd + + hv.extension('bokeh') + + # Generate sample data with uncertainty + x = np.linspace(0, 10, 30) + y = np.sin(x) + 0.1 + yerr = np.random.uniform(0.1, 0.2, len(x)) + + # Create error bars plot + errorbars = hv.ErrorBars((x, y, yerr)).options( + width=400, height=300, + title='Measurement with Uncertainty' + ) + + curve = hv.Curve((x, y), 'X', 'Value').options(color='navy') + error_plot = (curve * errorbars) + + # Create range visualization + spans = [] + for i in range(3): + x1, x2 = np.random.uniform(0, 10, 2) + x1, x2 = min(x1, x2), max(x1, x2) + spans.append(hv.VSpan(x1, x2).options( + alpha=0.2, color=['blue', 'green', 'red'][i] + )) + + range_plot = hv.Curve((x, y)) * hv.Overlay(spans).options( + width=400, height=300, + title='Regions of Interest' + ) + + # Combine visualizations + layout = (error_plot + range_plot).cols(2) + + layout + return (curve, error_plot, errorbars, hv, layout, np, pd, range_plot, spans, + x, y, yerr) + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 5706a702f9226c1c9d99114bd2c6d931f6bc5dab Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:55:45 +0530 Subject: [PATCH 23/34] new: Add `plotly-0.py` - `line plot` --- marimo/_snippets/data/plotly-0.py | 56 +++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 marimo/_snippets/data/plotly-0.py diff --git a/marimo/_snippets/data/plotly-0.py b/marimo/_snippets/data/plotly-0.py new file mode 100644 index 00000000000..d3862994624 --- /dev/null +++ b/marimo/_snippets/data/plotly-0.py @@ -0,0 +1,56 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Plotly: Interactive Line Plot + + Create an interactive line plot with hover tooltips and zoom capabilities. + Common usage: `fig = px.line(df, x="x_col", y="y_col")`. + """ + ) + return + + +@app.cell +def __(): + import plotly.express as px + import numpy as np + + # Sample data + x = np.linspace(0, 10, 100) + y = np.sin(x) + + # Create interactive plot + fig = px.line( + x=x, + y=y, + title="Interactive Sine Wave", + labels={"x": "X Axis", "y": "Sin(x)"} + ) + + # Update layout for better appearance + fig.update_layout( + showlegend=False, + hovermode="x unified" + ) + + fig + return fig, np, px + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From be80af11581dbf6265b8e0e7d0ea0a593487ff29 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:56:01 +0530 Subject: [PATCH 24/34] new: Add `plotly-1.py` - `scatter plot` --- marimo/_snippets/data/plotly-1.py | 66 +++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 marimo/_snippets/data/plotly-1.py diff --git a/marimo/_snippets/data/plotly-1.py b/marimo/_snippets/data/plotly-1.py new file mode 100644 index 00000000000..851c75552a1 --- /dev/null +++ b/marimo/_snippets/data/plotly-1.py @@ -0,0 +1,66 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: Interactive Scatter Plot with Categories + + Create a scatter plot with categorical coloring and size mapping. + Common usage: `fig = px.scatter(df, x="col1", y="col2", color="category", size="values")`. + """ + ) + return + + +@app.cell +def _(): + import plotly.express as px + import numpy as np + + # Sample data + np.random.seed(42) + n_points = 50 + + data = { + 'x': np.random.normal(0, 1, n_points), + 'y': np.random.normal(0, 1, n_points), + 'size': np.random.uniform(5, 25, n_points), + 'group': [f"Group {i}" for i in np.random.randint(1, 4, n_points)] + } + + # Create interactive scatter plot + fig = px.scatter( + data, + x='x', + y='y', + size='size', + color='group', + title="Interactive Grouped Scatter", + labels={'x': 'X Value', 'y': 'Y Value', 'size': 'Size Value'}, + hover_data=['group', 'size'] + ) + + # Update layout + fig.update_layout( + hovermode='closest' + ) + + fig + return data, fig, n_points, np, px + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From 43ff07988f9b9356775fa1ac26d180d053a89cdf Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:56:13 +0530 Subject: [PATCH 25/34] new: Add `plotly-2.py` - `TS` --- marimo/_snippets/data/plotly-2.py | 71 +++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 marimo/_snippets/data/plotly-2.py diff --git a/marimo/_snippets/data/plotly-2.py b/marimo/_snippets/data/plotly-2.py new file mode 100644 index 00000000000..4ecf52854c2 --- /dev/null +++ b/marimo/_snippets/data/plotly-2.py @@ -0,0 +1,71 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: Time Series with Range Selector + + Create an interactive time series plot with built-in range selector and slider. + Common usage: `fig = px.line(df, x="date_column", y="value_column")`. + """ + ) + return + + +@app.cell +def _(): + import plotly.express as px + import pandas as pd + import numpy as np + + # Generate sample time series data + dates = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D') + values = np.cumsum(np.random.randn(len(dates))) + 100 + + df = pd.DataFrame({ + 'date': dates, + 'value': values + }) + + # Create interactive time series + fig = px.line( + df, + x='date', + y='value', + title='Interactive Time Series' + ) + + # Add range selector and slider + fig.update_layout( + xaxis=dict( + rangeselector=dict( + buttons=[ + dict(count=1, label="1m", step="month", stepmode="backward"), + dict(count=3, label="3m", step="month", stepmode="backward"), + dict(count=6, label="6m", step="month", stepmode="backward"), + dict(step="all", label="All") + ] + ), + rangeslider=dict(visible=True) + ) + ) + + fig + return dates, df, fig, np, pd, px, values + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From 050f36760c3ef960ce5c17461bd0bffe8e5bb5ae Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:56:28 +0530 Subject: [PATCH 26/34] new: Add `plotly-3.py` - `heatmap` --- marimo/_snippets/data/plotly-3.py | 69 +++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 marimo/_snippets/data/plotly-3.py diff --git a/marimo/_snippets/data/plotly-3.py b/marimo/_snippets/data/plotly-3.py new file mode 100644 index 00000000000..bddd2f9fef9 --- /dev/null +++ b/marimo/_snippets/data/plotly-3.py @@ -0,0 +1,69 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: Correlation Heatmap + + Create an interactive correlation heatmap with customizable color scale. + Common usage: `fig = px.imshow(df.corr(), color_continuous_scale='RdBu_r')`. + """ + ) + return + + +@app.cell +def _(): + import plotly.express as px + import pandas as pd + import numpy as np + + # Generate sample correlated data + np.random.seed(42) + n_samples = 100 + df = pd.DataFrame({ + 'A': np.random.normal(0, 1, n_samples), + 'B': np.random.normal(0, 1, n_samples), + 'C': np.random.normal(0, 1, n_samples), + 'D': np.random.normal(0, 1, n_samples) + }) + df['B'] = df['A'] * 0.8 + np.random.normal(0, 0.2, n_samples) + df['D'] = -df['C'] * 0.6 + np.random.normal(0, 0.3, n_samples) + + # Create correlation matrix + corr_matrix = df.corr() + + # Create heatmap + fig = px.imshow( + corr_matrix, + color_continuous_scale='RdBu_r', + aspect='auto', + title='Correlation Matrix Heatmap' + ) + + # Update layout + fig.update_layout( + xaxis_title="Features", + yaxis_title="Features", + coloraxis_colorbar_title="Correlation" + ) + + fig + return corr_matrix, df, fig, n_samples, np, pd, px + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From c95ba42e5244b20c58b11e2b8e6d953bae7299c1 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:56:41 +0530 Subject: [PATCH 27/34] new: Add `plotly-4.py` - `dashboard` --- marimo/_snippets/data/plotly-4.py | 83 +++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 marimo/_snippets/data/plotly-4.py diff --git a/marimo/_snippets/data/plotly-4.py b/marimo/_snippets/data/plotly-4.py new file mode 100644 index 00000000000..d1805b9d983 --- /dev/null +++ b/marimo/_snippets/data/plotly-4.py @@ -0,0 +1,83 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: Multiple Metrics Dashboard + + Create a dashboard-style layout with multiple plots using subplots. + Common usage: `make_subplots(rows=2, cols=2)` followed by `add_trace()` for each plot. + """ + ) + return + + +@app.cell +def _(): + import plotly.graph_objects as go + from plotly.subplots import make_subplots + import numpy as np + import pandas as pd + + # Generate sample data + np.random.seed(42) + x = np.linspace(0, 10, 100) + y1 = np.sin(x) + np.random.normal(0, 0.1, 100) + y2 = np.cumsum(np.random.randn(100)) + y3 = np.random.normal(0, 1, 100) + + # Create subplots + fig = make_subplots( + rows=2, cols=2, + subplot_titles=('Time Series', 'Cumulative Sum', + 'Distribution', 'Moving Average') + ) + + # Add traces + fig.add_trace( + go.Scatter(x=x, y=y1, name="Time Series"), + row=1, col=1 + ) + + fig.add_trace( + go.Scatter(x=x, y=y2, name="Cumulative"), + row=1, col=2 + ) + + fig.add_trace( + go.Histogram(x=y3, name="Distribution"), + row=2, col=1 + ) + + fig.add_trace( + go.Scatter(x=x, y=pd.Series(y1).rolling(10).mean(), + name="Moving Avg"), + row=2, col=2 + ) + + # Update layout + fig.update_layout( + height=800, + showlegend=False, + title_text="Multiple Metrics Dashboard" + ) + + fig + return fig, go, make_subplots, np, pd, x, y1, y2, y3 + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From 58b0a59136ffb862e69ea6ae2190876c84ed7e20 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:56:54 +0530 Subject: [PATCH 28/34] new: Add `plotly-5.py` - `finance` --- marimo/_snippets/data/plotly-5.py | 91 +++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 marimo/_snippets/data/plotly-5.py diff --git a/marimo/_snippets/data/plotly-5.py b/marimo/_snippets/data/plotly-5.py new file mode 100644 index 00000000000..d5741d43c11 --- /dev/null +++ b/marimo/_snippets/data/plotly-5.py @@ -0,0 +1,91 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def __(mo): + mo.md( + r""" + # Plotly: Financial Chart with Volume + + Create an interactive financial chart combining candlesticks and volume bars. + Common usage: `go.Figure(data=[go.Candlestick(x=df.index, open=df.Open)])`. + """ + ) + return + + +@app.cell +def __(): + import plotly.graph_objects as go + from plotly.subplots import make_subplots + import pandas as pd + import numpy as np + + # Generate sample OHLCV data + np.random.seed(42) + dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') + price = 100 + np.random.randn(len(dates)).cumsum() + + df = pd.DataFrame({ + 'Open': price + np.random.randn(len(dates)), + 'High': price + abs(np.random.randn(len(dates))*2), + 'Low': price - abs(np.random.randn(len(dates))*2), + 'Close': price + np.random.randn(len(dates)), + 'Volume': np.random.randint(1000, 10000, len(dates)) + }, index=dates) + + # Create figure with secondary y-axis + fig = make_subplots( + rows=2, cols=1, + row_heights=[0.7, 0.3], + vertical_spacing=0.05, + shared_xaxes=True + ) + + # Add candlestick + fig.add_trace( + go.Candlestick( + x=df.index, + open=df.Open, + high=df.High, + low=df.Low, + close=df.Close, + name="OHLC" + ), + row=1, col=1 + ) + + # Add volume bars + fig.add_trace( + go.Bar( + x=df.index, + y=df.Volume, + name="Volume" + ), + row=2, col=1 + ) + + # Update layout + fig.update_layout( + title="Stock Price and Volume Analysis", + xaxis_rangeslider_visible=False, + height=800 + ) + + fig + return fig, go, make_subplots, pd, np + + +@app.cell +def __(): + import marimo as mo + return mo, + + +if __name__ == "__main__": + app.run() From 0f38902b51db4b129dc4088094f1c5d6cbb1b931 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:57:24 +0530 Subject: [PATCH 29/34] new: Add `plotly-6.py` - `stats distr` --- marimo/_snippets/data/plotly-6.py | 72 +++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 marimo/_snippets/data/plotly-6.py diff --git a/marimo/_snippets/data/plotly-6.py b/marimo/_snippets/data/plotly-6.py new file mode 100644 index 00000000000..43474863db3 --- /dev/null +++ b/marimo/_snippets/data/plotly-6.py @@ -0,0 +1,72 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: Statistical Distribution Comparison + + Create violin plots with box plots overlay for distribution comparison. + Common usage: `fig = go.Figure(data=[go.Violin(x=groups, y=values)])`. + """ + ) + return + + +@app.cell +def _(): + import plotly.graph_objects as go + import numpy as np + + # Generate sample data from different distributions + np.random.seed(42) + + groups = ['A', 'B', 'C'] + data = { + 'A': np.random.normal(0, 1, 200), + 'B': np.random.normal(2, 1.5, 200), + 'C': np.random.exponential(2, 200) + } + + # Create figure + fig = go.Figure() + + # Add violin plots + for group in groups: + fig.add_trace( + go.Violin( + x=[group] * len(data[group]), + y=data[group], + name=group, + box_visible=True, + meanline_visible=True, + points="outliers" + ) + ) + + # Update layout + fig.update_layout( + title="Distribution Comparison", + yaxis_title="Values", + xaxis_title="Groups", + violinmode='group' + ) + + fig + return data, fig, go, group, groups, np + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From 6ffee00518747e4131c34f10aef0b819c6a2ca98 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:58:24 +0530 Subject: [PATCH 30/34] new: Add `plotly-7.py` - `3D scatter` --- marimo/_snippets/data/plotly-7.py | 80 +++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 marimo/_snippets/data/plotly-7.py diff --git a/marimo/_snippets/data/plotly-7.py b/marimo/_snippets/data/plotly-7.py new file mode 100644 index 00000000000..155a276807b --- /dev/null +++ b/marimo/_snippets/data/plotly-7.py @@ -0,0 +1,80 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: 3D Scatter Plot with Clusters + + Create an interactive 3D scatter plot for dimensional analysis. + Common usage: `fig = px.scatter_3d(df, x='x', y='y', z='z', color='cluster')`. + """ + ) + return + + +@app.cell +def _(): + import plotly.express as px + import numpy as np + import pandas as pd + from sklearn.datasets import make_blobs + + # Generate clustered 3D data + n_samples = 300 + n_clusters = 4 + + X, labels = make_blobs( + n_samples=n_samples, + n_features=3, + centers=n_clusters, + random_state=42 + ) + + df = pd.DataFrame( + X, + columns=['x', 'y', 'z'] + ) + df['cluster'] = labels + + # Create 3D scatter plot + fig = px.scatter_3d( + df, + x='x', + y='y', + z='z', + color='cluster', + title='3D Cluster Visualization', + labels={'cluster': 'Cluster'}, + opacity=0.7 + ) + + # Update layout for better interactivity + fig.update_layout( + scene=dict( + camera=dict( + up=dict(x=0, y=0, z=1), + center=dict(x=0, y=0, z=0), + eye=dict(x=1.5, y=1.5, z=1.5) + ) + ) + ) + + fig + return X, df, fig, labels, make_blobs, n_clusters, n_samples, np, pd, px + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From 217ecb17953c59ae8866a99d193204dc675f1a4e Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:58:40 +0530 Subject: [PATCH 31/34] new: Add `plotly-8.py` - `geo map` --- marimo/_snippets/data/plotly-8.py | 68 +++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 marimo/_snippets/data/plotly-8.py diff --git a/marimo/_snippets/data/plotly-8.py b/marimo/_snippets/data/plotly-8.py new file mode 100644 index 00000000000..fd14ff28a46 --- /dev/null +++ b/marimo/_snippets/data/plotly-8.py @@ -0,0 +1,68 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: Geographic Choropleth Map + + Create an interactive choropleth map for geographic data visualization. + Common usage: `fig = px.choropleth(df, locations='iso_code', color='values')`. + """ + ) + return + + +@app.cell +def _(): + import plotly.express as px + import pandas as pd + + # Sample data for countries + data = { + 'country_code': ['USA', 'GBR', 'FRA', 'DEU', 'JPN', 'IND', 'CHN'], + 'value': [100, 30, 50, 76, 61, 89, 95], + 'text': ['United States', 'United Kingdom', 'France', + 'Germany', 'Japan', 'India', 'China'] + } + df = pd.DataFrame(data) + + # Create choropleth map + fig = px.choropleth( + df, + locations='country_code', + color='value', + hover_name='text', + color_continuous_scale='Viridis', + title='Global Distribution Map', + locationmode='ISO-3' + ) + + # Update layout + fig.update_layout( + geo=dict( + showframe=False, + showcoastlines=True, + projection_type='equirectangular' + ), + height=600 + ) + + fig + return data, df, fig, pd, px + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From 6a3ba4925c4c9e5aa8cc371fd2152ed0d1e9ad65 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:59:03 +0530 Subject: [PATCH 32/34] new: Add `plotly-9.py` - `analyze plot` --- marimo/_snippets/data/plotly-9.py | 64 +++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 marimo/_snippets/data/plotly-9.py diff --git a/marimo/_snippets/data/plotly-9.py b/marimo/_snippets/data/plotly-9.py new file mode 100644 index 00000000000..eb31c3c6c45 --- /dev/null +++ b/marimo/_snippets/data/plotly-9.py @@ -0,0 +1,64 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: Conversion Funnel Analysis + + Create an interactive funnel chart for analyzing conversion steps. + Common usage: `fig = go.Figure(go.Funnel(y=stages, x=values))`. + """ + ) + return + + +@app.cell +def _(): + import plotly.graph_objects as go + + # Sample conversion data + stages = ['Visitors', 'Cart', 'Checkout', 'Purchase'] + values = [1000, 600, 300, 150] + + # Calculate conversion rates + rates = [f"{100*v2/v1:.1f}%" + for v1, v2 in zip(values[:-1], values[1:])] + rates = [""] + rates + + # Create funnel chart + fig = go.Figure(go.Funnel( + y=stages, + x=values, + textinfo="value+percent initial", + textposition="auto", + texttemplate="%{value}
%{text}", + text=rates, + connector={"line": {"color": "royalblue", "dash": "dot"}} + )) + + # Update layout + fig.update_layout( + title="Conversion Funnel Analysis", + showlegend=False, + height=500 + ) + + fig + return fig, go, rates, stages, values + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From 776f1338538e27bba99ed27d1c0f893a1bb2718b Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:59:17 +0530 Subject: [PATCH 33/34] new: Add `plotly-10.py` - `bubble chart` --- marimo/_snippets/data/plotly-10.py | 85 ++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 marimo/_snippets/data/plotly-10.py diff --git a/marimo/_snippets/data/plotly-10.py b/marimo/_snippets/data/plotly-10.py new file mode 100644 index 00000000000..65e76e8c3a7 --- /dev/null +++ b/marimo/_snippets/data/plotly-10.py @@ -0,0 +1,85 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: Animated Bubble Chart + + Create an animated bubble chart for time-series multi-dimensional data. + Common usage: `px.scatter(df, x='x', y='y', animation_frame='year', size='size')`. + """ + ) + return + + +@app.cell +def _(): + import plotly.express as px + import pandas as pd + import numpy as np + + # Generate sample time-series data + np.random.seed(42) + years = range(2015, 2024) + categories = ['A', 'B', 'C', 'D'] + + data = [] + for year in years: + for cat in categories: + data.append({ + 'year': year, + 'category': cat, + 'value_x': np.random.normal(loc=year-2015, scale=1), + 'value_y': np.random.normal(loc=5, scale=2), + 'size': np.random.randint(20, 100), + 'growth': np.random.uniform(-10, 20) + }) + + df = pd.DataFrame(data) + + # Create animated bubble chart + fig = px.scatter( + df, + x='value_x', + y='value_y', + animation_frame='year', + size='size', + color='category', + hover_name='category', + text='category', + size_max=60, + range_x=[-1, 10], + range_y=[-5, 15], + title='Metric Evolution Over Time' + ) + + # Update layout + fig.update_traces( + textposition='top center', + marker=dict(sizemin=10) + ) + + fig.update_layout( + height=600, + showlegend=True + ) + + fig + return cat, categories, data, df, fig, np, pd, px, year, years + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run() From b1c46da47e87d57747d33d36e50087dededd5345 Mon Sep 17 00:00:00 2001 From: Srihari Thyagarajan Date: Mon, 10 Feb 2025 22:59:46 +0530 Subject: [PATCH 34/34] new: Add `plotly-11.py` - `dendrograms` --- marimo/_snippets/data/plotly-11.py | 107 +++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 marimo/_snippets/data/plotly-11.py diff --git a/marimo/_snippets/data/plotly-11.py b/marimo/_snippets/data/plotly-11.py new file mode 100644 index 00000000000..fe6256274ce --- /dev/null +++ b/marimo/_snippets/data/plotly-11.py @@ -0,0 +1,107 @@ +# Copyright 2024 Marimo. All rights reserved. + +import marimo + +__generated_with = "0.11.0" +app = marimo.App() + + +@app.cell +def _(mo): + mo.md( + r""" + # Plotly: Clustering Analysis Visualization + + Create an interactive heatmap with dendrograms for hierarchical clustering analysis. + Common usage: `fig = ff.create_dendrogram(X)` and `px.imshow(correlation_matrix)`. + Commonly used in: feature correlation analysis, gene expression analysis, customer segmentation. + """ + ) + return + + +@app.cell +def _(): + import plotly.figure_factory as ff + import plotly.express as px + from scipy.cluster.hierarchy import linkage + import numpy as np + import pandas as pd + + # Generate sample data + np.random.seed(42) + n_features = 10 + n_samples = 100 + + # Create feature names + feature_names = [f'Feature_{i}' for i in range(n_features)] + + # Generate correlated data + data = np.random.randn(n_samples, n_features) + data[:, 1] = data[:, 0] + np.random.randn(n_samples) * 0.3 # Correlate features 0 and 1 + data[:, 4] = data[:, 3] - np.random.randn(n_samples) * 0.2 # Correlate features 3 and 4 + + df = pd.DataFrame(data, columns=feature_names) + + # Compute correlation matrix + corr_matrix = df.corr() + + # Compute linkage for dendrogram + linkage_matrix = linkage(corr_matrix, 'ward') + + # Create dendrogram + fig_dendrogram = ff.create_dendrogram( + corr_matrix, + labels=feature_names, + color_threshold=1.5 + ) + fig_dendrogram.update_layout( + title='Feature Clustering Dendrogram', + width=800, + height=400 + ) + + # Create heatmap + fig_heatmap = px.imshow( + corr_matrix, + labels=dict(x="Features", y="Features", color="Correlation"), + x=feature_names, + y=feature_names, + color_continuous_scale="RdBu_r", + aspect="auto" + ) + fig_heatmap.update_layout( + title='Feature Correlation Heatmap', + width=800, + height=800 + ) + + # Display both visualizations + fig_dendrogram + fig_heatmap + return ( + corr_matrix, + data, + df, + feature_names, + ff, + fig_dendrogram, + fig_heatmap, + linkage, + linkage_matrix, + n_features, + n_samples, + np, + pd, + px, + ) + + +@app.cell +def _(): + import marimo as mo + return (mo,) + + +if __name__ == "__main__": + app.run()