### Setup Test Environment using Conda Source: https://datamapplot.readthedocs.io/en/latest/example_offline_fonts This sequence of commands sets up a Conda environment named 'datamapplot-test' from an 'environment_test.yml' file, activates it, and then installs the 'datamapplot' package as an editable installation. It concludes by installing the kernel for Jupyter. ```shell cd "/Users/keyu/Library/Mobile Documents/com~apple~CloudDocs/Coding/datamapplot" conda env create -f environment_test.yml conda activate datamapplot-test python -m ipykernel install --user --name datamapplot-test --display-name "DataMapPlot Test (Python 3.9)" ``` -------------------------------- ### Build HTML Documentation with Sphinx Source: https://datamapplot.readthedocs.io/en/latest/_sources/dev_docs This command sequence installs documentation dependencies, navigates to the doc directory, and builds the HTML documentation. The resulting documentation can be viewed by opening the _build/index.html file in a web browser. ```bash # Install documentation dependencies pip install -r doc/requirements.txt # Build HTML documentation cd doc make html # View the documentation (open _build/index.html in a browser) ``` -------------------------------- ### Manual Test Environment Setup Source: https://datamapplot.readthedocs.io/en/latest/example_offline_fonts This set of commands manually creates a Conda environment, activates it, installs core Python data science libraries and DataMapPlot, and then registers a Jupyter kernel. This method provides granular control over the setup process. ```shell # Create environment conda create -n datamapplot-test python=3.9 -y conda activate datamapplot-test # Install dependencies pip install numpy pandas matplotlib scikit-learn jupyter ipykernel pip install -e "/Users/keyu/Library/Mobile Documents/com~apple~CloudDocs/Coding/datamapplot" # Add to Jupyter python -m ipykernel install --user --name datamapplot-test --display-name "DataMapPlot Test (Python 3.9)" ``` -------------------------------- ### Load Example Data with Python Source: https://datamapplot.readthedocs.io/en/latest/size_controls Loads a pre-prepared data map and cluster labels from URLs using numpy and requests. This data is used for demonstrating DataMapPlot functionalities. Ensure 'numpy' and 'requests' are installed. ```python import numpy as np import requests import io data_map_file = requests.get("https://github.com/TutteInstitute/datamapplot/raw/main/examples/CORD19-subset-data-map.npy") cord19_data_map = np.load(io.BytesIO(data_map_file.content)) label_file = requests.get("https://github.com/TutteInstitute/datamapplot/raw/main/examples/CORD19-subset-cluster_labels.npy") cord19_labels = np.load(io.BytesIO(label_file.content), allow_pickle=True) ``` -------------------------------- ### Load Example Datasets for Interactive Plotting Source: https://datamapplot.readthedocs.io/en/latest/interactive_intro This code demonstrates how to download and load example datasets for interactive plotting from a GitHub repository. It fetches a data map and multiple layers of cluster labels, which are necessary for creating interactive visualizations. ```python import numpy as np import requests import io base_url = "https://github.com/TutteInstitute/datamapplot" data_map_file = requests.get( f"{base_url}/raw/main/examples/arxiv_ml_data_map.npy" ) arxivml_data_map = np.load(io.BytesIO(data_map_file.content)) arxivml_label_layers = [] for layer_num in range(5): label_file = requests.get( f"{base_url}/raw/interactive/examples/arxiv_ml_layer{layer_num}_cluster_labels.npy" ) arxivml_label_layers.append(np.load(io.BytesIO(label_file.content), allow_pickle=True)) ``` -------------------------------- ### Clone DataMapPlot Repository Source: https://datamapplot.readthedocs.io/en/latest/_sources/dev_docs Clones the DataMapPlot GitHub repository and navigates into the project directory. This is the first step in setting up the development environment. ```bash git clone https://github.com/TutteInstitute/datamapplot.git cd datamapplot ``` -------------------------------- ### Basic Plotting with DataMapper Plot Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_custom_cord19 Demonstrates how to create a simple plot using DataMapper Plot. This involves importing the library and calling the plot function with data and axis specifications. It's a fundamental example for getting started. ```python import datamapplot as dmp # Sample data data = { 'x': [1, 2, 3, 4, 5], 'y': [2, 4, 5, 4, 5] } # Create a plot dmp.plot(data, x='x', y='y', title='Simple Scatter Plot') ``` -------------------------------- ### Load Example Data for DataMapPlot Source: https://datamapplot.readthedocs.io/en/latest/interactive_customization_options Loads example datasets for DataMapPlot, including data maps, cluster labels, and hover data from a remote repository. This data is essential for demonstrating plot functionalities. ```python import numpy as np import requests import io base_url = "https://github.com/TutteInstitute/datamapplot" data_map_file = requests.get( f"{base_url}/raw/main/examples/arxiv_ml_data_map.npy" ) arxivml_data_map = np.load(io.BytesIO(data_map_file.content)) arxivml_label_layers = [] for layer_num in range(5): label_file = requests.get( f"{base_url}/raw/interactive/examples/arxiv_ml_layer{layer_num}_cluster_labels.npy" ) arxivml_label_layers.append(np.load(io.BytesIO(label_file.content), allow_pickle=True)) hover_data_file = requests.get( f"{base_url}/raw/interactive/examples/arxiv_ml_hover_data.npy" ) arxiv_hover_data = np.load(io.BytesIO(hover_data_file.content), allow_pickle=True) ``` -------------------------------- ### Install Python Dependencies for Development Source: https://datamapplot.readthedocs.io/en/latest/_sources/dev_docs Installs the DataMapPlot package in development mode along with testing and documentation dependencies using pip. Requires Python 3.10 or newer. ```bash # Install the package in development mode pip install -e . # Install testing dependencies pip install -r test-requirements.txt # For documentation development pip install -r doc/requirements.txt ``` -------------------------------- ### Basic Data Map Plotting with Python Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Demonstrates a simple data map plot using the datamapplot Python library. This example requires the library to be installed and assumes you have data in a pandas DataFrame. The output is a static map visualization. ```python import pandas as pd from datamapplot import DataMapPlot # Sample data data = { 'lat': [40.7128, 34.0522, 41.8781], 'lon': [-74.0060, -118.2437, -87.6298], 'value': [10, 20, 15] } df = pd.DataFrame(data) # Create a DataMapPlot instance dmp = DataMapPlot(df, 'lat', 'lon', 'value') # Generate and display the plot dmp.plot() ``` -------------------------------- ### Install Node.js and Playwright Dependencies Source: https://datamapplot.readthedocs.io/en/latest/_sources/dev_docs Installs Node.js dependencies and Playwright for interactive tests within the 'interactive_tests' directory. This step is necessary for running interactive tests. ```bash cd datamapplot/interactive_tests npm ci npx playwright install --with-deps ``` -------------------------------- ### Load Example Data for Datamapplot Source: https://datamapplot.readthedocs.io/en/latest/label_over_points This snippet demonstrates how to fetch and load example data, specifically a data map and corresponding cluster labels, from a remote GitHub repository using requests and numpy. This data is essential for generating plots with the datamapplot library. ```python import numpy as np import requests import io data_map_file = requests.get( "https://github.com/TutteInstitute/datamapplot/raw/main/examples/arxiv_ml_data_map.npy" ) arxivml_data_map = np.load(io.BytesIO(data_map_file.content)) label_file = requests.get( "https://github.com/TutteInstitute/datamapplot/raw/main/examples/arxiv_ml_cluster_labels.npy" ) arxivml_labels = np.load(io.BytesIO(label_file.content), allow_pickle=True) ``` -------------------------------- ### Python Data Mapping and Plotting Example Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree This snippet demonstrates how to use DataMapperPlot in Python to create a data map. It involves defining data sources, mapping them to visual elements, and generating a plot. Ensure the DataMapperPlot library is installed. ```python from datamapplot import DataMapperPlot # Sample data data = { "id": [1, 2, 3], "value": [10, 20, 30], "category": ["A", "B", "A"] } # Create a DataMapperPlot instance dmp = DataMapperPlot(data) # Map data to a color scale (example) dmp.map_color("value", scale="linear", domain=[0, 40], range=["blue", "red"]) # Map data to a size scale (example) dmp.map_size("value", scale="linear", domain=[0, 40], range=[5, 15]) # Create a plot (example using a generic plot function, replace with actual plotting if available) # plot = dmp.plot() # For demonstration, let's print the internal representation of the mappings print(dmp.get_mappings()) ``` -------------------------------- ### Install DataMapPlot using pip Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_cord19 This command installs the DataMapPlot library and its dependencies using pip, the Python package installer. Ensure you have pip installed and updated before running this command. ```bash pip install datamapplot ``` -------------------------------- ### Setup Test Environment using Script Source: https://datamapplot.readthedocs.io/en/latest/example_offline_fonts This shell script navigates to the project directory and executes the setup_test_env.sh script to configure the testing environment. It's a quick way to prepare for running DataMapPlot tests. ```shell cd "/Users/keyu/Library/Mobile Documents/com~apple~CloudDocs/Coding/datamapplot" ./setup_test_env.sh ``` -------------------------------- ### Install DataMapPlot using pip Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_cord19 This command installs the DataMapPlot library and its dependencies using pip, the Python package installer. Ensure you have Python and pip installed on your system. ```bash pip install datamapplot ``` -------------------------------- ### Python: Basic Plotting with DataMapperPlot Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Demonstrates the fundamental usage of DataMapperPlot to create a basic plot. This snippet assumes the library is installed and shows how to initialize a plot and add data. ```python from datamapplot import DataMapperPlot data = [ {'x': 1, 'y': 2, 'label': 'A'}, {'x': 3, 'y': 4, 'label': 'B'}, {'x': 5, 'y': 1, 'label': 'C'} ] dmp = DataMapperPlot(data=data) dmp.plot(x='x', y='y', label='label') dmp.show() ``` -------------------------------- ### Basic Plotting with DataMapper Plot (Python) Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml Demonstrates a fundamental plotting operation using the DataMapper Plot library in Python. This example assumes the library has been installed and imports necessary components. ```python from datamapplot import DataMapperPlot # Assuming you have data loaded into a suitable format data = [...] # Create a DataMapperPlot instance dmp = DataMapperPlot() # Generate a plot dmp.plot(data) ``` -------------------------------- ### Data Visualization Setup (JavaScript) Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml This code snippet illustrates how to initialize a visualization component using JavaScript, likely part of a web-based data visualization framework. It sets up a container for the visualization. ```javascript const container = document.getElementById('visualization-container'); // Further initialization code for the visualization would follow ``` -------------------------------- ### Create Data Map Plot with Font Options Source: https://datamapplot.readthedocs.io/en/latest/auto_examples/example_use_system_fonts This Python code demonstrates how to create data map plots using the datamapplot library. It illustrates the difference between using Google Fonts (default behavior) and exclusively using system fonts via the 'use_system_fonts' parameter. The code generates sample data, creates two plots with different font settings, and saves them as PNG files. Ensure necessary libraries like numpy and datamapplot are installed. The output includes generated PNG files and console messages indicating the process. ```python import numpy as np import datamapplot # Generate example data np.random.seed(42) n_samples = 1000 n_clusters = 5 # Create cluster centers centers = np.random.randn(n_clusters, 2) * 10 # Generate data points around centers data_coords = [] labels = [] for i, center in enumerate(centers): n_points = n_samples // n_clusters cluster_data = np.random.randn(n_points, 2) + center data_coords.append(cluster_data) labels.extend([f"Cluster {i+1}"] * n_points) # Add some noise points noise_points = np.random.uniform(-15, 15, (n_samples // 10, 2)) data_coords.append(noise_points) labels.extend(["Unlabelled"] * len(noise_points)) # Combine all data data_coords = np.vstack(data_coords) labels = np.array(labels) print("Creating plot with Google Fonts download (default behavior)...") fig1, ax1 = datamapplot.create_plot( data_coords, labels, title="With Google Fonts", sub_title="This plot attempts to download fonts from Google", font_family="Roboto", use_system_fonts=False, # Default behavior verbose=True ) fig1.savefig("example_with_google_fonts.png", dpi=150, bbox_inches='tight') print("\nCreating plot with system fonts only...") fig2, ax2 = datamapplot.create_plot( data_coords, labels, title="With System Fonts Only", sub_title="This plot uses only locally installed fonts", font_family="Arial", # Use a common system font use_system_fonts=True, # Skip Google Fonts download verbose=True ) fig2.savefig("example_with_system_fonts.png", dpi=150, bbox_inches='tight') print("\nDone! Check the generated PNG files to see the difference.") print("Note: When use_system_fonts=True, make sure to specify fonts that are installed on your system.") ``` -------------------------------- ### Create Plot Using Pathlib.Path Objects Source: https://datamapplot.readthedocs.io/en/latest/auto_examples/example_offline_data_path Shows how to utilize `pathlib.Path` objects for specifying the `offline_data_path` when creating an interactive plot. The library automatically handles directory creation. This example demonstrates flexible path management for saving plot-related files. Dependencies include datamapplot and pathlib. ```python import numpy as np import datamapplot from pathlib import Path # (Assuming data_coords and labels are already generated as in Example 1) # Example 3: Using Path objects print("\nExample 3: Using pathlib.Path objects") output_path = Path("visualizations") / "datamaps" / "analysis_2025" fig3 = datamapplot.create_interactive_plot( data_coords, labels, inline_data=False, offline_data_path=output_path, title="Example with Path object" ) # The directory is automatically created fig3.save(str(output_path.parent / "analysis_2025.html")) print(f"Files saved to: {output_path.parent}") ``` -------------------------------- ### Load Example Data for DataMapPlot Source: https://datamapplot.readthedocs.io/en/latest/colour_controls Loads sample data map and cluster labels from the DataMapPlot repository for demonstration purposes. This involves fetching data from URLs and using numpy to load the binary files. ```python import numpy as np import requests import io data_map_file = requests.get( "https://github.com/TutteInstitute/datamapplot/raw/main/examples/CORD19-subset-data-map.npy" ) cord19_data_map = np.load(io.BytesIO(data_map_file.content)) label_file = requests.get( "https://github.com/TutteInstitute/datamapplot/raw/main/examples/CORD19-subset-cluster_labels.npy" ) cord19_labels = np.load(io.BytesIO(label_file.content), allow_pickle=True) ``` -------------------------------- ### Basic Plotting with Python (Seaborn) Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_custom_cord19 An example of creating basic statistical plots using Python's Seaborn library, which is built on top of Matplotlib. This snippet requires both Seaborn and Matplotlib to be installed. ```python import seaborn as sns import matplotlib.pyplot as plt # Load a sample dataset tips = sns.load_dataset("tips") # Create a scatter plot sns.scatterplot(data=tips, x="total_bill", y="tip", hue="sex") plt.title('Total Bill vs Tip by Sex') plt.xlabel('Total Bill ($)') plt.ylabel('Tip ($)') plt.show() ``` -------------------------------- ### Demonstrate use_system_fonts Parameter in DataMapPlot Source: https://datamapplot.readthedocs.io/en/latest/auto_examples/index This example demonstrates how to use the `use_system_fonts` parameter in DataMapPlot. This parameter helps to avoid the automatic downloading of fonts, which can be useful in certain environments or for offline usage. The code is written in Python. ```python sphx_glr_auto_examples_example_use_system_fonts.py ``` -------------------------------- ### Install DataMapper Plot using pip Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_cord19 This snippet shows the command to install the DataMapper Plot library using pip, the standard package installer for Python. Ensure you have pip installed and accessible in your environment. ```bash pip install datamapper-plot ``` -------------------------------- ### Run Backend Tests with Makefile Source: https://datamapplot.readthedocs.io/en/latest/_sources/dev_docs Command to execute all unit and backend tests for DataMapPlot using the project's Makefile. These tests are a prerequisite for interactive frontend tests as they generate necessary HTML files. ```bash make test-backend ``` -------------------------------- ### Import DataMapPlot library Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_custom_cord19 This example shows the standard way to import the DataMapPlot library in a Python script. It is aliased as 'dmp' for brevity, which is a common convention. ```python import datamapplot as dmp ``` -------------------------------- ### Create Basic DataMapPlot Visualization Source: https://datamapplot.readthedocs.io/en/latest/placement_controls Generates a basic DataMapPlot visualization using the provided data map and labels. This serves as a starting point to understand the default output before applying customizations. ```python import datamapplot datamapplot.create_plot(wikipedia_data_map, wikipedia_labels) ``` -------------------------------- ### Python: Handling Large Datasets Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Shows an example of using DataMapperPlot with a larger dataset, potentially demonstrating optimizations or best practices for performance when dealing with more data points. ```python import numpy as np from datamapplot import DataMapperPlot x_data = np.random.rand(1000) y_data = np.random.rand(1000) labels = [f'Point_{i}' for i in range(1000)] data = [{'x': x, 'y': y, 'label': l} for x, y, l in zip(x_data, y_data, labels)] dmp = DataMapperPlot(data=data) dmp.plot(x='x', y='y', label='label', marker='.', markersize=5) dmp.show() ``` -------------------------------- ### Run Static Frontend Tests with Makefile Source: https://datamapplot.readthedocs.io/en/latest/_sources/dev_docs Commands to execute static frontend visual regression tests and open their reports using the Makefile. These tests compare generated static outputs with baseline images using pytest-mpl. ```bash # Run static tests make test-static # Open the mpl test report make report-static ``` -------------------------------- ### Data Visualization with Seaborn (Python) Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Illustrates creating statistical visualizations using Seaborn in Python. This example generates a distribution plot (histogram) to visualize the distribution of a dataset. ```python import seaborn as sns import matplotlib.pyplot as plt import numpy as np data = np.random.randn(100) sns.histplot(data, kde=True) plt.title("Distribution Plot") plt.xlabel("Value") plt.ylabel("Frequency") plt.show() ``` -------------------------------- ### Data Transformation Example (Python) Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml Illustrates a data transformation process using Python, possibly involving libraries like Pandas or NumPy. This snippet focuses on preparing data before visualization. ```python import pandas as pd # Load data into a Pandas DataFrame df = pd.read_csv('data.csv') # Perform transformations (e.g., filtering, aggregation) processed_df = df[df['value'] > 10].groupby('category').mean() ``` -------------------------------- ### Example Firewall Scenario Plot (Python) Source: https://datamapplot.readthedocs.io/en/latest/_sources/offline_fonts A complete example demonstrating DataMapPlot usage in a restricted environment, like behind a firewall, by enabling `use_system_fonts=True`. It includes data generation using `make_blobs` from scikit-learn and data preparation for plotting. This snippet highlights practical application in challenging network conditions. ```python import datamapplot import numpy as np from sklearn.datasets import make_blobs # Generate sample clustered data X, y = make_blobs(n_samples=1000, centers=5, n_features=2, random_state=42) # Map numeric labels to categories # (Assuming you would have category mapping logic here) # For demonstration, let's just use the numeric labels as categories labels = y.astype(str) # Create a plot using system fonts for firewall scenario fig, ax = datamapplot.create_plot( X, # Use X for coordinates labels, title="Firewall Environment Plot", font_family="Verdana", use_system_fonts=True ) ``` -------------------------------- ### Makefile Test Rules for DataMapPlot Source: https://datamapplot.readthedocs.io/en/latest/_sources/dev_docs This snippet displays the available rules in the Makefile for running various types of tests and generating reports for DataMapPlot. It's used to understand and execute different testing scenarios. ```none *** AVAILABLE RULES *** test Run all tests test-static Run python based backend and static frontend tests test-backend Run python based backend tests test-ui Run interactive frontend tests test-ui-fast Run interactive frontend tests, not slow tests report-static Open the mpl static test report report-interactive Open the playwright test report update-static-baseline Update static baseline images update-interactive-baseline Update interactive baseline images ``` -------------------------------- ### Data Visualization with Python (Matplotlib) Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_custom_cord19 Demonstrates how to create data visualizations using Python's Matplotlib library, a common tool for plotting and graphical representation. This snippet requires the Matplotlib library to be installed. ```python import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.figure(figsize=(8, 6)) plt.plot(x, y, label='sin(x)', color='blue', linestyle='-') plt.title('Sine Wave Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.legend() plt.grid(True) plt.show() ``` -------------------------------- ### Run Interactive Frontend Tests with Makefile Source: https://datamapplot.readthedocs.io/en/latest/_sources/dev_docs Commands to run interactive frontend tests using Playwright and access their reports via the Makefile. These tests verify browser-based interactive features and can be run fully or with a 'fast' option. ```bash # Run all interactive tests make test-ui # Run only fast interactive tests make test-ui-fast # Open the playwright test report make report-interactive ``` -------------------------------- ### Basic Plotting with Matplotlib Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_cord19 Demonstrates a fundamental plotting example using Matplotlib. This involves importing the library, creating sample data, and generating a simple line plot. Matplotlib is a widely-used plotting library in Python. ```python import matplotlib.pyplot as plt import numpy as np # Sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Create plot plt.figure(figsize=(8, 6)) plt.plot(x, y, label='sin(x)') plt.title('Simple Sine Wave Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.legend() plt.grid(True) plt.show() ``` -------------------------------- ### Setup Expand All/Collapse All Handler Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Manages the 'Expand All' and 'Collapse All' functionality. It toggles the visibility of all nested lists and updates the caret states accordingly. The button's text and data attribute are updated to reflect the current state. ```javascript setupExpandAllHandler() { this.expandAllBtn.addEventListener('click', function() { const isExpanded = this.dataset.expanded === 'true'; const carets = document.querySelectorAll('.caret'); carets.forEach(caret => { const nestedList = getNextSibling(caret, '.nested'); if (isExpanded) { caret.classList.remove('caret-down'); if (nestedList) { nestedList.classList.remove('active'); } } else { caret.classList.add('caret-down'); if (nestedList) { nestedList.classList.add('active'); } } }); this.dataset.expanded = (!isExpanded).toString(); this.textContent = isExpanded ? 'Expand All' : 'Collapse All'; }); } ``` -------------------------------- ### Initialize DataMap with Bounds and Viewport Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Initializes a new DataMap instance, setting up the deck.gl container, initial viewport state based on provided bounds, and data selection manager. It calculates the initial zoom level and center coordinates for the map. ```javascript class DataMap { constructor({container, bounds, searchItemId = "text-search", lassoSelectionItemId = "lasso-selection", }) { this.container = container; this.searchItemId = searchItemId; this.lassoSelectionItemId = lassoSelectionItemId; this.pointData = null; this.labelData = null; this.metaData = null; this.layers = []; const { viewportWidth, viewportHeight } = getInitialViewportSize(); const { zoomLevel, dataCenter } = calculateZoomLevel(bounds, viewportWidth, viewportHeight); this.deckgl = new deck.DeckGL({ container: container, initialViewState: { latitude: dataCenter[1], longitude: dataCenter[0], zoom: zoomLevel }, controller: { scrollZoom: { speed: 0.01, smooth: true } }, }); this.updateTriggerCounter = 0; this.dataSelectionManager = new DataSelectionManager(lassoSelectionItemId); } ``` -------------------------------- ### Python: Customizing Plot Appearance with DataMapperPlot Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml This example showcases how to customize the appearance of plots generated by DataMapperPlot in Python. Users can modify elements like colors, labels, and markers using arguments passed to the plotting function. This allows for tailored visualizations. Ensure DataMapperPlot is installed. ```python from datamapperplot import DataMapperPlot # Sample data data = {'x': [1, 2, 3, 4, 5], 'y': [2, 3, 5, 7, 11]} # Create a DataMapperPlot object dmp = DataMapperPlot() # Generate a plot with custom appearance dmp.plot(data, x='x', y='y', title='Customized Plot', color='red', marker='o', linestyle='--') dmp.show() ``` -------------------------------- ### Basic Scatter Plot Creation in Python Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Demonstrates how to create a simple scatter plot using DataMapperPlot. This requires importing the library and preparing sample data. The output is a basic visualization of data points. ```python import datamapplot as dmplt data = { 'x': [1, 2, 3, 4, 5], 'y': [2, 3, 5, 7, 11] } plot = dmplt.scatter(data, x='x', y='y') plot.show() ``` -------------------------------- ### Initialize DataMap with DeckGL Container Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_custom_cord19 Initializes the DataMap class, setting up the deck.gl container, initial viewport, and data selection manager. It takes a container element and optional IDs for search and lasso selection elements. ```javascript class DataMap{ constructor({ container, bounds, searchItemId="text-search", lassoSelectionItemId="lasso-selection", }) { this.container = container; this.searchItemId = searchItemId; this.lassoSelectionItemId = lassoSelectionItemId; this.pointData = null; this.labelData = null; this.metaData = null; this.layers = []; const { viewportWidth, viewportHeight } = getInitialViewportSize(); const { zoomLevel, dataCenter } = calculateZoomLevel(bounds, viewportWidth, viewportHeight); this.deckgl = new deck.DeckGL({ container: container, initialViewState: { latitude: dataCenter[1], longitude: dataCenter[0], zoom: zoomLevel, }, controller: { scrollZoom: { speed: 0.01, smooth: true, }, }, }); this.updateTriggerCounter = 0; this.dataSelectionManager = new DataSelectionManager(lassoSelectionItemId); } // ... other methods ``` -------------------------------- ### Get and Set DataMapPlot Configuration Values Source: https://datamapplot.readthedocs.io/en/latest/_sources/configuration Demonstrates how to get and set configuration values using the `ConfigManager` instance, which behaves like a dictionary. This allows dynamic modification of plot settings through Python code. ```python print(cfg["dpi"]) cfg["font_family"] = "Roboto" ``` -------------------------------- ### Initialize DataMapperPlot Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_custom_cord19 This snippet shows how to initialize the DataMapperPlot library, setting up the necessary configurations for plotting and mapping functionalities. It typically involves importing the library and calling an initialization function. ```javascript import DataMapperPlot from "datamapperplot"; const plot = new DataMapperPlot({ // Configuration options here width: 800, height: 600, margin: { top: 20, right: 30, bottom: 40, left: 40 } }); ``` -------------------------------- ### Basic Map Plotting with DataMapPlot (Python) Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_cord19 Demonstrates how to create a basic geographical map using DataMapPlot. This involves importing the library, preparing data (e.g., coordinates, values), and plotting the map. No external dependencies are strictly required for this basic example, but geographical data files might be needed for real-world use. ```python import datamapplot as dmp # Sample data (replace with your actual data) data = [ {'lat': 40.7128, 'lon': -74.0060, 'value': 10}, {'lat': 34.0522, 'lon': -118.2437, 'value': 20}, {'lat': 41.8781, 'lon': -87.6298, 'value': 15} ] # Create a map plot dmp.plot_map(data, 'value', lat_col='lat', lon_col='lon') # To save the plot (optional) # dmp.save_plot('my_map.html') ``` -------------------------------- ### Configuration File Loading in Python Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_cord19 Shows how to load configuration settings from a JSON file in Python. This is a standard practice for managing application settings. ```python import json def load_config(filepath): with open(filepath, 'r') as f: config = json.load(f) return config ``` -------------------------------- ### Demonstrate offline_data_path Parameter in DataMapPlot Source: https://datamapplot.readthedocs.io/en/latest/auto_examples/index This example illustrates the usage of the `offline_data_path` parameter in DataMapPlot. This parameter offers enhanced control over data paths, particularly useful for managing data in an offline environment. The code is written in Python. ```python sphx_glr_auto_examples_example_offline_data_path.py ``` -------------------------------- ### Utility Functions for DataMap Initialization and Font Loading Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Provides essential JavaScript utility functions for the DataMapPlot library. These include functions to determine the layer order, check if a font is loaded, wait for a font to load with a timeout, get the initial viewport size, and calculate the appropriate zoom level and data center based on geographical bounds and viewport dimensions. ```javascript LAYER_ORDER=['imageLayer','dataPointLayer','boundaryLayer','labelLayer'];function getLayerIndex(object){return LAYER_ORDER.indexOf(object.id);} function isFontLoaded(fontName){return document.fonts.check(`12px "${fontName}"`);} function waitForFont(fontName,maxWait=500){return new Promise((resolve,reject)=>{if(isFontLoaded(fontName)){resolve();}else{const startTime=Date.now();const interval=setInterval(()=>{if(isFontLoaded(fontName)){clearInterval(interval);resolve();}else if(Date.now()-startTime>maxWait){clearInterval(interval);reject(new Error(`Font ${fontName} did not load within ${maxWait}ms`));}},50);}});} function getInitialViewportSize(){const width=document.documentElement.clientWidth;const height=document.documentElement.clientHeight;return{viewportWidth:width,viewportHeight:height};} function calculateZoomLevel(bounds,viewportWidth,viewportHeight,padding=0.5){const lngRange=bounds[1]-bounds[0];const latRange=bounds[3]-bounds[2];const centerLng=(bounds[0]+bounds[1])/2;const centerLat=(bounds[2]+bounds[3])/2;const zoomX=Math.log2(360/(lngRange/(viewportWidth/256)));const zoomY=Math.log2(180/(latRange/(viewportHeight/256)));const zoom=Math.min(zoomX,zoomY)-padding;return{zoomLevel:zoom,dataCenter:[centerLng,centerLat]};} ``` -------------------------------- ### Example: Offline Firewall Plot - DataMapPlot Source: https://datamapplot.readthedocs.io/en/latest/offline_fonts A complete example demonstrating how to create a DataMapPlot plot for users working behind firewalls or in restricted network environments. It uses `use_system_fonts=True` and common system fonts like 'Arial' to ensure the plot renders without external resource dependencies. ```python import datamapplot import numpy as np from sklearn.datasets import make_blobs # Generate sample clustered data X, y = make_blobs(n_samples=1000, centers=5, n_features=2, random_state=42) # Map numeric labels to categories label_names = ['Research', 'Development', 'Production', 'Testing', 'Documentation'] labels = np.array([label_names[i] for i in y]) # Create plot for offline use fig, ax = datamapplot.create_plot( X, labels, title="Project Classification Map", sub_title="Internal data visualization - no external resources needed", font_family="Arial", # Safe choice for most systems use_system_fonts=True, darkness=0.5, figsize=(12, 10) ) ``` -------------------------------- ### Demonstrate Offline Mode with Custom Font File Paths Source: https://datamapplot.readthedocs.io/en/latest/auto_examples/index This example shows how to use DataMapPlot in offline mode, specifically demonstrating how to manage custom font file paths. This is beneficial when you need to use local font files instead of relying on external sources. The code is written in Python. ```python sphx_glr_auto_examples_example_offline_custom_font_file.py ``` -------------------------------- ### Get Current Selected Indices Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree This method returns the currently selected indices managed by the `dataSelectionManager`. It directly accesses the `selectedIndicesCommon` property of the `dataSelectionManager`. ```javascript getSelectedIndices(){return this.dataSelectionManager.getSelectedIndices();} ``` -------------------------------- ### Create Basic DataMapPlot Visualization in Python Source: https://datamapplot.readthedocs.io/en/latest/size_controls Generates the most basic DataMapPlot output using the loaded data map and labels. This serves as a baseline for understanding the effects of various customization options. Requires the 'datamapplot' library. ```python import datamapplot datamapplot.create_plot(cord19_data_map, cord19_labels) ``` -------------------------------- ### Python: Create Interactive Plot with Custom Font Cache Source: https://datamapplot.readthedocs.io/en/latest/auto_examples/example_offline_custom_font_file This Python script demonstrates how to create an interactive data map plot in offline mode using custom font and JavaScript cache files. It generates sample data, creates temporary cache files with placeholder content, and then uses `datamapplot.create_interactive_plot` with specific offline mode parameters. The output is saved as an HTML file. This example addresses an issue where offline mode failed when specifying individual font files. ```python import numpy as np import datamapplot import tempfile import json from pathlib import Path # Generate example data np.random.seed(42) n_samples = 1000 n_clusters = 5 # Create cluster centers centers = np.random.randn(n_clusters, 2) * 10 # Generate data points around centers data_coords = [] labels = [] for i, center in enumerate(centers): n_points = n_samples // n_clusters cluster_data = np.random.randn(n_points, 2) + center data_coords.append(cluster_data) labels.extend([f"Cluster {i+1}"] * n_points) # Add some noise points noise_points = np.random.uniform(-15, 15, (n_samples // 10, 2)) data_coords.append(noise_points) labels.extend(["Unlabelled"] * len(noise_points)) # Combine all data data_coords = np.vstack(data_coords) labels = np.array(labels) print("Creating example with custom font cache file...") # Create a temporary directory for demonstration with tempfile.TemporaryDirectory() as temp_dir: # Path for our custom font cache custom_font_file = Path(temp_dir) / "my_custom_fonts.json" # Create a minimal font cache (in practice, you'd use dmp_offline_cache to generate this) font_cache = { "Roboto": [{"style": "normal", "weight": "400", "unicode_range": "", "type": "woff2", "content": "d09GMgABAAAAAAIAAA4AAAAAA..." # Truncated for example }] } with open(custom_font_file, 'w') as f: json.dump(font_cache, f) print(f"Created custom font cache at: {custom_font_file}") # Also need a JS cache file for offline mode js_cache_file = Path(temp_dir) / "my_js_cache.json" js_cache = { "https://unpkg.com/deck.gl@latest/dist.min.js": { "encoded_content": "ZGVja2dsX2NvbnRlbnQ=", # Placeholder "name": "unpkg_com_deck_gl_latest_dist_min_js" } } with open(js_cache_file, 'w') as f: json.dump(js_cache, f) try: # Create interactive plot with custom font file fig = datamapplot.create_interactive_plot( data_coords, labels, title="Offline Mode with Custom Font File", sub_title="Using specified font cache file instead of default location", font_family="Roboto", inline_data=False, offline_mode=True, offline_mode_font_data_file=str(custom_font_file), offline_mode_js_data_file=str(js_cache_file), offline_data_path=temp_dir / "plot_data" ) # Save the plot output_file = Path(temp_dir) / "offline_custom_font_plot.html" fig.save(str(output_file)) print(f"\nSuccess! Plot saved to: {output_file}") print("\nThis demonstrates the fix for issue #112:") print("- Offline mode now correctly uses specified font file paths") print("- No longer defaults to potentially non-existent cache locations") except Exception as e: print(f"\nError: {e}") print("\nNote: For a real use case, you would:") print("1. Use 'dmp_offline_cache' to create proper font/JS cache files") print("2. Store them in your desired location") print("3. Reference them using the offline_mode_*_data_file parameters") ``` -------------------------------- ### ArXiv ML Word Cloud Plot Generation with Python Source: https://datamapplot.readthedocs.io/en/latest/auto_examples/plot_arxiv_ml_word_cloud Generates a word cloud style data map plot using the ArXiv ML dataset. It requires libraries such as datamapplot, numpy, requests, PIL, matplotlib, and colorcet. The script loads data, fetches a logo, creates the plot with customizable parameters, and saves it as a PNG file. ```python import datamapplot import numpy as np import requests import PIL import matplotlib.pyplot as plt import colorcet plt.rcParams['savefig.bbox'] = 'tight' arxivml_data_map = np.load("arxiv_ml_data_map.npy") arxivml_labels = np.load("arxiv_ml_cluster_labels.npy", allow_pickle=True) arxiv_logo_response = requests.get( "https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/ArXiv_logo_2022.svg/320px-ArXiv_logo_2022.svg.png", stream=True, headers={'User-Agent': 'My User Agent 1.0'} ) arxiv_logo = np.asarray(PIL.Image.open(arxiv_logo_response.raw)) fig, ax = datamapplot.create_plot( arxivml_data_map, arxivml_labels, title="ArXiv ML Landscape", sub_title="A data map of papers from the Machine Learning section of ArXiv", label_wrap_width=10, label_over_points=True, dynamic_label_size=True, max_font_size=36, min_font_size=4, min_font_weight=100, max_font_weight=1000, font_family="Roboto Condensed", cmap=colorcet.cm.CET_C2, logo=arxiv_logo, logo_width=0.1, ) fig.savefig("plot_arxiv_ml.png", bbox_inches="tight") plt.show() ``` -------------------------------- ### Data Transformation in Python Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_cord19 Demonstrates data transformation capabilities within DataMapperPlot (Python). This example shows how to apply a simple transformation before plotting. ```python from datamapperplot import Plot # Sample data data = { 'x': [1, 2, 3, 4, 5], 'y': [2, 3, 5, 7, 11] } # Define a transformation function (e.g., square root) def sqrt_transform(values): import math return [math.sqrt(v) for v in values] # Create a plot object plot = Plot() # Add a scatter plot layer with transformation plot.add_layer('scatter', data=data, transform={'y': sqrt_transform}) # Set plot title plot.set_title('Plot with Transformed Data') # Save the plot plot.save('transformed_data_plot.png') ``` -------------------------------- ### Generating Heatmaps with Seaborn (Python) Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Provides a code example for creating heatmaps using Seaborn in Python. Heatmaps are useful for visualizing matrix-like data and identifying patterns. ```python import seaborn as sns import matplotlib.pyplot as plt import numpy as np data = np.random.rand(10, 12) sns.heatmap(data, annot=True, fmt=".2f", cmap="viridis") plt.title("Sample Heatmap") plt.xlabel("Columns") plt.ylabel("Rows") plt.show() ``` -------------------------------- ### Configure DataMapPlot Plotting Options Source: https://datamapplot.readthedocs.io/en/latest/customization This snippet demonstrates basic configuration options for DataMapPlot, including setting highlight labels, font sizes, and styling for highlighted keywords. It shows how to define the appearance of labels and their associated keyword styles. No external libraries are strictly required for this configuration, but the `arxiv_logo` is assumed to be defined elsewhere. ```python highlight_labels=[ "Clustering", "Manifold learning and dimension reduction", "Active learning", "Topic modelling and text classification" ], label_font_size=8, highlight_label_keywords={"fontsize": 12, "fontweight": "bold", "bbox":{"boxstyle":"circle", "pad":0.75}}, logo=arxiv_logo, ) ``` -------------------------------- ### Interactive Plotting with Plotly (JavaScript) Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml_topic_tree Shows how to create interactive plots using Plotly.js in a web environment. This example focuses on generating a scatter plot that can be manipulated by the user. ```javascript const data = [ { x: [1, 2, 3, 4, 5], y: [1, 4, 9, 16, 25], mode: 'markers', type: 'scatter' } ]; const layout = { title: 'Interactive Scatter Plot', xaxis: { title: 'X Values' }, yaxis: { title: 'Y Values' } }; Plotly.newPlot('myDiv', data, layout); ``` -------------------------------- ### Data Transformation in Python Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_cord19 Illustrates a data transformation process using Python. This example focuses on converting data types and restructuring a list of dictionaries for further processing. ```python def transform_records(records): transformed = [] for record in records: transformed.append({ 'record_id': str(record['id']), 'full_name': f"{record['first_name']} {record['last_name']}", 'is_active': bool(record['status'] == 'active') }) return transformed ``` -------------------------------- ### DataMap Class Initialization Source: https://datamapplot.readthedocs.io/en/latest/_sources/auto_examples/plot_interactive_arxiv_ml Initializes the DataMap class, setting up the deck.gl instance with calculated initial view state based on provided bounds. It also sets up event listeners for interactions like scrolling and zooming. Dependencies include the `deck` library and utility functions like `getInitialViewportSize` and `calculateZoomLevel`. ```javascript class DataMap{ constructor({container,bounds,searchItemId="text-search",lassoSelectionItemId="lasso-selection",}){ this.container=container; this.searchItemId=searchItemId; this.lassoSelectionItemId=lassoSelectionItemId; this.pointData=null; this.labelData=null; this.metaData=null; this.layers=[]; const{viewportWidth,viewportHeight}=getInitialViewportSize(); const{zoomLevel,dataCenter}=calculateZoomLevel(bounds,viewportWidth,viewportHeight); this.deckgl=new deck.DeckGL({ container:container, initialViewState:{ latitude:dataCenter[1], longitude:dataCenter[0], zoom:zoomLevel }, controller:{ scrollZoom:{ speed:0.01, smooth:true } } }); this.updateTriggerCounter=0; this.dataSelectionManager=new DataSelectionManager(lassoSelectionItemId); } ```