### Install Cosmograph Widget
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Python/get-started-widget
Installs the Cosmograph widget using pip. Ensure you have Python and pip installed.
```bash
pip install cosmograph
```
--------------------------------
### Cosmograph Usage Example: Node Color
Source: https://cosmograph.app/docs/cosmograph/Sharing%20Graphs
An example URL demonstrating how to set the node color to 'incoming links' in Cosmograph.
```URL
https://cosmograph.app/run/?data=https://cosmograph.app/data/data-links-example.csv&nodeColor=incoming%20links
```
--------------------------------
### Cosmograph Usage Example: Simulation Parameters
Source: https://cosmograph.app/docs/cosmograph/Sharing%20Graphs
An example URL showing how to configure multiple simulation parameters in Cosmograph, including decay, link distance, and link spring.
```URL
https://cosmograph.app/run/?&decay=100000&link-distance=1&link-spring=2&data=https://cosmograph.app/data/100x100.csv
```
--------------------------------
### Cosmograph Usage Example: Link Color
Source: https://cosmograph.app/docs/cosmograph/Sharing%20Graphs
An example URL illustrating how to set the link color based on the average value of a 'value' column in Cosmograph.
```URL
https://cosmograph.app/run/?data=https://cosmograph.app/data/data-links-example.csv&linkColor=avg-value
```
--------------------------------
### Graph Mode Data: Edge List Example
Source: https://cosmograph.app/docs/cosmograph/How%20to%20Use
Example of a simple edge list for Graph mode, specifying source and target nodes for graph connections. This format requires at least two columns.
```text
source;target
node1;node2
node1;node3
```
--------------------------------
### Graph Mode Metadata: Node Information Example
Source: https://cosmograph.app/docs/cosmograph/How%20to%20Use
Example of a metadata file for Graph mode, providing 'id', 'color', and 'size' for nodes. This file allows enrichment of node properties beyond the edge list.
```text
id;color;size
node1;red;10
node2;green;20
node3;blue;30
```
--------------------------------
### Create Basic Graph Visualization (JavaScript/TypeScript)
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
Provides a basic example of initializing the Cosmograph JavaScript/TypeScript library to render a graph. It demonstrates setting up the container, creating a Cosmograph instance with initial configuration, and loading node and link data.
```typescript
import { Cosmograph } from '@cosmograph/cosmograph'
// Define graph data
const nodes = [
{ id: 'node1' },
{ id: 'node2' },
{ id: 'node3' },
{ id: 'node4' }
]
const links = [
{ source: 'node1', target: 'node2' },
{ source: 'node2', target: 'node3' },
{ source: 'node3', target: 'node4' },
{ source: 'node1', target: 'node4' }
]
// Create container and Cosmograph instance
const container = document.getElementById('graph-container')
const cosmograph = new Cosmograph(container, {
backgroundColor: '#ffffff',
nodeColor: '#5B8FF9',
nodeSize: 8,
linkWidth: 2,
linkColor: '#cccccc'
})
// Load data and start simulation
cosmograph.setData(nodes, links)
```
--------------------------------
### Sample Node and Link Data
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Provides example data structures for nodes and links used in Cosmograph visualizations. Nodes have an 'id', and links define 'source' and 'target' node IDs.
```javascript
export const nodes = [
{ id: 'node1' },
{ id: 'node2' },
{ id: 'node3' },
]
export const links = [
{ source: 'node1', target: 'node2' },
{ source: 'node2', target: 'node3' },
]
```
--------------------------------
### JavaScript: Zoom to Node Example
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20JavaScript/Cosmograph
This JavaScript snippet shows how to directly call the `zoomToNode` method on a Cosmograph instance after it has been initialized.
```javascript
// In JavaScript you can simply call the methods on the Cosmograph
// instance once the graph has been initialized
cosmograph.zoomToNode({ id: 'node0' })
```
--------------------------------
### Cosmograph Widget Quick Start Visualization
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Python/get-started-widget
Demonstrates how to use the Cosmograph widget to visualize data. It requires pandas for data manipulation and the cosmograph library. The function takes pandas DataFrames for points and links, along with configuration for mapping data columns to visual attributes.
```python
import pandas as pd
from cosmograph import cosmo
points = pd.DataFrame({
'id': [1, 2, 3, 4, 5],
'label': ['Node A', 'Node B', 'Node C', 'Node D', 'Node E'],
'value': [10, 20, 15, 25, 30],
'category': ['A', 'B', 'A', 'B', 'A']
})
links = pd.DataFrame({
'source': [1, 2, 3, 1, 2],
'target': [2, 3, 4, 5, 4],
'value': [1.0, 2.0, 1.5, 0.5, 1.8]
})
widget = cosmo(
points=points,
links=links,
point_id_by='id',
link_source_by='source',
link_target_by='target',
point_color_by='category',
point_include_columns=['value'],
point_label_by='label',
link_include_columns=['value'],
)
widget
```
--------------------------------
### React Example: Zooming to a Node in Cosmograph
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Demonstrates how to use the `useRef` hook in React to get a reference to the Cosmograph instance and call the `zoomToNode` method in response to a button click. This allows programmatic control over graph navigation.
```jsx
import React, { useRef, useEffect } from 'react'
import { Cosmograph } from '@cosmograph/react'
export function GraphVisualization ({ nodes, links }) {
// Create a ref to hold the Cosmograph instance
const cosmographRef = useRef(null)
const zoomToNode = () => cosmographRef.current?.zoomToNode({{ id: 'node0' }})
return (<>
>)
}
```
--------------------------------
### Embedding Mode Data: Node Coordinates Example
Source: https://cosmograph.app/docs/cosmograph/How%20to%20Use
Example data file for Embedding mode, containing 'id', 'x', and 'y' coordinates for node positioning. This mode expects pre-defined coordinates for visualization.
```text
id;x;y
node1;0.2;0.5
node2;0.7;0.3
node3;0.4;0.8
```
--------------------------------
### Simulation Control Methods
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Python/configuration
Methods to control the simulation, including starting, pausing, restarting, and stepping through frames.
```APIDOC
## `start(alpha)`
### Description
Starts the simulation. The `alpha` parameter may control simulation speed or other properties.
### Method
POST
### Endpoint
/websites/cosmograph_app_cosmograph/start
### Parameters
#### Query Parameters
- **alpha** (float) - Optional - A parameter that might influence simulation behavior.
### Request Example
```json
{
"alpha": 0.5
}
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
## `pause()`
### Description
Pauses the simulation.
### Method
POST
### Endpoint
/websites/cosmograph_app_cosmograph/pause
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
## `restart()`
### Description
Restarts the simulation from its initial state.
### Method
POST
### Endpoint
/websites/cosmograph_app_cosmograph/restart
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
## `step()`
### Description
Renders only a single frame of the simulation. Useful for frame-by-frame analysis.
### Method
POST
### Endpoint
/websites/cosmograph_app_cosmograph/step
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### React: Zoom to Node Example
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20JavaScript/Cosmograph
This React snippet demonstrates how to use the `useRef` hook to get a reference to the Cosmograph instance and call the `zoomToNode` method to programmatically zoom to a specific node.
```javascript
import React, { useRef, useEffect } from 'react'
import { Cosmograph } from '@cosmograph/react'
export function GraphVisualization ({ nodes, links }) {
// Create a ref to hold the Cosmograph instance
const cosmographRef = useRef(null)
const zoomToNode = () => cosmographRef.current?.zoomToNode({ id: 'node0' })
return (<>
>)
}
```
--------------------------------
### Control Viewport and Navigation in Cosmograph
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
This example demonstrates programmatic control over the graph's viewport, including zooming, panning, and fitting views. It configures initial view settings and provides methods to animate transitions for various navigation actions. Requires the Cosmograph library and node data.
```typescript
import { Cosmograph } from '@cosmograph/cosmograph'
const cosmograph = new Cosmograph(container)
cosmograph.setConfig({
initialZoomLevel: 1.5,
fitViewOnInit: true,
fitViewDelay: 500
})
cosmograph.setData(nodes, links)
// Fit all nodes in view
cosmograph.fitView(250) // 250ms animation
// Fit specific nodes by IDs
cosmograph.fitViewByNodeIds(['node1', 'node2', 'node3'], 500)
// Zoom to specific node
cosmograph.zoomToNode(nodes[0])
// Set zoom level
cosmograph.setZoomLevel(2.5, 300) // Zoom to 2.5x over 300ms
// Get current zoom
const zoomLevel = cosmograph.getZoomLevel()
console.log('Current zoom:', zoomLevel)
// Zoom to rectangular area
cosmograph.fitViewByNodePositions([[0, 0], [100, 100]], 400)
```
--------------------------------
### JavaScript Example: Zooming to a Node in Cosmograph
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Illustrates how to directly invoke Cosmograph methods, such as `zoomToNode`, on a Cosmograph instance in a JavaScript environment after the graph has been initialized. This provides a straightforward way to control graph behavior.
```javascript
// In JavaScript you can simply call the methods on the Cosmograph
// instance once the graph has been initialized
cosmograph.zoomToNode({ id: 'node0' })
```
--------------------------------
### Configure Link Appearance with `setConfig` (JS/TS)
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
This example shows how to configure link appearance, including width and color, using the `setConfig` method in Cosmograph. It defines a configuration object with functional properties for dynamic styling. This approach is suitable for non-React environments or when direct configuration is preferred.
```javascript
const colors = ['#88C6FF', '#FF99D2', '#2748A4'];
const config = {
linkWidth: () => 1 + 2 * Math.random(),
linkColor: () => colors[Math.floor(Math.random() * colors.length)]
}
cosmograph.setConfig(config)
```
--------------------------------
### Graph Mode Edge List with Time and Value (CSV)
Source: https://cosmograph.app/docs/cosmograph/How%20to%20use
This example demonstrates an extended CSV file for Graph mode, including 'time' and 'value' columns. The 'time' column enables timeline visualization, and 'value' can be used for link styling.
```text
time;source;target;value
2/4/2022;node1;node2;2
2/5/2022;node1;node3;10
```
--------------------------------
### Basic React Integration with Cosmograph
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
Integrate Cosmograph into a React application using the dedicated React component. This example demonstrates how to pass nodes and links data, and configure basic visual properties like node size, color, link color, and background color.
```tsx
import React from 'react'
import { Cosmograph } from '@cosmograph/react'
interface Node {
id: string
label: string
}
interface Link {
source: string
target: string
}
export function GraphVisualization() {
const nodes: Node[] = [
{ id: 'node1', label: 'Alpha' },
{ id: 'node2', label: 'Beta' },
{ id: 'node3', label: 'Gamma' }
]
const links: Link[] = [
{ source: 'node1', target: 'node2' },
{ source: 'node2', target: 'node3' }
]
return (
)
}
```
--------------------------------
### Graph Mode Metadata with Type and Time (CSV)
Source: https://cosmograph.app/docs/cosmograph/How%20to%20use
This example shows an enhanced metadata CSV file for Graph mode, including 'type' and 'time' columns. 'type' can be used for categorical coloring, and 'time' for node-specific timelines.
```text
id;color;size;type;time
node1;red;10;bird;2/4/2022
node2;green;20;plant;2/5/2022
node3;blue;30;bird;2/6/2022
```
--------------------------------
### React: Handle User Interactions with Event Handlers
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
This example demonstrates how to manage user interactions within the Cosmograph React component using various event handler props. It showcases handling clicks, mouseovers, mouseouts, zoom events, and simulation completion to update application state and log information. This approach allows for dynamic responses to user actions on the graph.
```tsx
import React, { useState } from 'react'
import { Cosmograph } from '@cosmograph/react'
interface Node {
id: string
label: string
connections?: number
}
export function EventHandlingGraph() {
const [selectedNode, setSelectedNode] = useState(null)
const [hoverNode, setHoverNode] = useState(null)
const [zoomLevel, setZoomLevel] = useState(1)
const nodes: Node[] = [
{ id: 'n1', label: 'Node 1', connections: 5 },
{ id: 'n2', label: 'Node 2', connections: 3 },
{ id: 'n3', label: 'Node 3', connections: 7 }
]
const links = [
{ source: 'n1', target: 'n2' },
{ source: 'n2', target: 'n3' }
]
return (
)
}
```
--------------------------------
### Graph Mode Metadata: Extended Node Information
Source: https://cosmograph.app/docs/cosmograph/How%20to%20Use
An extended metadata file example for Graph mode, including 'type' and 'time' columns for nodes. Plain text columns like 'type' can generate categorical color scales, and 'time' can be used for node-specific timelines.
```text
id;color;size;type;time
node1;red;10;bird;2/4/2022
node2;green;20;plant;2/5/2022
node3;blue;30;bird;2/6/2022
```
--------------------------------
### Configure Node Ring Colors and Focus Node in React
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
This React example demonstrates how to set custom colors for hovered and focused node rings and how to programmatically focus a node using the Cosmograph component. It utilizes refs to access the Cosmograph instance after mounting.
```jsx
import React, { useCallback } from 'react'
import { Cosmograph } from '@cosmograph/react'
export function Example ({ nodes, links }) {
// Create a ref to hold the Cosmograph instance
const cosmographRef = useCallback((ref) => {
// Focus node after Cosmograph mount
ref?.focusNode({ id: 'node0' })
}, [])
return (<>
>)
}
```
--------------------------------
### Define Nodes for Cosmograph
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Provides an example of defining an array of node objects for use with Cosmograph. Each node object must have a unique 'id' property, and can optionally include other properties like 'value'. This structure is fundamental for referencing nodes in configuration.
```javascript
export const nodes = [
{ id: 'node0', value: 1 },
{ id: 'node1', value: 2 },
{ id: 'node2', value: 3 },
{ id: 'node3', value: 4 },
{ id: 'node4', value: 5 },
]
```
--------------------------------
### Graph Mode Data: Edge List with Time and Value
Source: https://cosmograph.app/docs/cosmograph/How%20to%20Use
Example of an edge list for Graph mode including 'time' and 'value' columns. The 'time' column is automatically parsed for timeline display, and numeric columns like 'value' can be used for link color and thickness.
```text
time;source;target;value
2/4/2022;node1;node2;2
2/5/2022;node1;node3;10
```
--------------------------------
### Create Cosmograph Instance with JS/TS
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Shows how to initialize a Cosmograph instance using plain JavaScript or TypeScript. This involves creating a DOM element, instantiating Cosmograph, and setting the data.
```javascript
import { Cosmograph } from '@cosmograph/cosmograph'
import { nodes, links } from './path/to/data'
// Create an HTML element
const div = document.createElement('div')
document.body.appendChild(div)
// Create a Cosmograph instance with this element
const cosmograph = new Cosmograph(div)
// Set the data for the Cosmograph instance
cosmograph.setData(nodes, links)
```
--------------------------------
### Quadtree Algorithm Settings (Experimental)
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Python/configuration
Experimental settings for the quadtree algorithm used in the Many-Body force simulation.
```APIDOC
## `use_quadtree`
### Description
Activates or deactivates the quadtree algorithm for Many-Body force calculation. Defaults to `False`.
### Method
POST
### Endpoint
/websites/cosmograph_app_cosmograph/use_quadtree
### Parameters
#### Query Parameters
- **value** (boolean) - Required - Set to `True` to activate quadtree, `False` to deactivate.
### Request Example
```json
{
"value": true
}
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
## `simulation_repulsion_quadtree_levels`
### Description
Sets the Barnes–Hut approximation depth for the quadtree algorithm. Only usable when `use_quadtree` is set to `True`. Defaults to `12`.
### Method
POST
### Endpoint
/websites/cosmograph_app_cosmograph/simulation_repulsion_quadtree_levels
### Parameters
#### Query Parameters
- **levels** (integer) - Required - The depth level for the quadtree approximation.
### Request Example
```json
{
"levels": 15
}
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### Configure Cosmograph Simulation Forces (JavaScript/TypeScript)
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
This snippet demonstrates configuring simulation forces using a configuration object and the `setConfig` method in JavaScript/TypeScript. This approach is useful for setting multiple parameters at once and managing simulation state programmatically.
```javascript
const config = {
simulationFriction: 0.1,
simulationLinkSpring: 0.5,
simulationLinkDistance: 2.0,
}
cosmograph.setConfig(config)
```
--------------------------------
### Load Graph with Metadata (Cosmograph Launcher)
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
Explains how to load graph data along with additional node properties from a separate metadata file. The metadata file should contain an 'id' column to link properties to nodes. This allows for custom styling of nodes, such as color and size.
```bash
# In Cosmograph launcher:
# 1. Select data.csv as "Data file"
# 2. Select metadata.csv as "Metadata file"
# 3. Click "Launch"
# Node colors and sizes will be applied from metadata
```
--------------------------------
### Configure Cosmograph with Methods (JS/TS)
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Demonstrates how to configure a Cosmograph instance using JavaScript/TypeScript by calling `setConfig` and `setData` methods. This allows for dynamic updates to the graph's appearance and data.
```javascript
const config = {
nodeColor: d => d.color,
nodeSize: 20,
linkWidth: 2,
}
cosmograph.setConfig(config)
cosmograph.setData(nodes, links)
```
--------------------------------
### Share Graphs via URL (Cosmograph)
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
Shows how to generate shareable URLs for Cosmograph visualizations. These URLs can encode visual settings, simulation parameters, and data sources directly in the query string, allowing for reproducible and customizable sharing of graphs.
```bash
# Share graph with custom node coloring
https://cosmograph.app/run/?data=https://example.com/data.csv&nodeColor=incoming%20links&nodeSize=total%20links
# Share with simulation parameters
https://cosmograph.app/run/?data=https://example.com/data.csv&decay=5000&link-spring=1.5&gravity=0.2
# Share embedding with labels
https://cosmograph.app/run/?embedding=https://example.com/embedding.csv&nodeLabel=id&nodeSizeScale=2
```
--------------------------------
### Initialize Cosmograph with CosmographProvider in React
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20JavaScript/React%20Advanced%20Usage
The CosmographProvider component initializes Cosmograph with nodes and links data. Wrap your application with it to provide Cosmograph instance and data to other components via React Context API. Ensure Cosmograph is initialized within the provider for all Cosmograph React Components to function correctly.
```javascript
import { CosmographProvider, Cosmograph } from '@cosmograph/react'
import { nodes, links } from './path/to/data'
function App() {
return (
{/* Your app components */}
)
}
```
--------------------------------
### Configure Cosmograph Simulation Forces (JavaScript)
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20JavaScript/Cosmograph
This snippet demonstrates how to configure simulation forces programmatically using JavaScript. A configuration object is created with desired force parameters, and then passed to the cosmograph.setConfig method to apply the settings to an existing simulation instance.
```javascript
const config = {
simulationFriction: 0.1,
simulationLinkSpring: 0.5,
simulationLinkDistance: 2.0,
}
cosmograph.setConfig(config)
```
--------------------------------
### Create Cosmograph Instance with React
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Demonstrates how to create a Cosmograph instance within a React component. It takes nodes and links as props and renders them using the Cosmograph component.
```jsx
import { Cosmograph, CosmographProvider } from '@cosmograph/react'
export const Component = ({ nodes, links}) => {
return (
)
}
```
--------------------------------
### Handle User Interactions with Cosmograph
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
This snippet demonstrates how to handle user interactions such as clicks and hovers on graph nodes. It configures callbacks for selection, hover events, and zoom, allowing for dynamic updates and user feedback. Dependencies include the Cosmograph library.
```typescript
import { Cosmograph } from '@cosmograph/cosmograph'
const cosmograph = new Cosmograph(container)
cosmograph.setConfig({
onClick: (clickedNode, index, position, event) => {
if (clickedNode) {
console.log('Clicked node:', clickedNode.id)
cosmograph.selectNode(clickedNode, true) // Select with adjacent nodes
// Get adjacent nodes
const adjacent = cosmograph.getAdjacentNodes(clickedNode.id)
console.log('Adjacent nodes:', adjacent)
} else {
cosmograph.unselectNodes() // Clear selection
}
},
onNodeMouseOver: (hoveredNode, index, position, event) => {
console.log('Hovering:', hoveredNode.id)
document.body.style.cursor = 'pointer'
},
onNodeMouseOut: (event) => {
document.body.style.cursor = 'default'
},
onZoom: (event, userDriven) => {
console.log('Zoom level:', event.transform.k)
},
nodeGreyoutOpacity: 0.2,
hoveredNodeRingColor: '#FFD700',
focusedNodeRingColor: '#FF6B6B'
})
cosmograph.setData(nodes, links)
// Programmatic selection
setTimeout(() => {
cosmograph.selectNodes([nodes[0], nodes[1], nodes[2]])
}, 2000)
```
--------------------------------
### Initialize Cosmograph with CosmographProvider in React
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/React%20Advanced%20Usage
The CosmographProvider component initializes a Cosmograph instance and provides data to the application using React's Context API. Wrap your application with it and pass nodes and links to set up initial data. It's essential for other Cosmograph React Components to function correctly.
```javascript
import { CosmographProvider, Cosmograph } from '@cosmograph/react'
import { nodes, links } from './path/to/data'
function App() {
return (
{/* Your app components */}
)
}
```
--------------------------------
### Load Embedding Data (Cosmograph Launcher)
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
Illustrates how to visualize pre-positioned nodes using embedding data, bypassing the force simulation. The CSV file must include 'id', 'x', and 'y' columns for node coordinates. This mode is suitable for visualizing embeddings from machine learning models.
```bash
# In Cosmograph launcher:
# 1. Select "Embedding" mode
# 2. Choose your CSV file with id, x, y columns
# 3. Click "Launch"
# Graph renders without force simulation
```
--------------------------------
### Interactive Selection and Programmatic Control with Cosmograph
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
This Python snippet illustrates how to create a Cosmograph graph with points and links, display it, and then interact with it programmatically. It covers selecting points by ID, focusing on specific points, fitting the view, activating selection tools, and accessing selection state.
```python
import pandas as pd
from cosmograph import Cosmograph
points_df = pd.DataFrame({
'id': ['a', 'b', 'c', 'd', 'e'],
'value': [10, 20, 30, 40, 50]
})
links_df = pd.DataFrame({
'source': ['a', 'b', 'c', 'd'],
'target': ['b', 'c', 'd', 'e']
})
graph = Cosmograph(
points=points_df,
point_id_by='id',
point_size_by='value',
links=links_df,
link_source_by='source',
link_target_by='target'
)
# Display graph
# display(graph) # Assuming 'display' is available in the environment (e.g., Jupyter)
# Programmatic control
graph.select_point_by_id('a')
graph.focus_point('b')
graph.fit_view()
# Select multiple points
graph.select_points_by_ids(['a', 'b', 'c'])
# Activate rectangular selection tool
graph.activate_rect_selection()
# Access selection state
print('Selected IDs:', graph.selected_point_ids)
print('Selected indices:', graph.selected_point_indices)
print('Clicked point:', graph.clicked_point_id)
# Control simulation
graph.pause()
graph.restart()
```
--------------------------------
### Load Embedding Data for Visualization with Cosmograph
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
This snippet demonstrates how to load and prepare embedding data using pandas and then initialize a Cosmograph visualization. It sets up points with ID, coordinates, cluster information, and text labels, disabling simulation for a static view.
```python
import pandas as pd
from cosmograph import Cosmograph
# Load embedding data (e.g., from UMAP, t-SNE)
embeddings_df = pd.DataFrame({
'id': [f'doc_{i}' for i in range(100)],
'x': [0.1 * i for i in range(100)], # Replace with actual coordinates
'y': [0.05 * i for i in range(100)], # Replace with actual coordinates
'cluster': ['cluster_A' if i < 50 else 'cluster_B' for i in range(100)],
'text': [f'Document {i}' for i in range(100)]
})
# Create embedding visualization without simulation
embedding_viz = Cosmograph(
points=embeddings_df,
point_id_by='id',
point_x_by='x',
point_y_by='y',
point_color_by='cluster',
point_label_by='text',
disable_simulation=True,
render_links=False,
show_dynamic_labels=True,
point_size=8,
background_color='#1a1a1a',
fit_view_on_init=True
)
embedding_viz
```
--------------------------------
### Load Graph Data from CSV (Cosmograph Launcher)
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
Demonstrates how to load network graph data from CSV files into the Cosmograph web application. The library automatically detects numeric, color, and time columns. This process involves selecting the CSV file and launching the visualization.
```bash
# Open Cosmograph web app at https://cosmograph.app
# Click "Choose files" and select your CSV/TSV/SSV file
# Click "Launch" to render the graph
```
--------------------------------
### Cosmograph Simulation URL Parameters
Source: https://cosmograph.app/docs/cosmograph/Sharing%20Graphs
Sets simulation parameters for Cosmograph visualizations via URL. These parameters control the physics of the force-directed layout, including gravity, repulsion, link behavior, and simulation decay.
```URL Parameters
gravity
repulsion
repulsion-theta
link-spring
link-distance
friction
decay
```
--------------------------------
### Python: Create Graph Visualization with Pandas DataFrames
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
This Python snippet demonstrates how to create and render an interactive Cosmograph visualization directly within a Jupyter notebook. It utilizes pandas DataFrames to define graph nodes and links, specifying attributes like ID, size, color, label, and link weight. The Cosmograph constructor is then used with various `_by` arguments to map DataFrame columns to visual properties.
```python
import pandas as pd
from cosmograph import Cosmograph
# Create graph data
points_df = pd.DataFrame({
'id': ['node1', 'node2', 'node3', 'node4'],
'size': [10, 15, 8, 20],
'color': ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4'],
'label': ['Hub A', 'Hub B', 'Leaf C', 'Leaf D']
})
links_df = pd.DataFrame({
'source': ['node1', 'node1', 'node2', 'node3'],
'target': ['node2', 'node3', 'node4', 'node4'],
'weight': [5, 3, 7, 2]
})
# Create and display graph
graph = Cosmograph(
points=points_df,
point_id_by='id',
point_color_by='color',
point_size_by='size',
point_label_by='label',
links=links_df,
link_source_by='source',
link_target_by='target',
link_width_by='weight',
background_color='#ffffff',
simulation_repulsion=0.3,
simulation_link_spring=1.2
)
# Display in notebook
graph
```
--------------------------------
### Miscellaneous API
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20JavaScript/Cosmograph
Utility functions for graph instance management and coordinate conversion.
```APIDOC
## remove
### Description
Destroys the graph instance and cleans up the context.
### Method
N/A (Function Call)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```javascript
remove();
```
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
```APIDOC
## create
### Description
Create new graph instance.
### Method
N/A (Function Call)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```javascript
create();
```
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
```APIDOC
## spaceToScreenPosition
### Description
Converts the X and Y node coordinates from the space coordinate system to the screen coordinate system.
### Method
N/A (Function Call)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
- **spacePosition** ([number, number]) - Required - The [x, y] coordinates in the space system.
### Request Example
```javascript
const screenPos = spaceToScreenPosition([100, 200]);
```
### Response
#### Success Response (200)
- **screenPosition** ([number, number]) - The [x, y] coordinates in the screen system.
#### Response Example
```json
{
"screenPosition": [300, 400]
}
```
```
```APIDOC
## spaceToScreenRadius
### Description
Converts the node radius value from the space coordinate system to the screen coordinate system.
### Method
N/A (Function Call)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
- **spaceRadius** (number) - Required - The radius in the space system.
### Request Example
```javascript
const screenRadius = spaceToScreenRadius(10);
```
### Response
#### Success Response (200)
- **screenRadius** (number) - The radius in the screen system.
#### Response Example
```json
{
"screenRadius": 20
}
```
```
--------------------------------
### Show Specific Node Labels Using IDs with JavaScript Configuration
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Illustrates how to configure the Cosmograph instance programmatically using JavaScript to display labels for specific nodes identified by their 'id'. The `setConfig` method is used with a configuration object that includes the `showLabelsFor` property, accepting an array of node IDs.
```javascript
const config = {
showDynamicLabels: false,
showLabelsFor: [{ id: "node0" }, { id: "node3" }]
}
cosmograph.setConfig(config)
```
--------------------------------
### Cosmograph Link URL Parameters
Source: https://cosmograph.app/docs/cosmograph/Sharing%20Graphs
Configures the appearance of links in Cosmograph visualizations using URL parameters. Allows adjustment of link width and color. Options include 'records' for handling duplicate links, and numeric column-derived settings like 'sum-value' and 'avg-value'. Color columns can also be used for link coloring.
```URL Parameters
linkWidth
linkColor
linkWidthScale
linkColor=records
linkWidth=records
linkWidth=sum-_value_
linkWidth=avg-_value_
linkColor=sum-_value_
linkColor=avg-_value_
linkColor=
```
--------------------------------
### Control Graph Simulation Forces with Cosmograph
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
This code configures various force parameters to customize the graph's layout and simulation behavior. It allows adjustment of repulsion, link attraction, gravity, and other physics-based properties to achieve desired node distribution. Requires the Cosmograph library.
```typescript
import { Cosmograph } from '@cosmograph/cosmograph'
const cosmograph = new Cosmograph(container)
cosmograph.setConfig({
// Increase repulsion for more spread out nodes
simulationRepulsion: 0.5,
// Stronger link attraction
simulationLinkSpring: 1.5,
// Minimum distance between linked nodes
simulationLinkDistance: 5,
// Pull nodes toward center
simulationGravity: 0.2,
// Slower cooldown for longer simulation
simulationDecay: 5000,
// Lower friction for faster movement
simulationFriction: 0.75,
// Enable quadtree for better performance (experimental)
useQuadtree: false,
// Mouse repulsion on right-click
simulationRepulsionFromMouse: 3.0
})
cosmograph.setData(nodes, links)
// Control simulation programmatically
cosmograph.pause()
setTimeout(() => cosmograph.restart(), 2000)
```
--------------------------------
### Configure Cosmograph with Props (React)
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Illustrates passing configuration options like node color, size, and link width as props to the Cosmograph component in a React application. React manages updates automatically.
```jsx
d.color} nodeSize={20} linkWidth={2} />
```
--------------------------------
### Customize Node Appearance with Methods (JS/TS)
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Library/Cosmograph
Illustrates customizing node appearance in JavaScript/TypeScript by providing functions to the `nodeSize` and `nodeColor` properties within the configuration object passed to `setConfig`. This allows for dynamic styling of nodes.
```javascript
const config = {
nodeSize: (n, i) => n.size,
nodeColor: (n, i) => n.color,
}
cosmograph.setConfig(config)
```
--------------------------------
### Custom Styling and Simulation Settings in Cosmograph
Source: https://context7.com/context7/cosmograph_app_cosmograph/llms.txt
This Python code demonstrates advanced customization of a Cosmograph visualization. It includes detailed configuration for point and link appearance, physics simulation parameters, visual settings like background color and zoom, label management, and performance options.
```python
import pandas as pd
from cosmograph import Cosmograph
points_df = pd.DataFrame({
'id': [f'node_{i}' for i in range(50)],
'category': ['A', 'B', 'C'] * 16 + ['A', 'B']
})
links_df = pd.DataFrame({
'source': [f'node_{i}' for i in range(49)],
'target': [f'node_{i+1}' for i in range(49)]
})
graph = Cosmograph(
points=points_df,
point_id_by='id',
point_color_by='category',
point_size=12,
point_size_scale=1.5,
links=links_df,
link_source_by='source',
link_target_by='target',
link_color='#666666',
link_width=2,
link_arrows=True,
curved_links=False,
# Simulation settings
disable_simulation=False,
simulation_repulsion=0.4,
simulation_link_spring=1.5,
simulation_link_distance=3,
simulation_gravity=0.1,
simulation_friction=0.8,
simulation_decay=2000,
# Visual settings
background_color='#0a0a0a',
scale_points_on_zoom=True,
initial_zoom_level=1.2,
# Labels
show_top_labels=True,
show_top_labels_limit=20,
show_hovered_point_label=True,
# Performance
pixel_ratio=2,
show_FPS_monitor=True
)
graph
```
--------------------------------
### Point Focus Methods
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20Python/configuration
Methods to set focus on a specific point, drawing a visual indicator around it.
```APIDOC
## `focus_point(id)`
### Description
Sets the focus on a specific point identified by its ID. A visual ring will be drawn around the focused point.
### Method
POST
### Endpoint
/websites/cosmograph_app_cosmograph/focus_point
### Parameters
#### Query Parameters
- **id** (string) - Required - The ID of the point to focus on.
### Request Example
```json
{
"id": "point_456"
}
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
## `focus_point_by_index(index)`
### Description
Sets the focus on a specific point identified by its index. A visual ring will be drawn around the focused point.
### Method
POST
### Endpoint
/websites/cosmograph_app_cosmograph/focus_point_by_index
### Parameters
#### Query Parameters
- **index** (integer) - Required - The index of the point to focus on.
### Request Example
```json
{
"index": 7
}
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the success of the operation.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### Graph Properties API
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20JavaScript/Cosmograph
Access to graph-level properties.
```APIDOC
## maxPointSize
### Description
_Getter_. Returns a numeric value that represents the maximum point size. This value is the maximum size of the `gl.POINTS` primitive that **WebGL** can render on the user's hardware.
### Method
Getter
### Endpoint
N/A
### Parameters
N/A
### Request Example
```javascript
const maxSize = maxPointSize;
```
### Response
#### Success Response (200)
- **maxPointSize** (number) - The maximum renderable point size.
#### Response Example
```json
{
"maxPointSize": 64
}
```
```
--------------------------------
### Configure Cosmograph Simulation Forces (React)
Source: https://cosmograph.app/docs/cosmograph/Cosmograph%20JavaScript/Cosmograph
This snippet shows how to configure simulation forces directly within the Cosmograph React component using props. It sets friction, link spring, and link distance to specific values. These props allow for immediate visual tuning of the simulation's behavior.
```jsx
```