### Install drawdata and Data Handling Libraries Source: https://github.com/koaning/drawdata/blob/main/readme.md Installs the drawdata library and optional data handling libraries like pandas and polars. These are necessary for using the drawing widgets and processing the drawn data. ```shell python -m pip install drawdata python -m pip install pandas polars ``` -------------------------------- ### Python: Marimo App with ScatterWidget and Altair Chart Source: https://github.com/koaning/drawdata/blob/main/docs/index.html This Python code defines a Marimo application that integrates the drawdata library's ScatterWidget. It displays markdown instructions and visualizes drawn data using Altair charts, updating dynamically as the user interacts with the ScatterWidget. It requires Marimo, Pandas, Drawdata, and Altair libraries. ```python import marimo __generated_with = "0.13.6" app = marimo.App(width="medium") @app.cell def _(): import marimo as mo import pandas as pd from drawdata import ScatterWidget return ScatterWidget, mo @app.cell(hide_code=True) def _(mo): mo.md( r""" # Drawing a `ScatterChart` This notebook contains a demo of the `ScatterWidget` inside of the [drawdata](https://github.com/koaning/drawdata) library. You should see that as you draw data, that the chart below updates. """ ) return @app.cell(hide_code=True) def _(ScatterWidget, mo): widget = mo.ui.anywidget(ScatterWidget(height=350)) widget return (widget,) @app.cell(hide_code=True) def _(mo, widget): import altair as alt out = mo.md("Draw some data to see the effect here.") if widget.value["data"]: base = alt.Chart(widget.data_as_pandas) base_bar = base.mark_bar(opacity=0.3, binSpacing=0) color_domain = widget.data_as_pandas["color"].unique() xscale = alt.Scale(domain=(0, widget.value["width"])) yscale = alt.Scale(domain=(0, widget.value["height"])) colscale = alt.Scale(domain=color_domain, range=color_domain) points = base.mark_circle().encode( alt.X("x").scale(xscale), alt.Y("y").scale(yscale), color="color", ) top_hist = ( base_bar .encode( alt.X("x:Q"), # when using bins, the axis scale is set through # the bin extent, so we do not specify the scale here # (which would be ignored anyway) .bin(maxbins=30, extent=xscale.domain).stack(None).title(""), alt.Y("count()").stack(None).title(""), alt.Color("color:N", scale=colscale) ) .properties(height=60) ) right_hist = ( base_bar .encode( alt.Y("y:Q"), ``` -------------------------------- ### Customize ScatterWidget and BarWidget Appearance Source: https://context7.com/koaning/drawdata/llms.txt Illustrates how to customize the appearance and behavior of `ScatterWidget` and `BarWidget` using initialization parameters. It covers setting dimensions, brush size for ScatterWidget, and number of bins, axis limits, and collection names for BarWidget. It also shows how to access and modify these properties after widget creation. ```python from drawdata import ScatterWidget, BarWidget # ScatterWidget configuration scatter_widget = ScatterWidget( width=1000, # Canvas width in pixels height=600, # Canvas height in pixels brushsize=50 # Size of the drawing brush ) # BarWidget configuration bar_widget = BarWidget( width=800, # Canvas width height=550, # Canvas height n_bins=24, # Number of bins/bars y_min=0.0, # Minimum y-axis value y_max=100.0, # Maximum y-axis value collection_names=["usage", "capacity", "forecast"] # Names for data series ) # Access and modify properties after creation scatter_widget.brushsize = 60 bar_widget.y_max = 150.0 # Display widgets # scatter_widget # bar_widget # Properties are synchronized with the frontend print(f"Current brush size: {scatter_widget.brushsize}") print(f"Number of bins: {bar_widget.n_bins}") ``` -------------------------------- ### Initialize and Display BarWidget for Data Drawing Source: https://github.com/koaning/drawdata/blob/main/readme.md Initializes the BarWidget from the drawdata library with specified collection names and number of bins. This widget is used for drawing bar chart data. ```python from drawdata import BarWidget widget = BarWidget(collection_names=["usage", "sunshine"], n_bins=24) widget ``` -------------------------------- ### Create and Use ScatterWidget for Interactive Point Drawing (Python) Source: https://context7.com/koaning/drawdata/llms.txt Demonstrates how to initialize a ScatterWidget, display it in a Jupyter notebook, and access the drawn data in various formats including raw lists, pandas DataFrames, polars DataFrames, and scikit-learn compatible arrays (X, y). Handles both classification (multi-color) and regression (single-color) tasks. ```Python from drawdata import ScatterWidget # Create a scatter widget with custom dimensions widget = ScatterWidget(height=400, width=600, brushsize=30) # Display the widget in a Jupyter notebook widget # Access the raw data as a list of dictionaries raw_data = widget.data # Example output: [{'x': 150, 'y': 200, 'color': '#ff0000'}, {'x': 300, 'y': 350, 'color': '#0000ff'}] # Convert to pandas DataFrame import pandas as pd df = widget.data_as_pandas print(df.head()) # x y color # 0 150 200 #ff0000 # 1 300 350 #0000ff # Convert to polars DataFrame import polars as pl df_polars = widget.data_as_polars # Get data formatted for scikit-learn (classification with multiple colors) X, y = widget.data_as_X_y # X shape: (n_samples, 2) - x and y coordinates # y: list of color strings for each point # For single-color regression tasks (y-axis is the target) single_color_widget = ScatterWidget() # After drawing with one color X_reg, y_reg = single_color_widget.data_as_X_y # X_reg shape: (n_samples, 1) - x coordinates only # y_reg: array of y coordinates as regression targets ``` -------------------------------- ### Create and Use BarWidget for Interactive Bar Chart Drawing (Python) Source: https://context7.com/koaning/drawdata/llms.txt Illustrates the creation and usage of BarWidget for interactive bar chart data generation. It covers initialization with custom bins and collections, accessing raw data, converting to pandas and polars DataFrames, and integrating with Altair for visualization. ```Python from drawdata import BarWidget # Create a bar widget with multiple collections and custom bins widget = BarWidget( height=400, width=700, n_bins=24, collection_names=["solar", "wind", "hydro"], y_min=0.0, y_max=100.0 ) # Display the widget widget # Access the raw data raw_data = widget.data # Example: [{'bin': 0, 'value': 45.2, 'collection': 'solar'}, # {'bin': 1, 'value': 32.8, 'collection': 'solar'}] # Convert to pandas DataFrame for analysis df = widget.data_as_pandas print(df.head()) # bin value collection # 0 0 45.2 solar # 1 1 32.8 solar # 2 2 52.1 solar # Pivot and aggregate the data pivot_df = df.pivot(columns='collection', index='bin', values='value') print(pivot_df.head()) # solar wind hydro # bin # 0 45.2 30.5 12.3 # 1 32.8 28.7 15.6 # Convert to polars DataFrame import polars as pl df_polars = widget.data_as_polars # Use with visualization libraries import altair as alt chart = alt.Chart(df).mark_bar().encode( x='bin:O', y='value:Q', color='collection:N' ) ``` -------------------------------- ### Initialize and Display ScatterWidget for Data Drawing Source: https://github.com/koaning/drawdata/blob/main/readme.md Initializes the ScatterWidget from the drawdata library and displays it. This widget allows users to draw points on a scatter plot within a Jupyter environment. ```python from drawdata import ScatterWidget widget = ScatterWidget() widget ``` -------------------------------- ### Access Drawn Data from ScatterWidget Source: https://github.com/koaning/drawdata/blob/main/readme.md Demonstrates how to retrieve the data drawn using the ScatterWidget. Supports various formats including a list of dictionaries, pandas DataFrame, Polars DataFrame, and scikit-learn compatible X, y arrays. ```python # Get the drawn data as a list of dictionaries widget.data # Get the drawn data as a dataframe widget.data_as_pandas widget.data_as_polars X, y = widget.data_as_X_y ``` -------------------------------- ### Data Conversion Utilities Source: https://context7.com/koaning/drawdata/llms.txt Provides properties to easily convert the drawn data from the widgets into commonly used data structures like pandas DataFrames and polars DataFrames for further analysis and visualization. ```APIDOC ## Data Conversion Properties ### Description These properties, available on both `ScatterWidget` and `BarWidget`, allow users to convert the interactively drawn data into standard data structures for analysis. ### Method Access properties on widget instances. ### Endpoint N/A (Python Library) ### Parameters N/A ### Properties - **data_as_pandas** (pandas.DataFrame) - Converts the widget's drawn data into a pandas DataFrame with appropriate column names and data types. - **data_as_polars** (polars.DataFrame) - Converts the widget's drawn data into a polars DataFrame. - **data_as_X_y** (tuple) - For `ScatterWidget`, returns data formatted for scikit-learn (see `ScatterWidget` documentation). ### Request Example (data_as_pandas) ```python from drawdata import ScatterWidget import pandas as pd widget = ScatterWidget(height=350, width=800) # After drawing some points in the widget # Get pandas DataFrame df = widget.data_as_pandas # Perform standard pandas operations summary = df.groupby('color').agg({ 'x': ['mean', 'std'], 'y': ['mean', 'std'], 'color': 'count' }) print(summary) ``` ### Response #### Success Response (DataFrame Output) - **data_as_pandas** (pandas.DataFrame) - A pandas DataFrame containing the drawn data. #### Response Example (pandas output) ``` x y color 0 150 200 #ff0000 1 300 350 #0000ff ``` ``` -------------------------------- ### Format Data for Scikit-learn with ScatterWidget Source: https://context7.com/koaning/drawdata/llms.txt Demonstrates how to use the `data_as_X_y` property of ScatterWidget to format drawn data into feature (X) and target (y) arrays suitable for scikit-learn classifiers and regressors. It intelligently detects whether the task is classification or regression based on the drawn data. ```python from drawdata import ScatterWidget from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LinearRegression from sklearn.metrics import accuracy_score, r2_score # Classification example (multiple colors drawn) widget_classification = ScatterWidget() # Draw points with multiple colors (e.g., red, blue, green) X, y = widget_classification.data_as_X_y # X shape: (n_samples, 2) with x,y coordinates # y: color labels for each point # Train a classifier X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) clf = RandomForestClassifier(n_estimators=100, random_state=42) clf.fit(X_train, y_train) predictions = clf.predict(X_test) print(f"Classification accuracy: {accuracy_score(y_test, predictions):.3f}") # Regression example (single color drawn) widget_regression = ScatterWidget() # Draw points with a single color X_reg, y_reg = widget_regression.data_as_X_y # X_reg shape: (n_samples, 1) with x coordinates # y_reg: y coordinates as continuous targets # Train a regressor X_train, X_test, y_train, y_test = train_test_split(X_reg, y_reg, test_size=0.2) reg = LinearRegression() reg.fit(X_train, y_train) predictions = reg.predict(X_test) print(f"R² score: {r2_score(y_test, predictions):.3f}") ``` -------------------------------- ### BarWidget API Source: https://context7.com/koaning/drawdata/llms.txt The BarWidget allows users to draw bar chart data interactively. It supports multiple collections (e.g., different series) and custom binning, outputting data in raw format, pandas DataFrames, or polars DataFrames. ```APIDOC ## BarWidget ### Description Provides an interface for drawing bar chart data with multiple collections, useful for visualizing time series, distributions, or comparative data across categories. ### Method Instantiate `BarWidget` ### Endpoint N/A (Python Library) ### Parameters #### Initialization Parameters - **height** (int) - Optional - The height of the widget canvas. - **width** (int) - Optional - The width of the widget canvas. - **n_bins** (int) - Optional - The number of bins for the bar chart. - **collection_names** (list of str) - Optional - Names for different data collections. - **y_min** (float) - Optional - Minimum value for the y-axis. - **y_max** (float) - Optional - Maximum value for the y-axis. #### Properties - **data** (list) - Returns the raw data as a list of dictionaries, where each dictionary contains 'bin', 'value', and 'collection'. - **data_as_pandas** (pandas.DataFrame) - Returns the drawn data as a pandas DataFrame. - **data_as_polars** (polars.DataFrame) - Returns the drawn data as a polars DataFrame. ### Request Example ```python from drawdata import BarWidget # Create a bar widget with multiple collections and custom bins widget = BarWidget( height=400, width=700, n_bins=24, collection_names=["solar", "wind", "hydro"], y_min=0.0, y_max=100.0 ) # Display the widget widget ``` ### Response #### Success Response (Data Access) - **data** (list) - List of dictionaries, e.g., `[{'bin': 0, 'value': 45.2, 'collection': 'solar'}, ...]` - **data_as_pandas** (pandas.DataFrame) - DataFrame with columns like 'bin', 'value', 'collection'. - **data_as_polars** (polars.DataFrame) - Polars DataFrame with columns like 'bin', 'value', 'collection'. #### Response Example (data_as_pandas) ```python import pandas as pd df = widget.data_as_pandas print(df.head()) ``` ``` bin value collection 0 0 45.2 solar 1 1 32.8 solar 2 2 52.1 solar ``` ``` -------------------------------- ### JavaScript: Iframe Resizing with ResizeObserver Source: https://github.com/koaning/drawdata/blob/main/docs/index.html This JavaScript function resizes an iframe element to fit its content. It uses ResizeObserver to dynamically adjust the height when the content changes, ensuring no scrollbars are hidden. It requires the iframe element object as input. ```javascript function __resizeIframe(obj) { var scrollbarHeight = 20; // Max between windows, mac, and linux function setHeight() { var element = obj.contentWindow.document.documentElement; // If there is no vertical scrollbar, we don't need to resize the iframe if (element.scrollHeight === element.clientHeight) { return; } // Create a new height that includes the scrollbar height if it's visible var hasHorizontalScrollbar = element.scrollWidth > element.clientWidth; var newHeight = element.scrollHeight + (hasHorizontalScrollbar ? scrollbarHeight : 0); // Only update the height if it's different from the current height if (obj.style.height !== `${newHeight}px`) { obj.style.height = `${newHeight}px`; } } // Resize the iframe to the height of the content and bottom scrollbar height setHeight(); // Resize the iframe when the content changes const resizeObserver = new ResizeObserver((entries) => { setHeight(); }); resizeObserver.observe(obj.contentWindow.document.body); } ``` -------------------------------- ### Access and Analyze Data as Pandas DataFrame (Python) Source: https://context7.com/koaning/drawdata/llms.txt Shows how to obtain the drawn data from a ScatterWidget as a pandas DataFrame using the `data_as_pandas` property. It demonstrates common pandas operations like grouping, filtering, and calculating correlations on the generated dataset. ```Python from drawdata import ScatterWidget import pandas as pd widget = ScatterWidget(height=350, width=800) # After drawing some points in the widget # Get pandas DataFrame df = widget.data_as_pandas # Perform standard pandas operations summary = df.groupby('color').agg({ 'x': ['mean', 'std'], 'y': ['mean', 'std'], 'color': 'count' }) print(summary) # Filter by color red_points = df[df['color'] == '#ff0000'] # Calculate statistics correlation = df['x'].corr(df['y']) print(f"X-Y correlation: {correlation:.3f}") ``` -------------------------------- ### Integrate Data with Polars using BarWidget Source: https://context7.com/koaning/drawdata/llms.txt Shows how to convert drawn bar chart data into a Polars DataFrame using the `data_as_polars` property of BarWidget. This allows for efficient data manipulation and analysis using Polars' powerful API, including grouping, filtering, and calculating rolling statistics. ```python from drawdata import BarWidget import polars as pl widget = BarWidget( n_bins=48, collection_names=["demand", "supply"], height=400 ) # After drawing bar data # Get polars DataFrame df = widget.data_as_polars # Perform polars operations result = ( df .group_by(['bin', 'collection']) .agg(pl.col('value').mean().alias('avg_value')) .sort(['bin', 'collection']) ) print(result) # Filter and transform high_demand = ( df .filter(pl.col('collection') == 'demand') .filter(pl.col('value') > 50) .select(['bin', 'value']) ) # Calculate rolling statistics rolling_avg = ( df .sort('bin') .with_columns( pl.col('value') .rolling_mean(window_size=3) .over('collection') .alias('rolling_avg') ) ) print(rolling_avg) ``` -------------------------------- ### Create Stacked Bar Chart with Color Encoding in Python Source: https://github.com/koaning/drawdata/blob/main/docs/index.html This Python code snippet demonstrates how to create a stacked bar chart using the Drawdata library. It specifies the x-axis, y-axis (count), and color encoding. The chart is configured with a width of 60 pixels. ```python alt.X("count()", stack=None).title(""), alt.Color("color:N"), ).properties(width=60) out = top_hist & (points | right_hist) out return if __name__ == "__main__": app.run() ``` -------------------------------- ### ScatterWidget API Source: https://context7.com/koaning/drawdata/llms.txt The ScatterWidget allows users to interactively draw scatter plot data points. It supports multiple colors for classification tasks and can output data in raw format, pandas DataFrames, polars DataFrames, or as X, y arrays for scikit-learn. ```APIDOC ## ScatterWidget ### Description Allows users to draw scatter plot data points interactively by clicking or dragging on a canvas, with support for multiple colors to represent different classes. ### Method Instantiate `ScatterWidget` ### Endpoint N/A (Python Library) ### Parameters #### Initialization Parameters - **height** (int) - Optional - The height of the widget canvas. - **width** (int) - Optional - The width of the widget canvas. - **brushsize** (int) - Optional - The size of the drawing brush. #### Properties - **data** (list) - Returns the raw data as a list of dictionaries, where each dictionary contains 'x', 'y', and 'color'. - **data_as_pandas** (pandas.DataFrame) - Returns the drawn data as a pandas DataFrame. - **data_as_polars** (polars.DataFrame) - Returns the drawn data as a polars DataFrame. - **data_as_X_y** (tuple) - Returns data formatted for scikit-learn. For classification, returns (X, y) where X is an (n_samples, 2) array of coordinates and y is a list of color strings. For regression (single color), returns (X, y) where X is an (n_samples, 1) array of x-coordinates and y is an array of y-coordinates. ### Request Example ```python from drawdata import ScatterWidget # Create a scatter widget with custom dimensions widget = ScatterWidget(height=400, width=600, brushsize=30) # Display the widget in a Jupyter notebook widget ``` ### Response #### Success Response (Data Access) - **data** (list) - List of dictionaries, e.g., `[{'x': 150, 'y': 200, 'color': '#ff0000'}, ...]` - **data_as_pandas** (pandas.DataFrame) - DataFrame with columns like 'x', 'y', 'color'. - **data_as_polars** (polars.DataFrame) - Polars DataFrame with columns like 'x', 'y', 'color'. - **data_as_X_y** (tuple) - Tuple containing NumPy arrays suitable for machine learning. #### Response Example (data_as_pandas) ```python import pandas as pd df = widget.data_as_pandas print(df.head()) ``` ``` x y color 0 150 200 #ff0000 1 300 350 #0000ff ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.