### 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])
}}
/>
{customCharts.map(chart => (
{chart.metadata.name}
))}
)
}
```
--------------------------------
### 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 (