### Run Local Web Server (Python 2) Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Home This command starts a simple HTTP server in the current directory using Python 2. It's used to serve the RAW application locally for development or testing. Ensure Python 2 is installed. ```python python -m SimpleHTTPServer 4000 ``` -------------------------------- ### Install Client-Side Dependencies (Shell) Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Home This command installs the necessary client-side dependencies for the RAW application using Bower. Bower must be installed globally. ```sh bower install ``` -------------------------------- ### Run Local Web Server (Python 3) Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Home This command starts a simple HTTP server in the current directory using Python 3. It's used to serve the RAW application locally for development or testing. Ensure Python 3 is installed. ```python python -m http.server 4000 ``` -------------------------------- ### Install Project Dependencies (Shell) Source: https://github.com/rawgraphs/rawgraphs-app/blob/master/README.md Installs all the necessary project dependencies using Yarn, a package manager for Node.js. This command must be run after cloning the repository and navigating into the project directory. ```shell yarn install ``` -------------------------------- ### Start RAWGraphs Development Server (Shell) Source: https://github.com/rawgraphs/rawgraphs-app/blob/master/README.md Starts the RAWGraphs application in development mode. This command allows you to see changes in real-time and test the application locally. ```shell yarn start ``` -------------------------------- ### Clone RAW Repository (Shell) Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Home This command clones the RAW project repository from GitHub using Git. Ensure Git is installed on your system. ```sh git clone git://github.com/densitydesign/raw.git ``` -------------------------------- ### Tree Model Example: Data Transformation Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Models An example demonstrating the 'tree' model's data transformation. It includes sample input data, the configuration of dimensions for hierarchy, size, color, and label, and the resulting hierarchical JSON output. ```javascript { "children": [ { "name":"Action", "class":"Genre", "children": [ { "name":"Avatar", "class":"Movie", "size":425000000, "color":"Action", "label": [ "Avatar" ] }, { "name":"Iron Man 3", "class":"Movie", "size":200000000, "color":"Action", "label": [ "Iron Man 3" ] }, ... ] } ... ] } ``` -------------------------------- ### Points Model Example: Data Transformation Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Models An example illustrating the 'points' model transformation. It shows sample input data, the mapping of dimensions to model properties (x, y, color, label), and the resulting JSON output, which is an array of point objects. ```javascript [ {"x":425000000,"y":760507625,"size":1,"color":"Action","label":["Avatar"]}, {"x":94000000,"y":380529370,"size":1,"color":"Adventure","label":["Finding Nemo"]}, {"x":30000000,"y":238632124,"size":1,"color":"Comedy","label":["Ghostbusters"]}, {"x":200000000,"y":396702239,"size":1,"color":"Action","label":["Iron Man 3"]}, ... ] ``` -------------------------------- ### Example Graph Output JSON Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Models This is an example of the JSON output generated by the graph model. It shows the 'nodes' array, where each object has a 'name' and 'group', and the 'links' array, where each object specifies 'source', 'target' indices, and a 'value' for the link's weight. ```json { "nodes": [ {"name":"Action","group":"Genre"}, {"name":"Adventure","group":"Genre"}, {"name":"Comedy","group":"Genre"}, ... ], "links": [ {"source":0,"target":6,"value":1}, {"source":0,"target":10,"value":1}, {"source":0,"target":11,"value":1}, {"source":0,"target":16,"value":1}, ... ] } ``` -------------------------------- ### List Option Configuration Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts Configures and retrieves values for a list selection element. It allows setting the available options and getting the currently selected value. This is typically used for user input to filter or categorize data. ```javascript chart.list() // Returns the currently selected value. list.values(["value1", "value2"]) // Sets the array of possible values. ``` -------------------------------- ### RAWGraphs Hierarchy Data Structure Example (CSV) Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Hierarchical--Data-Format This CSV data structure is an example for defining hierarchical data in RAWGraphs. Each column represents a layer in the hierarchy, and each row defines a leaf with its path through the layers. Additional numerical columns can be used for weighted visualizations. ```csv Orchestra type,Group,Instrument,Number Modern orchestra,Brass,Baritone horn,1 Early Romantic orchestra,Woodwinds,Bass Clarinet,1 Late Romantic orchestra,Woodwinds,Bass Clarinet,1 Early Romantic orchestra,Percussion,Bass Drum,1 ``` -------------------------------- ### Initialize and Use Points Model in JavaScript Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Models Demonstrates how to initialize the 'points' model and apply it to a chart in JavaScript. It shows the basic usage and how to remove specific dimensions if they are not needed, which will set their values to null and remove them from the GUI. ```javascript var points = raw.models.points(); var chart = raw.chart() .model(points) ``` ```javascript var points = raw.models.points(); // removing the color dimension points.dimensions().remove('color'); var chart = raw.chart() .model(points) ``` -------------------------------- ### Navigate to RAW Directory (Shell) Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Home This command changes the current directory to the root folder of the cloned RAW project. This is a standard shell command. ```sh cd raw ``` -------------------------------- ### Load Custom Charts Dynamically in JavaScript Source: https://context7.com/rawgraphs/rawgraphs-app/llms.txt This snippet demonstrates how to load custom chart modules dynamically at runtime. It supports loading from NPM packages, URLs, or file uploads. It utilizes the `useSafeCustomCharts` hook and provides functions for loading from NPM, URL, and handling file uploads. Error handling is included for each loading method. ```javascript import useSafeCustomCharts from './hooks/useSafeCustomCharts' function CustomChartManager() { const [ customCharts, { toConfirmCustomChart, confirmCustomChartLoad, abortCustomChartLoad, uploadCustomCharts, loadCustomChartsFromUrl, loadCustomChartsFromNpm, importCustomChartFromProject, removeCustomChart, exportCustomChart } ] = useSafeCustomCharts() // Load from NPM package const loadFromNpm = async (packageName) => { try { await loadCustomChartsFromNpm(packageName) console.log('Successfully loaded chart from NPM:', packageName) } catch (error) { console.error('Failed to load chart:', error) } } // Load from URL const loadFromUrl = async (chartUrl) => { try { await loadCustomChartsFromUrl(chartUrl) console.log('Successfully loaded chart from URL:', chartUrl) } catch (error) { console.error('Failed to load chart:', error) } } // Upload chart file const handleFileUpload = async (file) => { try { const text = await file.text() await uploadCustomCharts(text) console.log('Successfully uploaded chart:', file.name) } catch (error) { console.error('Failed to upload chart:', error) } } return (

Custom Charts ({customCharts.length})

{ if (e.key === 'Enter') loadFromNpm(e.target.value) }} /> { if (e.key === 'Enter') loadFromUrl(e.target.value) }} /> { if (e.target.files[0]) handleFileUpload(e.target.files[0]) }} />
) } ``` -------------------------------- ### Create and Configure a RAWGraphs Chart - JavaScript Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Adding-New-Charts This JavaScript code demonstrates the creation of a RAWGraphs chart. It initializes a chart instance, associates it with a predefined model, and sets a title and description for the chart. This sets up the basic structure for the visualization. ```javascript var chart = raw.chart(); chart.model(model); chart.title("Simple scatter plot") .description("A simple scatter plot for learning purposes") ``` -------------------------------- ### Clone RAWGraphs App Repository (Shell) Source: https://github.com/rawgraphs/rawgraphs-app/blob/master/README.md Clones the RAWGraphs application repository from GitHub to your local machine. This is the first step in setting up a local development environment. ```shell git clone https://github.com/rawgraphs/rawgraphs-app.git ``` -------------------------------- ### Complete Scatter Plot Drawing Function (JavaScript) Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Adding-New-Charts This is a consolidated example of the `draw` function for a scatter plot in RAWGraphs. It includes setting SVG dimensions, defining x and y linear scales, and rendering the data points as SVG circles. This function adheres to RAWGraphs' constraints of using only SVG and inline styles. ```javascript chart.draw(function (selection, data){ // svg size selection .attr("width", width()) .attr("height", height()) // x and y scale var xScale = d3.scale.linear() .domain([0, d3.max(data, function (d){ return d.x; })]) .range([margin(), width()-margin()]); var yScale = d3.scale.linear() .domain([0, d3.max(data, function (d){ return d.y; })]) .range([height()-margin(), margin()]); // let's plot the dots selection.selectAll("circle") .data(data) .enter().append("circle") .attr("cx", function(d) { return xScale(d.x); }) .attr("cy", function(d) { return yScale(d.y); }) .attr("r", 5) }) ``` -------------------------------- ### Build Production Version of RAWGraphs (Shell) Source: https://github.com/rawgraphs/rawgraphs-app/blob/master/README.md Builds a production-ready version of the RAWGraphs application. This command compiles and optimizes the project for deployment on a server. ```shell yarn build ``` -------------------------------- ### Navigate to RAWGraphs App Directory (Shell) Source: https://github.com/rawgraphs/rawgraphs-app/blob/master/README.md Changes the current directory to the newly cloned RAWGraphs app folder. This is necessary to run subsequent commands within the project context. ```shell cd rawgraphs-app ``` -------------------------------- ### Rawgraphs Project Serialization and Export/Import (JavaScript) Source: https://context7.com/rawgraphs/rawgraphs-app/llms.txt Provides functions to serialize the current Rawgraphs application state into a JSON string for export and to deserialize a project string back into an application state for restoration. It utilizes the `serializeProject` and `deserializeProject` functions from `@rawgraphs/rawgraphs-core`. The `exportProject` function saves the state to a file, while `importProject` and `loadProjectFromUrl` handle restoring the state from a string or a URL. ```javascript import { serializeProject, deserializeProject } from '@rawgraphs/rawgraphs-core' // Export current project to JSON string async function exportProject(appState) { const { userInput, userData, userDataType, data, separator, thousandsSeparator, decimalsSeparator, locale, stackDimension, dataSource, currentChart, mapping, visualOptions } = appState const projectJson = serializeProject({ userInput, userData, userDataType, parseError: null, unstackedData: null, unstackedColumns: null, data, separator, thousandsSeparator, decimalsSeparator, locale, stackDimension, dataSource, currentChart, mapping, visualOptions, customChart: currentChart.rawCustomChart || null }) // Save to file const blob = new Blob([projectJson], { type: 'application/json' }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = 'rawgraphs-project.rawgraphs' link.click() return projectJson } // Import project from JSON string function importProject(projectString, availableCharts) { try { const project = deserializeProject(projectString, availableCharts) // Restore application state return { data: project.data, currentChart: project.currentChart, mapping: project.mapping, visualOptions: project.visualOptions, separator: project.separator, thousandsSeparator: project.thousandsSeparator, decimalsSeparator: project.decimalsSeparator, locale: project.locale, dataSource: project.dataSource, userInput: project.userInput } } catch (error) { console.error('Failed to import project:', error) throw new Error('Invalid project file') } } // Load project from URL async function loadProjectFromUrl(projectUrl, availableCharts) { try { const response = await fetch(projectUrl) if (!response.ok) throw new Error('Failed to fetch project') const projectString = await response.text() return importProject(projectString, availableCharts) } catch (error) { console.error('Failed to load project from URL:', error) throw error } } ``` -------------------------------- ### General Option Methods Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts Provides common methods for all option types (number, checkbox, list, color) to manage their title, description, default value, and reset functionality. These methods enhance the usability and configuration of GUI elements. ```javascript option.title('Option Title'); option.description('Detailed explanation.'); option.defaultValue(initialValue); option.reset(); const type = option.type(); // e.g., 'number', 'checkbox' ``` -------------------------------- ### Constructing a New Chart Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts Initializes a new chart instance within the RAWGraphs application. This is the fundamental step to begin defining a new visualization. ```javascript raw.chart() ``` -------------------------------- ### Export Visualizations to SVG, PNG, and JSON in JavaScript Source: https://context7.com/rawgraphs/rawgraphs-app/llms.txt This snippet demonstrates how to export rendered visualizations using `@rawgraphs/rawgraphs-core`. It covers exporting to SVG with inline styles, PNG with specified dimensions, and exporting the visualization data and configuration as JSON. It also includes functionality to copy the SVG content to the clipboard. This requires a `rawViz` object containing visualization details and an `exportProject` function. ```javascript import { exportSvg, exportPng, exportJson } from '@rawgraphs/rawgraphs-core' function Exporter({ rawViz, exportProject }) { // Export to SVG with embedded styles const handleSvgExport = () => { const svgString = exportSvg(rawViz.svgNode, { inlineStyles: true, includeMetadata: true, pretty: true }) const blob = new Blob([svgString], { type: 'image/svg+xml' }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = 'visualization.svg' link.click() } // Export to PNG with specified dimensions const handlePngExport = async (scale = 2) => { try { const pngBlob = await exportPng(rawViz.svgNode, { scale: scale, backgroundColor: '#ffffff' }) const url = URL.createObjectURL(pngBlob) const link = document.createElement('a') link.href = url link.download = 'visualization.png' link.click() } catch (error) { console.error('PNG export failed:', error) } } // Export data and configuration as JSON const handleJsonExport = async () => { const projectData = await exportProject() const jsonData = { data: rawViz.data, visualOptions: rawViz.visualOptions, mapping: rawViz.mapping, chart: rawViz.chart.metadata, project: projectData } const blob = new Blob([JSON.stringify(jsonData, null, 2)], { type: 'application/json' }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = 'visualization-data.json' link.click() } // Copy SVG to clipboard const handleCopyToClipboard = async () => { const svgString = exportSvg(rawViz.svgNode, { inlineStyles: true }) try { await navigator.clipboard.writeText(svgString) console.log('SVG copied to clipboard') } catch (error) { console.error('Failed to copy:', error) } } return (
) } ``` -------------------------------- ### Set Node.js OpenSSL Legacy Provider (Shell) Source: https://github.com/rawgraphs/rawgraphs-app/blob/master/README.md Configures the Node.js environment to use legacy OpenSSL providers. This is a workaround for potential compatibility issues with newer OpenSSL versions and is required for certain operations. ```shell export NODE_OPTIONS=--openssl-legacy-provider ``` -------------------------------- ### Initialize and Use Tree Model in JavaScript Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Models Shows how to initialize the 'tree' model in JavaScript for creating hierarchical data structures. This model is suitable for charts like Treemaps or Circle Packings, transforming records into a nested structure. ```javascript raw.models.tree(records) ``` -------------------------------- ### Chart Construction and Configuration Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts APIs for constructing a new chart and configuring its model, title, description, and drawing function. ```APIDOC ## Chart Construction and Configuration ### `raw.chart()` **Description**: Constructs a new chart instance. **Method**: N/A (Constructor) **Endpoint**: N/A ### `chart.model([model])` **Description**: Sets or gets the model used by the chart. The model transforms the user dataset into the structure expected by the chart based on selected dimensions. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: * **model** (object) - Optional - The model to apply to the dataset. ### `chart.title([text])` **Description**: Sets or gets the title of the chart. This title is displayed in the GUI. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: * **text** (string) - Optional - The title for the chart. ### `chart.description([text])` **Description**: Sets or gets the description for the chart, displayed in the GUI. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: * **text** (string) - Optional - The description for the chart. ### `chart.draw([function])` **Description**: Sets or gets the drawing function for the chart. This function is responsible for rendering the visualization within a given SVG selection and data. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: * **function** (function(selection, data)) - Optional - The function to draw the chart. It receives an SVG selection and the processed data. **Code Example for Draw Function**: ```javascript function(selection, data) { // generate chart here... } ``` **Note**: The SVG is cleared before each draw call. CSS styles cannot be used directly; styles and attributes must be defined explicitly using D3 operators (e.g., `.style()`, `.attr()`). ``` -------------------------------- ### Color Scale Configuration Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts Constructs and configures color scales for visualizations. This includes setting the domain of colors and optionally applying an accessor function. This method must be called before the color scale is used in the draw function. ```javascript chart.color() // Constructs a new color option. color.domain(["#ff0000", "#00ff00"]) // Sets the domain of the color scale. color.domain(["#ff0000", "#00ff00"], d => d.name) // Sets the domain with an accessor function. ``` -------------------------------- ### React Chart Selection and Rendering Workflow Source: https://context7.com/rawgraphs/rawgraphs-app/llms.txt Manages the user's interaction with chart selection, data mapping, and visual options for rendering charts. It utilizes React hooks for state management and imports components for each step of the workflow. Dependencies include React and Rawgraphs core utilities for option configuration. ```javascript import React, { useState, useMemo } from 'react' import ChartSelector from './components/ChartSelector' import DataMapping from './components/DataMapping' import ChartPreviewWithOptions from './components/ChartPreviewWIthOptions' import { getOptionsConfig, getDefaultOptionsValues } from '@rawgraphs/rawgraphs-core' import allCharts from './charts' function VisualizationWorkflow({ data }) { const [currentChart, setCurrentChart] = useState(allCharts[0]) const [mapping, setMapping] = useState({}) const [visualOptions, setVisualOptions] = useState(() => { const options = getOptionsConfig(currentChart?.visualOptions) return getDefaultOptionsValues(options) }) const [rawViz, setRawViz] = useState(null) const handleChartChange = (nextChart) => { setMapping({}) setCurrentChart(nextChart) const options = getOptionsConfig(nextChart?.visualOptions) setVisualOptions(getDefaultOptionsValues(options)) setRawViz(null) } return ( <> {/* Step 1: Select chart type */} console.log('Remove', chartId)} /> {/* Step 2: Map data columns to chart dimensions */} {currentChart && ( )} {/* Step 3: Customize and preview chart */} {currentChart && mapping && ( console.log('Mapping:', loading)} /> )} ) } ``` -------------------------------- ### Creating a Number Option Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts Constructs a numeric input option for the chart's GUI. This allows users to input numerical values that can control chart properties. The `fitToWidth` method can optionally enable fitting the input to the available browser width. ```javascript const widthOption = chart.number(); widthOption.title('Chart Width'); widthOption.defaultValue(500); widthOption.fitToWidth(true); // To get the value: const currentValue = widthOption(); ``` -------------------------------- ### Setting/Getting Chart Description Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts Sets or retrieves the descriptive text for a chart, which can be displayed in the GUI. This helps provide context or additional information about the visualization. Defaults to null. ```javascript chart.description("This chart shows..."); // or const currentDescription = chart.description(); ``` -------------------------------- ### Setting/Getting Chart Model Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts Configures or retrieves the data model for a chart. The model dictates how user-selected data is structured for the chart's visualization. It's essential for mapping raw data to the chart's expected format. ```javascript chart.model(yourModel); // or const currentModel = chart.model(); ``` -------------------------------- ### Initialize RAW Model and Dimensions Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Adding-New-Charts This JavaScript code initializes a new data model using `raw.model()` and defines two numeric dimensions, 'X Axis' and 'Y Axis', using chained method calls. These dimensions are crucial for a scatter plot, as they will allow users to map numeric columns from their dataset to the respective axes. The `.title()` method sets the user-facing label, and `.types(Number)` specifies that only numeric data types are acceptable for these dimensions. ```javascript var x = model.dimension() .title("X Axis") .types(Number); var y = model.dimension() .title("Y Axis") .types(Number); ``` -------------------------------- ### React Data Loading Component with useDataLoader Hook Source: https://context7.com/rawgraphs/rawgraphs-app/llms.txt This React component, `App`, utilizes a custom hook `useDataLoader` to manage data loading and parsing. It displays a `DataLoader` component, which takes various props from the hook, including user input states, parsed data, error information, and loading status. The component also renders a preview of the loaded data and any parsing errors encountered. ```javascript import React from 'react' import useDataLoader from './hooks/useDataLoader' import DataLoader from './components/DataLoader' function App() { const dataLoader = useDataLoader() const { userInput, userData, userDataType, parseError, data, separator, thousandsSeparator, decimalsSeparator, locale, stackDimension, dataSource, loading } = dataLoader return (
{ // Restore application state from saved project console.log('Loading project:', project) }} /> {data && (

Loaded {data.dataset.length} rows

Columns: {Object.keys(data.dataTypes).join(', ')}

{JSON.stringify(data.dataTypes, null, 2)}
)} {parseError && (
Parse Error: {parseError.message}
)}
) } ``` -------------------------------- ### List API Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts The List API allows users to create and manage dropdown menus for selecting values. It supports constructing list options, retrieving the selected value, and setting or retrieving the available list values. ```APIDOC ## List API ### Description This API manages list options, allowing users to select values from a dropdown menu. ### Methods - **chart.list()**: Constructs a list option. - **list()**: Returns the currently selected value. - **list.values([array])**: Sets or retrieves the array of possible values for the list. ### Parameters #### list.values([array]) - **array** (array) - Optional - The array of possible values to set for the list. ``` -------------------------------- ### Chart Options API Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts APIs for creating and configuring general chart options, including number and checkbox types. ```APIDOC ## Chart Options (GUI elements) Chart options bind chart variables to interface elements for user control. Available types include number, checkbox, list, and color. ### General Methods (Available to all Option Types) #### `option.title([text])` **Description**: Sets or gets the title of the option, displayed in the GUI. **Method**: N/A (Instance Method) **Parameters**: * **text** (string) - Optional - The title for the option. #### `option.description([text])` **Description**: Sets or gets the description for the option, displayed in the GUI. **Method**: N/A (Instance Method) **Parameters**: * **text** (string) - Optional - The description for the option. #### `option.type()` **Description**: Returns the type of the option as a string (e.g., 'number', 'checkbox'). **Method**: N/A (Instance Method) #### `option.defaultValue([value])` **Description**: Sets or gets the default value for the option. **Method**: N/A (Instance Method) **Parameters**: * **value** (any) - Optional - The default value for the option. #### `option.reset()` **Description**: Resets the option to its default value. **Method**: N/A (Instance Method) ### Number Option #### `chart.number()` **Description**: Constructs a numeric option. Binds numeric values to numeric INPUT elements. **Method**: N/A (Instance Method) #### `number()` **Description**: Returns the numeric value bound to this option. **Method**: N/A (Instance Method) #### `number.fitToWidth([boolean])` **Description**: Enables or disables the possibility to set the option's value equal to the available browser width. **Method**: N/A (Instance Method) **Parameters**: * **boolean** (boolean) - Optional - `true` to enable, `false` to disable. ### Checkbox Option #### `chart.checkbox()` **Description**: Constructs a checkbox option. Binds boolean values to CHECKBOX elements. **Method**: N/A (Instance Method) #### `checkbox()` **Description**: Returns the boolean value bound to this option. **Method**: N/A (Instance Method) ``` -------------------------------- ### Define Custom Scatter Plot Chart with RawGraphs Core Source: https://context7.com/rawgraphs/rawgraphs-app/llms.txt This snippet demonstrates how to create a custom scatter plot chart using the `@rawgraphs/rawgraphs-core` library. It defines the chart's metadata, data dimensions, customizable visual options, and the rendering logic using D3.js. The render function handles the creation of scales and the drawing of points and labels onto an SVG element. ```javascript import { createChart } from '@rawgraphs/rawgraphs-core' import * as d3 from 'd3' const customScatterChart = createChart({ metadata: { name: 'Scatter Plot', id: 'rawgraphs.scatterplot', description: 'Display two numeric dimensions using Cartesian coordinates', categories: ['correlations', 'distributions'], icon: 'scatterplot' }, // Use built-in points model or define custom model dimensions: [ { id: 'x', name: 'X Axis', validTypes: ['number'], required: true }, { id: 'y', name: 'Y Axis', validTypes: ['number'], required: true }, { id: 'size', name: 'Size', validTypes: ['number'], required: false }, { id: 'color', name: 'Color', validTypes: ['string', 'number', 'date'], required: false } ], // Define customizable visual options visualOptions: { width: { type: 'number', label: 'Width', default: 800, group: 'artboard' }, height: { type: 'number', label: 'Height', default: 600, group: 'artboard' }, margin: { type: 'number', label: 'Margin', default: 20, group: 'artboard' }, pointRadius: { type: 'number', label: 'Point radius', default: 5, min: 1, max: 50, group: 'chart' }, showLabels: { type: 'boolean', label: 'Show labels', default: false, group: 'chart' }, colorScale: { type: 'colorScale', label: 'Color scale', default: { scaleType: 'ordinal', interpolator: 'interpolateSpectral' }, group: 'colors' } }, // Render function receives selection (SVG) and data render(svgNode, data, visualOptions, mapping, originalData, styles) { const { width, height, margin, pointRadius, showLabels, colorScale } = visualOptions const selection = d3.select(svgNode) .attr('width', width) .attr('height', height) // Create scales const xScale = d3.scaleLinear() .domain([0, d3.max(data, d => d.x)]) .range([margin, width - margin]) .nice() const yScale = d3.scaleLinear() .domain([0, d3.max(data, d => d.y)]) .range([height - margin, margin]) .nice() const sizeScale = d3.scaleLinear() .domain(d3.extent(data, d => d.size || 1)) .range([pointRadius / 2, pointRadius * 2]) // Draw points selection.selectAll('circle') .data(data) .join('circle') .attr('cx', d => xScale(d.x)) .attr('cy', d => yScale(d.y)) .attr('r', d => sizeScale(d.size || 1)) .attr('fill', d => colorScale(d.color)) .attr('opacity', 0.7) .attr('stroke', '#000') .attr('stroke-width', 0.5) // Optionally add labels if (showLabels) { selection.selectAll('text') .data(data) .join('text') .attr('x', d => xScale(d.x)) .attr('y', d => yScale(d.y) - sizeScale(d.size || 1) - 3) .attr('text-anchor', 'middle') .attr('font-size', 10) .attr('fill', '#000') .text(d => d.label ? d.label.join(', ') : '') } return svgNode } }) export default customScatterChart ``` -------------------------------- ### Construct RawGraphs Parser with Delimiter Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Data-Parsing Initializes a new parser for delimiter-separated values. If a delimiter is provided, it's used for parsing. Otherwise, the parser attempts to auto-detect the delimiter from a predefined list (comma, semicolon, tab, colon, vertical bar). ```javascript const parser = raw.parser(','); // Using comma as delimiter const autoParser = raw.parser(); // Auto-detect delimiter ``` -------------------------------- ### Create Chart Data Transformation Models with @rawgraphs/rawgraphs-core Source: https://context7.com/rawgraphs/rawgraphs-app/llms.txt Defines data transformation models for charting, allowing users to map data dimensions to visual properties. It involves creating dimensions, specifying their types and requirements, and defining a mapping function to transform raw data into chart-specific structures. ```javascript import { createModel } from '@rawgraphs/rawgraphs-core' // Create a model for scatter plot points const scatterModel = createModel() // Define dimensions that users can map to their data columns const xDimension = scatterModel.dimension() .title('X Axis') .types(['number']) .required(true) const yDimension = scatterModel.dimension() .title('Y Axis') .types(['number']) .required(true) const colorDimension = scatterModel.dimension() .title('Color') .types(['string', 'number', 'date']) .multiple(false) const labelDimension = scatterModel.dimension() .title('Label') .types(['string']) .multiple(true) // Define the transformation map function scatterModel.map(function(data) { return data.map(function(record) { return { x: +xDimension(record), y: +yDimension(record), color: colorDimension(record), label: labelDimension(record) } }) }) // Apply the model to dataset with user-selected column mappings const mapping = { x: ['Budget'], y: ['BoxOffice'], color: ['Genre'], label: ['Movie'] } const transformedData = scatterModel.applyMapping(dataset, mapping) // Result: [ // { x: 425000000, y: 760507625, color: "Action", label: ["Avatar"] }, // { x: 94000000, y: 380529370, color: "Adventure", label: ["Finding Nemo"] }, // ... // ] ``` -------------------------------- ### Include Chart Script in HTML Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Adding-New-Charts This snippet shows how to include your custom chart script file (`chart.js`) in the `index.html` file of the RAW Graphs application. This is a standard HTML script tag, and it's essential for the application to load and recognize your new chart. ```html ``` -------------------------------- ### Google Analytics Configuration (JavaScript) Source: https://github.com/rawgraphs/rawgraphs-app/blob/master/public/index.html This snippet configures Google Analytics for the RAWGraphs application. It initializes the dataLayer and sets up the gtag() function for sending tracking information. Ensure JavaScript is enabled in the browser for this to function. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-5816319-7'); ``` -------------------------------- ### Wrap Chart Code in Self-Executing Function Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Adding-New-Charts This JavaScript code demonstrates the best practice of wrapping your entire chart's code within a self-executing anonymous function (IIFE). This pattern helps to isolate the scope of your chart's variables and functions, preventing potential naming conflicts with other scripts in the RAW Graphs application. ```javascript (function(){ // your code here... })(); ``` -------------------------------- ### Creating a Checkbox Option Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts Creates a checkbox option for the chart's GUI, binding a boolean value. This is useful for toggling features or settings within the visualization. The option's state can be retrieved using the checkbox function. ```javascript const showLabelsOption = chart.checkbox(); showLabelsOption.title('Show Labels'); showLabelsOption.defaultValue(false); // To get the value: const isLabelsVisible = showLabelsOption(); ``` -------------------------------- ### Setting/Getting Chart Title Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Charts Manages the title displayed for the chart. This is useful for labeling visualizations in the GUI. If no title is set, it defaults to 'Untitled'. ```javascript chart.title("My Awesome Chart"); // or const currentTitle = chart.title(); ``` -------------------------------- ### Initialize Scatterplot Model and Dimensions - JavaScript Source: https://github.com/rawgraphs/rawgraphs-app/wiki/Adding-New-Charts This JavaScript snippet initializes a RAWGraphs model and defines two numeric dimensions, 'X Axis' and 'Y Axis'. These dimensions serve as accessors to retrieve data values from user-selected columns. The model's map function is then configured to transform the input data based on these dimensions. ```javascript var model = raw.model(); var x = model.dimension() .title('X Axis') .types(Number) var y = model.dimension() .title('Y Axis') .types(Number) model.map(function (data){ return data.map(function (d){ return { x : +x(d), y : +y(d) } }) }) ```