Add web-enhanced infinite agentic loop with progressive learning
Extends the infinite loop pattern with web crawling integration, enabling agents to learn from documentation, tutorials, and examples on each iteration. Each agent fetches unique URLs, extracts techniques, and applies learnings to create progressively sophisticated outputs. Key additions: - /project:infinite-web command with URL strategy and web priming - D3 visualization spec with progressive learning pathway - Curated URL strategy (foundation → expert) with 40+ resources - Comprehensive guide for creating custom web-enhanced loops - Demo: 3 D3 visualizations with selections, scales, and bar charts System supports pre-defined URLs, dynamic web search, and parallel agents with unique web research assignments. Generalizable to any domain where progressive web-based knowledge acquisition improves output quality. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
189d92a771
commit
0d28f88fcc
|
|
@ -0,0 +1,388 @@
|
|||
**WEB-ENHANCED INFINITE AGENTIC LOOP COMMAND**
|
||||
|
||||
Think deeply about this web-enhanced infinite generation task. You are about to embark on a sophisticated iterative creation process with progressive web-based knowledge acquisition.
|
||||
|
||||
**Variables:**
|
||||
|
||||
spec_file: $ARGUMENTS
|
||||
output_dir: $ARGUMENTS
|
||||
count: $ARGUMENTS
|
||||
url_strategy_file: $ARGUMENTS (optional, defaults to specs/d3_url_strategy.json)
|
||||
|
||||
**ARGUMENTS PARSING:**
|
||||
Parse the following arguments from "$ARGUMENTS":
|
||||
1. `spec_file` - Path to the markdown specification file (required)
|
||||
2. `output_dir` - Directory where iterations will be saved (required)
|
||||
3. `count` - Number of iterations (1-N or "infinite") (required)
|
||||
4. `url_strategy_file` - Path to URL strategy JSON (optional, defaults to specs/d3_url_strategy.json)
|
||||
|
||||
**PHASE 0: INITIAL WEB PRIMING**
|
||||
|
||||
Before generating any iterations, perform deep web research to establish foundational knowledge:
|
||||
|
||||
**Priming Objectives:**
|
||||
1. Read the specification file completely to understand the domain and requirements
|
||||
2. If url_strategy_file exists, read it and extract priming URLs
|
||||
3. Fetch 3-5 foundational web resources using WebFetch or WebSearch:
|
||||
- Official documentation pages
|
||||
- Comprehensive tutorials
|
||||
- Pattern libraries or galleries
|
||||
- Best practices guides
|
||||
- Recent updates and new features
|
||||
|
||||
**Priming Web Research Tasks:**
|
||||
For each priming URL:
|
||||
- Use WebFetch to retrieve and analyze content
|
||||
- Extract key concepts, techniques, and patterns
|
||||
- Build mental model of the domain
|
||||
- Identify progressive learning pathways
|
||||
- Note important code patterns and best practices
|
||||
|
||||
**Priming Synthesis:**
|
||||
Create a comprehensive knowledge base from web research:
|
||||
- Core concepts and terminology
|
||||
- Common patterns and anti-patterns
|
||||
- Technical foundations (APIs, libraries, methods)
|
||||
- Visual design principles (if applicable)
|
||||
- Accessibility considerations
|
||||
- Performance optimization strategies
|
||||
|
||||
**PHASE 1: SPECIFICATION + WEB CONTEXT ANALYSIS**
|
||||
|
||||
Read and deeply understand the specification file at `spec_file` in conjunction with priming knowledge:
|
||||
- What type of content to generate (enhanced by web learnings)
|
||||
- Format and structure requirements
|
||||
- Specific parameters or constraints
|
||||
- Intended evolution pattern between iterations
|
||||
- How web research should enhance each iteration
|
||||
|
||||
**Web Integration Strategy:**
|
||||
- How should each iteration incorporate new web knowledge?
|
||||
- What makes a valuable web source for this domain?
|
||||
- How should learnings accumulate across iterations?
|
||||
- What URL selection strategy best serves the goal?
|
||||
|
||||
**PHASE 2: OUTPUT DIRECTORY + URL TRACKING RECONNAISSANCE**
|
||||
|
||||
Thoroughly analyze the `output_dir` to understand current state:
|
||||
- List all existing files and their naming patterns
|
||||
- Identify the highest iteration number currently present
|
||||
- Analyze content evolution across existing iterations
|
||||
- Review which URLs have already been used (check file footers/comments)
|
||||
- Build list of USED_URLS to avoid duplication
|
||||
- Understand the trajectory of previous generations
|
||||
- Identify knowledge gaps that new web research could fill
|
||||
|
||||
**URL Strategy Analysis:**
|
||||
If url_strategy_file exists:
|
||||
- Read and parse the JSON structure
|
||||
- Extract URLs categorized by iteration range
|
||||
- Understand the progressive difficulty curve
|
||||
- Note web search templates for dynamic discovery
|
||||
- Plan URL assignment for upcoming iterations
|
||||
|
||||
**PHASE 3: WEB-ENHANCED ITERATION STRATEGY**
|
||||
|
||||
Based on spec analysis, priming knowledge, and existing iterations:
|
||||
|
||||
**Iteration Planning:**
|
||||
- Determine starting iteration number (highest existing + 1)
|
||||
- Plan how each iteration will be unique and evolutionary
|
||||
- Map iteration numbers to appropriate URL complexity level
|
||||
- Assign specific web sources to each planned iteration
|
||||
- Consider how to build upon previous iterations + new web knowledge
|
||||
|
||||
**URL Assignment Strategy:**
|
||||
|
||||
For each upcoming iteration, determine web source:
|
||||
|
||||
1. **Pre-defined URL Mode** (if url_strategy_file exists):
|
||||
- Match iteration number to URL category (foundation, intermediate, advanced, expert)
|
||||
- Select next unused URL from appropriate category
|
||||
- Ensure no duplicate URLs across iterations
|
||||
- Track assigned URLs in USED_URLS list
|
||||
|
||||
2. **Dynamic Search Mode** (fallback or primary):
|
||||
- Generate targeted web search queries based on:
|
||||
- Current iteration number
|
||||
- Previous iteration analysis
|
||||
- Identified knowledge gaps
|
||||
- Specific technique to explore
|
||||
- Use WebSearch to find relevant resources
|
||||
- Select most valuable result for the iteration
|
||||
|
||||
3. **Hybrid Mode** (recommended):
|
||||
- Use pre-defined URLs for core techniques
|
||||
- Use dynamic search for novel explorations
|
||||
- Balance structure with discovery
|
||||
|
||||
**PHASE 4: PARALLEL WEB-ENHANCED AGENT COORDINATION**
|
||||
|
||||
Deploy multiple Sub Agents with individualized web research assignments for maximum efficiency and learning diversity:
|
||||
|
||||
**Sub-Agent Distribution Strategy:**
|
||||
- For count 1-3: Launch all agents simultaneously with different URLs
|
||||
- For count 4-10: Launch in batches of 3-4 agents to manage web requests
|
||||
- For count 11+: Launch in batches of 5 agents to optimize coordination
|
||||
- For "infinite": Launch waves of 3-4 agents, monitoring context and web source availability
|
||||
|
||||
**Agent Assignment Protocol:**
|
||||
|
||||
Each Sub Agent receives:
|
||||
1. **Spec Context**: Complete specification file analysis + priming knowledge summary
|
||||
2. **Directory Snapshot**: Current state of output_dir at launch time
|
||||
3. **Iteration Assignment**: Specific iteration number (starting_number + agent_index)
|
||||
4. **Web Research Assignment**: Specific URL to fetch and learn from
|
||||
5. **Used URLs List**: All previously used URLs to avoid duplication
|
||||
6. **Uniqueness Directive**: Explicit instruction to avoid duplicating previous concepts
|
||||
7. **Quality Standards**: Detailed requirements from the specification
|
||||
8. **Integration Directive**: How to synthesize web learning with previous work
|
||||
|
||||
**Agent Task Specification:**
|
||||
```
|
||||
TASK: Generate iteration [NUMBER] for [SPEC_FILE] with web research integration
|
||||
|
||||
You are Sub Agent [X] generating iteration [NUMBER] with web-enhanced learning.
|
||||
|
||||
WEB RESEARCH ASSIGNMENT:
|
||||
- Your assigned URL: [SPECIFIC_URL]
|
||||
- Topic: [URL_TOPIC]
|
||||
- Your mission: Fetch this URL, learn a specific technique, and apply it to your iteration
|
||||
|
||||
RESEARCH PROCESS:
|
||||
1. Use WebFetch tool to retrieve content from [SPECIFIC_URL]
|
||||
2. Analyze the content deeply for:
|
||||
- New techniques, APIs, or patterns
|
||||
- Code examples and implementations
|
||||
- Visual design principles (if applicable)
|
||||
- Best practices and optimizations
|
||||
- Accessibility considerations
|
||||
3. Extract 1-3 specific learnings to apply to your iteration
|
||||
4. Plan how to integrate these learnings with the specification requirements
|
||||
|
||||
CONTEXT:
|
||||
- Specification: [Full spec analysis]
|
||||
- Priming knowledge: [Summary of initial web research]
|
||||
- Existing iterations: [Summary of current output_dir contents]
|
||||
- Used URLs: [List of URLs already researched to avoid duplication]
|
||||
- Your iteration number: [NUMBER]
|
||||
- Expected complexity level: [foundation/intermediate/advanced/expert]
|
||||
|
||||
REQUIREMENTS:
|
||||
1. FIRST: Fetch and analyze your assigned URL using WebFetch
|
||||
2. Extract specific technique(s) from the web source
|
||||
3. Read and understand the specification completely
|
||||
4. Analyze existing iterations to ensure your output is unique
|
||||
5. Generate content that:
|
||||
- Follows spec format exactly
|
||||
- Applies learning from your web source
|
||||
- Builds upon previous iterations where appropriate
|
||||
- Introduces genuine novelty and improvement
|
||||
6. Document your web source and what you learned in the output file
|
||||
7. Create file with exact name pattern specified
|
||||
|
||||
DELIVERABLE:
|
||||
- Single file as specified by spec
|
||||
- Must demonstrate learning from assigned URL
|
||||
- Must document web source and improvements
|
||||
- Must be genuinely enhanced by web research
|
||||
|
||||
CRITICAL: If WebFetch fails, fall back to WebSearch for the topic and find alternative source.
|
||||
```
|
||||
|
||||
**Parallel Execution Management:**
|
||||
- Launch assigned Sub Agents in batches to avoid overwhelming web services
|
||||
- Each agent performs independent WebFetch for their assigned URL
|
||||
- Monitor agent progress and web fetch completion
|
||||
- Handle web fetch failures by reassigning different URLs
|
||||
- Ensure no duplicate URLs across parallel agents in same batch
|
||||
- Collect and validate all completed iterations
|
||||
- Verify that web learnings were actually applied
|
||||
|
||||
**PHASE 5: INFINITE WEB-ENHANCED MODE ORCHESTRATION**
|
||||
|
||||
For infinite generation mode, orchestrate continuous waves with progressive web learning:
|
||||
|
||||
**Wave-Based Web Learning Strategy:**
|
||||
1. **Wave Planning**:
|
||||
- Determine next wave size (3-4 agents) based on context capacity
|
||||
- Select URL category for wave (foundation → intermediate → advanced → expert)
|
||||
- Identify unused URLs in target category
|
||||
- Plan specific URL assignment for each agent in wave
|
||||
|
||||
2. **Progressive URL Difficulty**:
|
||||
- Wave 1: Foundation URLs (basic concepts)
|
||||
- Wave 2: Intermediate URLs (common patterns)
|
||||
- Wave 3: Advanced URLs (complex techniques)
|
||||
- Wave 4+: Expert URLs + dynamic searches for cutting-edge techniques
|
||||
|
||||
3. **Knowledge Accumulation**:
|
||||
- Each wave builds on previous waves' learnings
|
||||
- Later agents can reference earlier iterations' web discoveries
|
||||
- Progressive complexity in both content and web sources
|
||||
- Synthesis of multiple web learnings in later iterations
|
||||
|
||||
4. **URL Exhaustion Handling**:
|
||||
- If pre-defined URLs exhausted, switch to dynamic WebSearch mode
|
||||
- Generate targeted search queries based on:
|
||||
- Current iteration sophistication level
|
||||
- Gaps in previous iterations
|
||||
- Novel techniques to explore
|
||||
- Continue until context limits approached
|
||||
|
||||
**Infinite Execution Cycle:**
|
||||
```
|
||||
INITIALIZE:
|
||||
- Load url_strategy_file
|
||||
- Extract all available URLs by category
|
||||
- Initialize USED_URLS tracker
|
||||
- Initialize current_difficulty_level = "foundation"
|
||||
|
||||
WHILE context_capacity > threshold:
|
||||
WAVE_SETUP:
|
||||
1. Assess current output_dir state
|
||||
2. Count existing iterations
|
||||
3. Determine appropriate difficulty level for next wave
|
||||
4. Select 3-4 unused URLs from current difficulty category
|
||||
5. If no URLs available, increment difficulty level or switch to dynamic search
|
||||
|
||||
AGENT_PREPARATION:
|
||||
For each agent in wave:
|
||||
- Assign unique iteration number
|
||||
- Assign unique URL from selected batch
|
||||
- Prepare context snapshot
|
||||
- Add URL to USED_URLS tracker
|
||||
|
||||
EXECUTION:
|
||||
6. Launch parallel Sub Agent wave with web assignments
|
||||
7. Monitor wave completion and web fetch success
|
||||
8. Validate that web learnings were applied
|
||||
|
||||
POST_WAVE:
|
||||
9. Update directory state snapshot
|
||||
10. Review iteration quality and web integration
|
||||
11. Evaluate context capacity remaining
|
||||
12. If sufficient capacity: Continue to next wave
|
||||
13. If approaching limits: Complete final wave and summarize
|
||||
|
||||
DIFFICULTY_PROGRESSION:
|
||||
- Waves 1-2: foundation URLs
|
||||
- Waves 3-4: intermediate URLs
|
||||
- Waves 5-6: advanced URLs
|
||||
- Waves 7+: expert URLs + dynamic discovery
|
||||
```
|
||||
|
||||
**Dynamic Web Search Integration:**
|
||||
|
||||
When pre-defined URLs are exhausted or for novel exploration:
|
||||
|
||||
**Search Query Generation:**
|
||||
- Analyze current iteration goals
|
||||
- Identify knowledge gaps from previous iterations
|
||||
- Generate targeted search queries using templates from url_strategy_file
|
||||
- Example: "D3.js force simulation collision detection site:observablehq.com"
|
||||
|
||||
**Search Result Selection:**
|
||||
- Use WebSearch to find relevant resources
|
||||
- Evaluate search results for quality and relevance
|
||||
- Select top result not in USED_URLS
|
||||
- Assign to agent with clear learning objectives
|
||||
|
||||
**PHASE 6: WEB INTEGRATION QUALITY ASSURANCE**
|
||||
|
||||
After each wave completion, verify web integration quality:
|
||||
|
||||
**Quality Checks:**
|
||||
1. **Web Source Attribution**: Each iteration documents its URL source
|
||||
2. **Learning Application**: Specific technique from URL is actually implemented
|
||||
3. **Improvement Evidence**: Iteration shows measurable improvement
|
||||
4. **Uniqueness**: No duplicate web sources, no duplicate implementations
|
||||
5. **Spec Compliance**: Meets all specification requirements
|
||||
6. **Cumulative Progress**: Builds upon previous iterations appropriately
|
||||
|
||||
**Failure Handling:**
|
||||
- If agent fails to fetch URL: Reassign with backup URL or web search
|
||||
- If agent doesn't apply learning: Regenerate with clearer directive
|
||||
- If URL already used: Select next available URL in category
|
||||
- If web source unavailable: Fall back to dynamic web search
|
||||
|
||||
**EXECUTION PRINCIPLES:**
|
||||
|
||||
**Progressive Web Learning:**
|
||||
- Each iteration incorporates new web-sourced knowledge
|
||||
- Knowledge accumulates across iterations
|
||||
- Later iterations can build upon earlier web discoveries
|
||||
- Balance between learning new techniques and mastering previous ones
|
||||
|
||||
**Quality & Uniqueness:**
|
||||
- Each iteration must be genuinely unique and valuable
|
||||
- Web research must genuinely enhance the output
|
||||
- Build upon previous work while introducing novel elements
|
||||
- Maintain consistency with original specification
|
||||
- Document web sources and learnings clearly
|
||||
|
||||
**Parallel Web Coordination:**
|
||||
- Deploy Sub Agents strategically with diverse web sources
|
||||
- Assign different URLs to each agent in a wave
|
||||
- Coordinate timing to avoid web service rate limiting
|
||||
- Monitor web fetch success and content extraction
|
||||
- Ensure all agents successfully integrate their web learnings
|
||||
|
||||
**Scalability & Efficiency:**
|
||||
- Batch web requests to avoid overwhelming services
|
||||
- Cache web content for potential reuse in context
|
||||
- Track used URLs rigorously to avoid duplication
|
||||
- Optimize URL selection for progressive learning curve
|
||||
- Balance parallel speed with web fetch reliability
|
||||
|
||||
**ULTRA-THINKING DIRECTIVE:**
|
||||
|
||||
Before beginning generation, engage in extended thinking about:
|
||||
|
||||
**Web Research Strategy:**
|
||||
- What web sources will provide the most value?
|
||||
- How should URL difficulty progress across iterations?
|
||||
- What's the optimal balance between pre-defined URLs and dynamic search?
|
||||
- How can web learnings accumulate most effectively?
|
||||
- What makes a web source genuinely useful vs. superficial?
|
||||
|
||||
**Specification & Web Synergy:**
|
||||
- How does web research enhance the specification goals?
|
||||
- What web knowledge is most critical for success?
|
||||
- How should iterations balance spec requirements with web inspiration?
|
||||
- What progressive learning pathway serves the goal best?
|
||||
|
||||
**Parallel Web Coordination:**
|
||||
- Optimal Sub Agent distribution for web-enhanced generation
|
||||
- How to assign URLs for maximum learning diversity
|
||||
- Managing web fetch timing and rate limits
|
||||
- Ensuring each agent extracts valuable, applicable learnings
|
||||
- Preventing duplicate web sources across parallel streams
|
||||
|
||||
**Knowledge Integration:**
|
||||
- How should agents synthesize web content with spec requirements?
|
||||
- What level of detail from web sources should be applied?
|
||||
- How to build upon previous iterations' web discoveries?
|
||||
- Balancing novelty from web vs. consistency with previous work
|
||||
|
||||
**Infinite Mode Web Optimization:**
|
||||
- Progressive URL difficulty strategy across waves
|
||||
- When to switch from pre-defined URLs to dynamic search
|
||||
- Balancing web research depth vs. breadth
|
||||
- Context management with web content inclusion
|
||||
- Quality control for web-enhanced parallel outputs
|
||||
|
||||
**Risk Mitigation:**
|
||||
- Handling web fetch failures gracefully
|
||||
- Ensuring web learnings are actually applied, not just mentioned
|
||||
- Managing URL exhaustion in long runs
|
||||
- Preventing superficial web integration
|
||||
- Maintaining spec compliance despite web inspiration
|
||||
|
||||
**Quality Assurance:**
|
||||
- How to verify that web research genuinely improved output?
|
||||
- What evidence shows learning application vs. mere citation?
|
||||
- How to ensure cumulative knowledge building?
|
||||
- Balancing web fidelity with creative adaptation?
|
||||
|
||||
Begin execution with deep analysis of the web-enhanced learning strategy and proceed systematically through each phase, leveraging Sub Agents with individualized web research assignments for maximum knowledge acquisition and creative output.
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# Context The Full Initial Infinite Agentic Loop
|
||||
|
||||
RUN:
|
||||
git ls-files
|
||||
|
||||
READ:
|
||||
ai_docs/full-initial.md
|
||||
72
CLAUDE.md
72
CLAUDE.md
|
|
@ -8,7 +8,7 @@ This is an experimental project demonstrating the Infinite Agentic Loop pattern
|
|||
|
||||
## Key Commands
|
||||
|
||||
### Running the Infinite Agentic Loop
|
||||
### Running the Original Infinite Agentic Loop
|
||||
|
||||
```bash
|
||||
claude
|
||||
|
|
@ -30,34 +30,88 @@ Then use the `/project:infinite` slash command with these variants:
|
|||
/project:infinite specs/invent_new_ui_v3.md infinite_src_new/ infinite
|
||||
```
|
||||
|
||||
### Running the Web-Enhanced Infinite Loop (NEW!)
|
||||
|
||||
The `/project:infinite-web` command adds progressive web-based learning where each iteration fetches and learns from web resources:
|
||||
|
||||
```bash
|
||||
# Single D3 visualization with web learning
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_viz 1
|
||||
|
||||
# Batch of 5 with different web sources
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_viz 5
|
||||
|
||||
# Progressive learning (20 iterations from foundation → expert)
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_viz 20 specs/d3_url_strategy.json
|
||||
|
||||
# Infinite mode - continuous learning until context limits
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_viz infinite specs/d3_url_strategy.json
|
||||
```
|
||||
|
||||
**Key Enhancement:** Each iteration fetches a web URL, learns specific techniques, and applies them to create progressively sophisticated outputs. See [WEB_ENHANCED_GUIDE.md](WEB_ENHANCED_GUIDE.md) for details.
|
||||
|
||||
## Architecture & Structure
|
||||
|
||||
### Command System
|
||||
The project uses Claude Code's custom commands feature:
|
||||
- `.claude/commands/infinite.md` - Main infinite loop orchestrator command
|
||||
- `.claude/commands/prime.md` - Additional command (if present)
|
||||
- `.claude/commands/infinite.md` - Original infinite loop orchestrator command
|
||||
- `.claude/commands/infinite-web.md` - NEW! Web-enhanced loop with progressive learning
|
||||
- `.claude/commands/prime.md` - Context priming command
|
||||
- `.claude/commands/prime-initial.md` - Initial context loading command
|
||||
- `.claude/settings.json` - Permissions configuration allowing Write, MultiEdit, Edit, and Bash
|
||||
|
||||
### Specification-Driven Generation
|
||||
- Specifications in `specs/` directory define what type of content to generate
|
||||
- Current main spec: `specs/invent_new_ui_v3.md` - Themed Hybrid UI Component Specification
|
||||
- Specs define naming patterns, content structure, design dimensions, and quality standards
|
||||
- **Original Specs:**
|
||||
- `specs/invent_new_ui_v3.md` - Themed Hybrid UI Component Specification
|
||||
- `specs/invent_new_ui_v4.md` - Modular architecture variant (3-file structure)
|
||||
- **Web-Enhanced Specs (NEW!):**
|
||||
- `specs/d3_visualization_progressive.md` - D3.js visualizations with progressive web learning
|
||||
- `specs/d3_url_strategy.json` - Curated URL progression for D3 learning
|
||||
- Specs define naming patterns, content structure, design dimensions, quality standards, and web integration strategy
|
||||
|
||||
### Multi-Agent Orchestration Pattern
|
||||
The infinite command implements sophisticated parallel agent coordination:
|
||||
Both infinite commands implement sophisticated parallel agent coordination:
|
||||
|
||||
**Original Pattern (`/project:infinite`):**
|
||||
1. **Specification Analysis** - Deeply understands the spec requirements
|
||||
2. **Directory Reconnaissance** - Analyzes existing iterations to maintain uniqueness
|
||||
3. **Parallel Sub-Agent Deployment** - Launches multiple agents with distinct creative directions
|
||||
4. **Wave-Based Generation** - For infinite mode, manages successive agent waves
|
||||
5. **Context Management** - Optimizes context usage across all agents
|
||||
|
||||
**Web-Enhanced Pattern (`/project:infinite-web` - NEW!):**
|
||||
1. **Initial Web Priming** - Fetches foundational web resources to build knowledge base
|
||||
2. **Specification + Web Context Analysis** - Understands spec with web knowledge integration
|
||||
3. **URL Strategy Planning** - Maps iterations to progressive difficulty URLs
|
||||
4. **Parallel Web-Enhanced Agents** - Each agent fetches unique URL, learns, and generates
|
||||
5. **Progressive Wave Learning** - Each wave increases sophistication with expert URLs
|
||||
6. **Knowledge Accumulation** - Later iterations build on earlier web discoveries
|
||||
|
||||
### Generated Content Organization
|
||||
- `src/` - Primary output directory for generated UI components
|
||||
- `src_infinite/` - Alternative output for infinite generation runs
|
||||
**Original Loop Outputs:**
|
||||
- `src/` - Primary output directory for themed hybrid UI components (35 files)
|
||||
- `src_infinite/` - Infinite mode UI generations (25 files)
|
||||
- `src_group/` - Modular 3-file architecture components (5 directories)
|
||||
- `legacy/` - Previous iteration attempts and experiments
|
||||
|
||||
**Web-Enhanced Loop Outputs (NEW!):**
|
||||
- `d3_viz/` - D3 visualizations with progressive web learning (create with `/project:infinite-web`)
|
||||
- Each output file documents its web source and learning application
|
||||
|
||||
### Key Implementation Details
|
||||
**Original Loop:**
|
||||
- Sub-agents receive complete context including spec, existing iterations, and unique creative assignments
|
||||
- Parallel execution managed through Task tool with batch sizes optimized by count
|
||||
- Progressive sophistication strategy for infinite mode waves
|
||||
- Each iteration must be genuinely unique while maintaining spec compliance
|
||||
- Each iteration must be genuinely unique while maintaining spec compliance
|
||||
|
||||
**Web-Enhanced Loop (NEW!):**
|
||||
- Initial web priming phase fetches 3-5 foundational resources before generation
|
||||
- Each sub-agent assigned unique URL to fetch and learn from
|
||||
- WebFetch or WebSearch tools used to retrieve documentation, tutorials, examples
|
||||
- Agents extract 1-3 specific techniques from web source and apply to output
|
||||
- URL tracking prevents duplicate web sources across iterations
|
||||
- Progressive URL difficulty: foundation → intermediate → advanced → expert
|
||||
- Dynamic web search fallback when pre-defined URLs exhausted
|
||||
- All outputs document web source and demonstrate learning application
|
||||
67
README.md
67
README.md
|
|
@ -2,13 +2,24 @@
|
|||
|
||||
> **Watch the Tutorial**: [Infinite Agentic Loop with Claude Code](https://youtu.be/9ipM_vDwflI)
|
||||
|
||||
An experimental project demonstrating Infinite Agentic Loop in a two prompt system using Claude Code.
|
||||
An experimental project demonstrating Infinite Agentic Loop patterns using Claude Code - now with **Web-Enhanced Progressive Learning**!
|
||||
|
||||
<img src="images/infinite-claude-img.png" alt="Infinite Agentic Loop" style="max-width: 800px; width: 100%;">
|
||||
|
||||
## Overview
|
||||
|
||||
This project uses a custom Claude Code slash command (`/project:infinite`) to orchestrate multiple AI agents in parallel, generating evolving iterations of content based on specifications.
|
||||
This project provides two powerful slash commands for orchestrating multiple AI agents in parallel:
|
||||
|
||||
1. **`/project:infinite`** - Original loop for generating evolving iterations based on specifications
|
||||
2. **`/project:infinite-web`** - NEW! Web-enhanced loop where each iteration learns from web resources
|
||||
|
||||
### What's New: Web-Enhanced Learning
|
||||
|
||||
The new `/project:infinite-web` command creates a **self-improving knowledge loop** where:
|
||||
- Each iteration fetches and learns from a different web URL
|
||||
- Knowledge progressively accumulates across iterations
|
||||
- Agents apply learnings from documentation, tutorials, and examples
|
||||
- Output quality improves as the system learns more sophisticated techniques
|
||||
|
||||
## Usage
|
||||
|
||||
|
|
@ -49,7 +60,37 @@ Generate 20 iterations in coordinated batches of 5 agents for optimal resource m
|
|||
```
|
||||
Continuous generation in waves until context limits are reached, with progressive sophistication.
|
||||
|
||||
## How It Works
|
||||
## Web-Enhanced Command (NEW!)
|
||||
|
||||
### D3 Data Visualization Example
|
||||
|
||||
Generate progressively sophisticated D3 visualizations with web-based learning:
|
||||
|
||||
```bash
|
||||
# Single visualization with web learning
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_output 1
|
||||
|
||||
# Batch of 5 with different web sources
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_output 5
|
||||
|
||||
# Progressive learning (20 iterations)
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_output 20 specs/d3_url_strategy.json
|
||||
|
||||
# Infinite mode - continuous learning
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_output infinite specs/d3_url_strategy.json
|
||||
```
|
||||
|
||||
**How It Works:**
|
||||
1. **Initial Priming**: Fetches 3-5 foundational web resources to build knowledge base
|
||||
2. **Progressive URL Assignment**: Each iteration gets a URL matched to its complexity level
|
||||
3. **Web Fetch & Learn**: Agent fetches URL, extracts techniques, applies learnings
|
||||
4. **Generate & Document**: Creates output demonstrating new technique, documents source
|
||||
5. **Accumulate Knowledge**: Each iteration builds on previous learnings
|
||||
6. **Infinite Waves**: Continues with progressive sophistication until context limits
|
||||
|
||||
See [WEB_ENHANCED_GUIDE.md](WEB_ENHANCED_GUIDE.md) for complete documentation and how to create your own web-enhanced loops!
|
||||
|
||||
## How the Original Loop Works
|
||||
|
||||
1. **Specification Analysis**: Reads and understands the spec file requirements
|
||||
2. **Directory Reconnaissance**: Analyzes existing iterations to determine starting point
|
||||
|
|
@ -59,10 +100,22 @@ Continuous generation in waves until context limits are reached, with progressiv
|
|||
|
||||
## Directions you can take to enhance this pattern
|
||||
|
||||
- Apply this to a use case of your choice.
|
||||
- Build an MCP Server that enables reuse of the infinite agentic loop.
|
||||
- Get the `.claude/commands/infinite.md` into your `~/.claude/commands/` directory for global use.
|
||||
- Update `.claude/commands/infinite.md` to generate sets of files instead of a single file.
|
||||
### Original Loop Enhancements
|
||||
- Apply this to a use case of your choice
|
||||
- Build an MCP Server that enables reuse of the infinite agentic loop
|
||||
- Get the `.claude/commands/infinite.md` into your `~/.claude/commands/` directory for global use
|
||||
- Update `.claude/commands/infinite.md` to generate sets of files instead of a single file
|
||||
|
||||
### Web-Enhanced Loop Possibilities
|
||||
- **React Components**: Progressive React patterns from official docs, popular libraries, and best practices
|
||||
- **CSS Techniques**: Master CSS animations, layouts, and effects through web tutorials
|
||||
- **Python Data Science**: Learn pandas, matplotlib, seaborn through progressive web examples
|
||||
- **Machine Learning**: Implement progressively complex ML models with paper and tutorial learnings
|
||||
- **API Development**: Build REST/GraphQL APIs learning from official documentation
|
||||
- **Game Development**: Create progressively complex games learning from web tutorials
|
||||
- **Any Domain**: Create your own spec + URL strategy for any progressive learning goal
|
||||
|
||||
See [WEB_ENHANCED_GUIDE.md](WEB_ENHANCED_GUIDE.md) for detailed instructions on creating your own web-enhanced loops!
|
||||
|
||||
## Master AI Coding
|
||||
Learn to code with AI with foundational [Principles of AI Coding](https://agenticengineer.com/principled-ai-coding?y=infageloop)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,560 @@
|
|||
# Web-Enhanced Infinite Agentic Loop Guide
|
||||
|
||||
## Overview
|
||||
|
||||
The **Web-Enhanced Infinite Agentic Loop** extends the original infinite loop pattern with progressive web-based knowledge acquisition. Each iteration fetches and learns from web resources, creating a self-improving system that gets smarter with each generation.
|
||||
|
||||
## Core Innovation
|
||||
|
||||
**Traditional Loop:**
|
||||
```
|
||||
Spec → Generate → Iterate → Generate → Iterate...
|
||||
```
|
||||
|
||||
**Web-Enhanced Loop:**
|
||||
```
|
||||
Spec → Web Prime → [Fetch URL → Learn → Generate]* → Iterate...
|
||||
↑_______________|
|
||||
```
|
||||
|
||||
Each iteration:
|
||||
1. Fetches a NEW web resource (URL)
|
||||
2. Learns specific techniques from that resource
|
||||
3. Applies learnings to create improved output
|
||||
4. Documents what was learned and how it was applied
|
||||
|
||||
## System Components
|
||||
|
||||
### 1. Specification File (`specs/*.md`)
|
||||
Defines what to generate and how web research should enhance it.
|
||||
|
||||
**Example:** `specs/d3_visualization_progressive.md`
|
||||
- Output format and structure
|
||||
- Quality standards
|
||||
- Progressive enhancement dimensions
|
||||
- Web integration strategy
|
||||
- Success criteria
|
||||
|
||||
### 2. URL Strategy File (`specs/*_url_strategy.json`)
|
||||
Curated knowledge pathway with URLs organized by difficulty.
|
||||
|
||||
**Structure:**
|
||||
```json
|
||||
{
|
||||
"priming_urls": [...], // Initial research URLs
|
||||
"foundation_urls": [...], // Iterations 1-5
|
||||
"intermediate_urls": [...], // Iterations 6-12
|
||||
"advanced_urls": [...], // Iterations 13-20
|
||||
"expert_urls": [...], // Iterations 21+
|
||||
"web_search_templates": [...] // Dynamic search fallbacks
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Command: `/project:infinite-web`
|
||||
Orchestrates the web-enhanced generation process.
|
||||
|
||||
**Location:** `.claude/commands/infinite-web.md`
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Command Structure
|
||||
|
||||
```bash
|
||||
/project:infinite-web <spec_file> <output_dir> <count> [url_strategy_file]
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `spec_file`: Path to specification markdown
|
||||
- `output_dir`: Where to save generated files
|
||||
- `count`: Number of iterations (1-N or "infinite")
|
||||
- `url_strategy_file`: (Optional) Path to URL strategy JSON
|
||||
|
||||
### Usage Examples
|
||||
|
||||
#### 1. Single D3 Visualization with Web Learning
|
||||
```bash
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_output 1
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
1. Reads D3 spec
|
||||
2. Performs initial web priming (3-5 foundational URLs)
|
||||
3. Selects one URL from foundation category
|
||||
4. Fetches URL, learns technique
|
||||
5. Generates `d3_viz_1.html` applying learning
|
||||
6. Documents web source in file footer
|
||||
|
||||
#### 2. Small Batch (5 Visualizations)
|
||||
```bash
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_output 5
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
1. Initial web priming phase
|
||||
2. Launches 5 parallel agents simultaneously
|
||||
3. Each agent gets different URL from foundation category
|
||||
4. Each agent fetches, learns, generates
|
||||
5. Produces 5 unique visualizations (d3_viz_1 through d3_viz_5)
|
||||
6. Each demonstrates different technique from different web source
|
||||
|
||||
#### 3. Progressive Learning (20 Iterations)
|
||||
```bash
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_output 20 specs/d3_url_strategy.json
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
1. Initial web priming
|
||||
2. Launches in batches of 5 agents
|
||||
3. Iterations 1-5: Foundation URLs (basic concepts)
|
||||
4. Iterations 6-12: Intermediate URLs (common patterns)
|
||||
5. Iterations 13-20: Advanced URLs (complex techniques)
|
||||
6. Each batch builds upon previous knowledge
|
||||
7. Progressive sophistication across all 20 outputs
|
||||
|
||||
#### 4. Infinite Mode - Continuous Learning
|
||||
```bash
|
||||
/project:infinite-web specs/d3_visualization_progressive.md d3_infinite infinite specs/d3_url_strategy.json
|
||||
```
|
||||
|
||||
**What happens:**
|
||||
1. Initial web priming
|
||||
2. Wave 1: 3-4 agents, foundation URLs
|
||||
3. Wave 2: 3-4 agents, intermediate URLs
|
||||
4. Wave 3: 3-4 agents, advanced URLs
|
||||
5. Wave 4+: Expert URLs, then dynamic web search
|
||||
6. Continues until context limits approached
|
||||
7. Each wave more sophisticated than last
|
||||
8. Graceful conclusion with summary
|
||||
|
||||
## How It Works
|
||||
|
||||
### Phase 0: Initial Web Priming
|
||||
|
||||
Before any generation, the system builds foundational knowledge:
|
||||
|
||||
```
|
||||
1. Read specification file
|
||||
2. Load URL strategy (if provided)
|
||||
3. Fetch 3-5 priming URLs:
|
||||
- Official documentation
|
||||
- Tutorials
|
||||
- Pattern libraries
|
||||
- Best practices
|
||||
4. Synthesize core concepts, patterns, principles
|
||||
5. Build mental model for domain
|
||||
```
|
||||
|
||||
### Phase 1-3: Analysis & Planning
|
||||
|
||||
```
|
||||
1. Analyze specification with priming knowledge
|
||||
2. Scan output directory for existing iterations
|
||||
3. Track which URLs have been used (avoid duplicates)
|
||||
4. Plan URL assignments for upcoming iterations
|
||||
5. Match iteration numbers to URL difficulty levels
|
||||
```
|
||||
|
||||
### Phase 4: Parallel Web-Enhanced Agents
|
||||
|
||||
Each sub-agent follows this process:
|
||||
|
||||
```
|
||||
SUB-AGENT WORKFLOW:
|
||||
├─ Receive assignment (iteration number + specific URL)
|
||||
├─ WebFetch assigned URL
|
||||
├─ Analyze content for techniques
|
||||
├─ Extract 1-3 specific learnings
|
||||
├─ Read specification
|
||||
├─ Review existing iterations
|
||||
├─ Generate output applying web learning
|
||||
├─ Document web source and improvements
|
||||
└─ Save file
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Each agent gets unique URL (no duplicates in batch)
|
||||
- Parallel execution for speed
|
||||
- Independent web research per agent
|
||||
- All learnings documented in output
|
||||
|
||||
### Phase 5: Infinite Mode Waves
|
||||
|
||||
```
|
||||
WAVE CYCLE:
|
||||
while (context_available):
|
||||
├─ Determine wave size (3-4 agents)
|
||||
├─ Select URL category (foundation → expert)
|
||||
├─ Assign unique URLs to each agent
|
||||
├─ Launch parallel agents
|
||||
├─ Monitor completion
|
||||
├─ Update used URLs tracker
|
||||
├─ Check context capacity
|
||||
└─ Prepare next wave (if capacity available)
|
||||
```
|
||||
|
||||
**Progressive Difficulty:**
|
||||
- Early waves: Foundational concepts
|
||||
- Mid waves: Common patterns and techniques
|
||||
- Later waves: Advanced and expert topics
|
||||
- Final waves: Dynamic web search for novel techniques
|
||||
|
||||
## URL Selection Strategies
|
||||
|
||||
### 1. Pre-defined URLs (Structured Learning)
|
||||
|
||||
**Advantages:**
|
||||
- Curated, high-quality sources
|
||||
- Progressive difficulty curve
|
||||
- Predictable learning pathway
|
||||
- Avoids low-quality content
|
||||
|
||||
**How it works:**
|
||||
```json
|
||||
// URL strategy file defines ranges
|
||||
{
|
||||
"foundation_urls": {
|
||||
"iteration_range": [1, 5],
|
||||
"urls": [
|
||||
{"url": "...", "topic": "Basic Bar Charts"},
|
||||
{"url": "...", "topic": "Scale Functions"},
|
||||
...
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Agent for iteration 3 gets URL from foundation_urls category.
|
||||
|
||||
### 2. Dynamic Web Search (Adaptive Discovery)
|
||||
|
||||
**Advantages:**
|
||||
- Finds latest resources
|
||||
- Adapts to specific needs
|
||||
- Never runs out of sources
|
||||
- Discovers novel techniques
|
||||
|
||||
**How it works:**
|
||||
```
|
||||
Agent determines knowledge gap
|
||||
→ Generates targeted search query
|
||||
→ Uses WebSearch tool
|
||||
→ Selects best result
|
||||
→ Fetches and learns from it
|
||||
```
|
||||
|
||||
**Example query generation:**
|
||||
```
|
||||
"D3.js force simulation collision detection site:observablehq.com"
|
||||
"D3 responsive design best practices 2024"
|
||||
"Advanced D3 network visualization techniques"
|
||||
```
|
||||
|
||||
### 3. Hybrid Mode (Recommended)
|
||||
|
||||
**Best of both worlds:**
|
||||
- Use pre-defined URLs for core curriculum
|
||||
- Fall back to dynamic search when URLs exhausted
|
||||
- Dynamic search for novel explorations
|
||||
- Structured foundation + adaptive innovation
|
||||
|
||||
## Creating Your Own Web-Enhanced Loop
|
||||
|
||||
### Step 1: Define Your Domain
|
||||
|
||||
Create a specification file for your domain:
|
||||
|
||||
**Template:** `specs/your_domain_progressive.md`
|
||||
|
||||
Key sections:
|
||||
- Core challenge and goals
|
||||
- Output format requirements
|
||||
- Progressive enhancement dimensions
|
||||
- Web research integration strategy
|
||||
- Quality standards
|
||||
- Iteration evolution pattern
|
||||
|
||||
### Step 2: Curate URL Strategy (Optional but Recommended)
|
||||
|
||||
Create URL strategy JSON: `specs/your_domain_url_strategy.json`
|
||||
|
||||
**Organize URLs by:**
|
||||
- Priming (foundational knowledge)
|
||||
- Foundation (basic techniques)
|
||||
- Intermediate (common patterns)
|
||||
- Advanced (complex implementations)
|
||||
- Expert (cutting-edge techniques)
|
||||
|
||||
**Include:**
|
||||
- Web search templates for dynamic discovery
|
||||
- Topic tags for each URL
|
||||
- Learning objectives
|
||||
|
||||
### Step 3: Run Your Loop
|
||||
|
||||
```bash
|
||||
/project:infinite-web specs/your_domain_progressive.md output_dir <count> specs/your_domain_url_strategy.json
|
||||
```
|
||||
|
||||
## Example Domains Beyond D3
|
||||
|
||||
### 1. React Component Library
|
||||
```bash
|
||||
# Spec: Progressive React component patterns
|
||||
# URLs: React docs, popular libraries, best practices
|
||||
# Output: Increasingly sophisticated React components
|
||||
/project:infinite-web specs/react_components_progressive.md react_output 20
|
||||
```
|
||||
|
||||
### 2. CSS Animation Techniques
|
||||
```bash
|
||||
# Spec: CSS animation mastery
|
||||
# URLs: CSS-Tricks, MDN, CodePen examples
|
||||
# Output: Progressive animation techniques
|
||||
/project:infinite-web specs/css_animations_progressive.md css_output infinite
|
||||
```
|
||||
|
||||
### 3. Python Data Science
|
||||
```bash
|
||||
# Spec: Data analysis and visualization
|
||||
# URLs: Pandas docs, Matplotlib gallery, Seaborn tutorials
|
||||
# Output: Jupyter notebooks with progressive techniques
|
||||
/project:infinite-web specs/python_datascience_progressive.md notebooks 15
|
||||
```
|
||||
|
||||
### 4. Machine Learning Models
|
||||
```bash
|
||||
# Spec: ML model implementations
|
||||
# URLs: TensorFlow tutorials, papers, Kaggle kernels
|
||||
# Output: Progressive ML implementations
|
||||
/project:infinite-web specs/ml_models_progressive.md models 10
|
||||
```
|
||||
|
||||
## Quality Assurance
|
||||
|
||||
### What Makes a Good Iteration?
|
||||
|
||||
**Web Integration:**
|
||||
- ✅ Specific URL documented in output
|
||||
- ✅ Technique from URL clearly identified
|
||||
- ✅ Learning demonstrably applied (not just mentioned)
|
||||
- ✅ Improvement over previous iteration explained
|
||||
|
||||
**Technical Quality:**
|
||||
- ✅ Follows specification format exactly
|
||||
- ✅ Code is clean, commented, functional
|
||||
- ✅ Demonstrates mastery of learned technique
|
||||
- ✅ Builds upon previous iterations appropriately
|
||||
|
||||
**Uniqueness:**
|
||||
- ✅ No duplicate URLs across iterations
|
||||
- ✅ Novel implementation (not copy-paste from web)
|
||||
- ✅ Genuine advancement over previous work
|
||||
- ✅ Creative synthesis of multiple learnings
|
||||
|
||||
### Common Pitfalls to Avoid
|
||||
|
||||
**Superficial Web Integration:**
|
||||
- ❌ URL cited but technique not applied
|
||||
- ❌ Copying example code without understanding
|
||||
- ❌ Mentioning learning without demonstrating it
|
||||
|
||||
**Poor Progression:**
|
||||
- ❌ Iterations don't build on each other
|
||||
- ❌ No measurable improvement
|
||||
- ❌ Duplicate techniques from different sources
|
||||
|
||||
**URL Management:**
|
||||
- ❌ Reusing same URL in multiple iterations
|
||||
- ❌ Low-quality or irrelevant sources
|
||||
- ❌ Ignoring URL strategy difficulty curve
|
||||
|
||||
## Advanced Techniques
|
||||
|
||||
### Custom Web Search Strategies
|
||||
|
||||
Define search templates in your URL strategy:
|
||||
|
||||
```json
|
||||
{
|
||||
"web_search_templates": [
|
||||
"{domain} {technique} tutorial site:observablehq.com",
|
||||
"{domain} {feature} best practices 2024",
|
||||
"advanced {domain} {area} technique",
|
||||
"{domain} performance optimization {context}"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Agents can fill templates dynamically based on needs.
|
||||
|
||||
### Multi-Domain Knowledge Fusion
|
||||
|
||||
Combine multiple URL strategies:
|
||||
|
||||
```bash
|
||||
# Fuse D3 + Design + Accessibility knowledge
|
||||
/project:infinite-web specs/accessible_dataviz.md output 20 specs/multi_domain_urls.json
|
||||
```
|
||||
|
||||
### Iteration Forking
|
||||
|
||||
Generate multiple variants per iteration:
|
||||
|
||||
```bash
|
||||
# Each iteration explores 3 different techniques from same URL
|
||||
/project:infinite-web specs/exploration_spec.md variants 30
|
||||
```
|
||||
|
||||
### Knowledge Checkpointing
|
||||
|
||||
Summarize learnings periodically:
|
||||
|
||||
```
|
||||
Iterations 1-10 → Generate summary.md with accumulated knowledge
|
||||
Iterations 11-20 → Build upon summary + new research
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### WebFetch Failures
|
||||
|
||||
**Problem:** URL fetch fails
|
||||
|
||||
**Solutions:**
|
||||
1. System falls back to WebSearch for topic
|
||||
2. Tries alternative URL from same category
|
||||
3. Logs failure and continues with fallback
|
||||
|
||||
### URL Exhaustion
|
||||
|
||||
**Problem:** All pre-defined URLs used
|
||||
|
||||
**Solutions:**
|
||||
1. Automatically switches to dynamic WebSearch mode
|
||||
2. Generates targeted queries based on:
|
||||
- Current sophistication level
|
||||
- Knowledge gaps
|
||||
- Novel areas to explore
|
||||
|
||||
### Context Limits in Infinite Mode
|
||||
|
||||
**Problem:** Approaching context window limits
|
||||
|
||||
**Solutions:**
|
||||
1. System monitors context usage continuously
|
||||
2. Completes current wave before limits
|
||||
3. Generates summary of progress
|
||||
4. Graceful conclusion with statistics
|
||||
|
||||
### Poor Web Learning Integration
|
||||
|
||||
**Problem:** Agents cite but don't apply learnings
|
||||
|
||||
**Solutions:**
|
||||
1. Strengthen integration directive in prompts
|
||||
2. Review output for genuine technique application
|
||||
2. Require code examples demonstrating learning
|
||||
4. Validate improvement over previous iteration
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Start Small, Scale Up
|
||||
```bash
|
||||
# Test with 1 iteration first
|
||||
/project:infinite-web specs/your_spec.md test 1
|
||||
|
||||
# Then try batch
|
||||
/project:infinite-web specs/your_spec.md test 5
|
||||
|
||||
# Finally go infinite
|
||||
/project:infinite-web specs/your_spec.md production infinite
|
||||
```
|
||||
|
||||
### 2. Curate Quality URLs
|
||||
- Choose authoritative sources
|
||||
- Verify URLs are accessible
|
||||
- Organize by genuine difficulty progression
|
||||
- Include diverse perspectives
|
||||
|
||||
### 3. Write Clear Specifications
|
||||
- Explicit output format requirements
|
||||
- Clear quality standards
|
||||
- Specific integration directives
|
||||
- Progressive enhancement dimensions
|
||||
|
||||
### 4. Monitor First Wave
|
||||
- Check first 3-5 outputs carefully
|
||||
- Verify web learning application
|
||||
- Adjust spec if needed
|
||||
- Refine URL strategy based on results
|
||||
|
||||
### 5. Document Learnings
|
||||
- Each iteration should document:
|
||||
- Web source URL
|
||||
- Specific technique learned
|
||||
- How it was applied
|
||||
- Improvement over previous iteration
|
||||
|
||||
## System Architecture Summary
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ /project:infinite-web Command │
|
||||
│ ├─ Phase 0: Initial Web Priming (3-5 foundational URLs)│
|
||||
│ ├─ Phase 1: Spec Analysis + Priming Knowledge │
|
||||
│ ├─ Phase 2: Directory Recon + URL Tracking │
|
||||
│ ├─ Phase 3: Web-Enhanced Iteration Strategy │
|
||||
│ ├─ Phase 4: Parallel Agent Coordination │
|
||||
│ │ ├─ Agent 1: URL A → Fetch → Learn → Generate │
|
||||
│ │ ├─ Agent 2: URL B → Fetch → Learn → Generate │
|
||||
│ │ └─ Agent N: URL N → Fetch → Learn → Generate │
|
||||
│ └─ Phase 5: Infinite Mode Waves (optional) │
|
||||
│ └─ Wave 1, 2, 3... until context limits │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Example Session
|
||||
|
||||
```bash
|
||||
# Terminal session
|
||||
$ claude
|
||||
|
||||
> /project:infinite-web specs/d3_visualization_progressive.md d3_viz 5 specs/d3_url_strategy.json
|
||||
|
||||
# System performs:
|
||||
# 1. Reads D3 spec
|
||||
# 2. Loads URL strategy
|
||||
# 3. Fetches 3 priming URLs:
|
||||
# - d3js.org/what-is-d3
|
||||
# - observablehq.com/@d3/learn-d3
|
||||
# - d3-graph-gallery.com
|
||||
# 4. Synthesizes foundational knowledge
|
||||
# 5. Launches 5 parallel agents:
|
||||
# - Agent 1: d3js.org/d3-selection → learns selections → generates d3_viz_1.html
|
||||
# - Agent 2: d3js.org/d3-scale → learns scales → generates d3_viz_2.html
|
||||
# - Agent 3: observablehq.com/@d3/bar-chart → learns bar charts → d3_viz_3.html
|
||||
# - Agent 4: observablehq.com/@d3/line-chart → learns line charts → d3_viz_4.html
|
||||
# - Agent 5: observablehq.com/@d3/scatterplot → learns scatter → d3_viz_5.html
|
||||
# 6. Each file documents its web source and learnings
|
||||
# 7. Summary of all 5 iterations and techniques learned
|
||||
|
||||
✓ Generated 5 D3 visualizations with progressive web learning
|
||||
✓ URLs used: 8 total (3 priming + 5 iteration)
|
||||
✓ Techniques applied: selections, scales, bar charts, line charts, scatter plots
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Try the D3 Example**: Run a small batch to see the system in action
|
||||
2. **Create Your Domain**: Define spec and URL strategy for your use case
|
||||
3. **Experiment with Modes**: Try single, batch, and infinite modes
|
||||
4. **Refine Strategy**: Adjust URL difficulty progression based on results
|
||||
5. **Scale Up**: Once validated, run larger batches or infinite mode
|
||||
|
||||
## Conclusion
|
||||
|
||||
The Web-Enhanced Infinite Agentic Loop transforms the original loop pattern into a **self-improving knowledge system**. Each iteration doesn't just generate output—it learns from the web, applies new techniques, and builds upon accumulated knowledge.
|
||||
|
||||
**Key Innovation:** Progressive web-based learning creates outputs that continuously improve in sophistication, quality, and technical excellence.
|
||||
|
||||
Start experimenting with D3 visualizations, then apply this pattern to any domain where progressive web-enhanced learning can create increasingly sophisticated outputs!
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,493 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>D3 Visualization 1: Interactive Technology Adoption Dashboard</title>
|
||||
<script src="https://d3js.org/d3.v7.min.js"></script>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
padding: 20px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
#visualization-container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
|
||||
padding: 40px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #2c3e50;
|
||||
margin-bottom: 10px;
|
||||
font-size: 2.5em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
text-align: center;
|
||||
color: #7f8c8d;
|
||||
margin-bottom: 30px;
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
#controls {
|
||||
margin-bottom: 30px;
|
||||
padding: 20px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.control-btn {
|
||||
padding: 12px 24px;
|
||||
border: 2px solid #667eea;
|
||||
background: white;
|
||||
color: #667eea;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 1em;
|
||||
font-weight: 600;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.control-btn:hover {
|
||||
background: #667eea;
|
||||
color: white;
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.control-btn.active {
|
||||
background: #667eea;
|
||||
color: white;
|
||||
}
|
||||
|
||||
#viz {
|
||||
margin: 40px 0;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.bar {
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.bar:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.bar-label {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
fill: #2c3e50;
|
||||
}
|
||||
|
||||
.value-label {
|
||||
font-size: 12px;
|
||||
fill: white;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.axis-label {
|
||||
font-size: 14px;
|
||||
fill: #7f8c8d;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.axis path,
|
||||
.axis line {
|
||||
stroke: #bdc3c7;
|
||||
}
|
||||
|
||||
.axis text {
|
||||
fill: #2c3e50;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
#insights {
|
||||
padding: 25px;
|
||||
background: #ecf0f1;
|
||||
border-radius: 8px;
|
||||
border-left: 5px solid #667eea;
|
||||
}
|
||||
|
||||
#insights h3 {
|
||||
color: #2c3e50;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.legend {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
margin-top: 15px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.legend-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.legend-color {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
#selected-info {
|
||||
margin-top: 15px;
|
||||
padding: 15px;
|
||||
background: white;
|
||||
border-radius: 6px;
|
||||
min-height: 60px;
|
||||
}
|
||||
|
||||
footer {
|
||||
margin-top: 40px;
|
||||
padding: 30px;
|
||||
background: #2c3e50;
|
||||
color: white;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
footer h3 {
|
||||
color: #3498db;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
footer ul {
|
||||
list-style-position: inside;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
footer li {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
footer strong {
|
||||
color: #3498db;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="visualization-container">
|
||||
<h1>Technology Adoption Dashboard</h1>
|
||||
<p class="subtitle">Interactive visualization demonstrating D3 selection patterns and data binding</p>
|
||||
|
||||
<div id="controls">
|
||||
<button class="control-btn active" data-sort="name">Sort by Name</button>
|
||||
<button class="control-btn" data-sort="adoption">Sort by Adoption</button>
|
||||
<button class="control-btn" data-sort="growth">Sort by Growth</button>
|
||||
<button class="control-btn" data-action="randomize">Randomize Data</button>
|
||||
<button class="control-btn" data-action="reset">Reset</button>
|
||||
</div>
|
||||
|
||||
<div id="viz"></div>
|
||||
|
||||
<div id="insights">
|
||||
<h3>Visualization Insights</h3>
|
||||
<p>Click on any bar to see detailed information. Hover for interactive effects.</p>
|
||||
<div class="legend">
|
||||
<div class="legend-item">
|
||||
<div class="legend-color" style="background: #3498db;"></div>
|
||||
<span>High Adoption (>70%)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color" style="background: #2ecc71;"></div>
|
||||
<span>Medium Adoption (40-70%)</span>
|
||||
</div>
|
||||
<div class="legend-item">
|
||||
<div class="legend-color" style="background: #f39c12;"></div>
|
||||
<span>Growing (<40%)</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="selected-info">
|
||||
<em style="color: #7f8c8d;">Select a technology to see details...</em>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Embedded realistic data - Technology adoption rates
|
||||
const originalData = [
|
||||
{ name: "React", adoption: 78, growth: 12, category: "Frontend", users: "12.5M" },
|
||||
{ name: "Vue.js", adoption: 52, growth: 18, category: "Frontend", users: "4.2M" },
|
||||
{ name: "Angular", adoption: 45, growth: -3, category: "Frontend", users: "3.8M" },
|
||||
{ name: "Svelte", adoption: 22, growth: 35, category: "Frontend", users: "850K" },
|
||||
{ name: "Node.js", adoption: 85, growth: 8, category: "Backend", users: "18.2M" },
|
||||
{ name: "Python", adoption: 82, growth: 15, category: "Backend", users: "16.7M" },
|
||||
{ name: "Rust", adoption: 18, growth: 42, category: "Backend", users: "2.1M" },
|
||||
{ name: "Go", adoption: 38, growth: 22, category: "Backend", users: "3.5M" },
|
||||
{ name: "TypeScript", adoption: 72, growth: 28, category: "Language", users: "10.8M" },
|
||||
{ name: "GraphQL", adoption: 35, growth: 25, category: "API", users: "2.9M" },
|
||||
{ name: "Docker", adoption: 88, growth: 10, category: "DevOps", users: "22.4M" },
|
||||
{ name: "Kubernetes", adoption: 58, growth: 30, category: "DevOps", users: "6.8M" },
|
||||
{ name: "PostgreSQL", adoption: 76, growth: 14, category: "Database", users: "14.3M" },
|
||||
{ name: "MongoDB", adoption: 65, growth: 8, category: "Database", users: "9.2M" },
|
||||
{ name: "Redis", adoption: 55, growth: 12, category: "Database", users: "6.5M" },
|
||||
{ name: "TailwindCSS", adoption: 48, growth: 45, category: "CSS", users: "4.5M" },
|
||||
{ name: "Jest", adoption: 62, growth: 5, category: "Testing", users: "7.8M" },
|
||||
{ name: "Playwright", adoption: 28, growth: 55, category: "Testing", users: "1.8M" },
|
||||
{ name: "Vite", adoption: 42, growth: 62, category: "Build Tool", users: "3.6M" },
|
||||
{ name: "Next.js", adoption: 68, growth: 38, category: "Framework", users: "8.9M" }
|
||||
];
|
||||
|
||||
// Clone data for manipulation
|
||||
let data = JSON.parse(JSON.stringify(originalData));
|
||||
|
||||
// Dimensions and margins
|
||||
const margin = { top: 20, right: 30, bottom: 60, left: 160 };
|
||||
const width = 1100 - margin.left - margin.right;
|
||||
const height = 800 - margin.top - margin.bottom;
|
||||
|
||||
// TECHNIQUE 1: select() - Select the viz container and append SVG
|
||||
// Using d3.select() to query a single element
|
||||
const svg = d3.select("#viz")
|
||||
.append("svg")
|
||||
.attr("width", width + margin.left + margin.right)
|
||||
.attr("height", height + margin.top + margin.bottom)
|
||||
.append("g")
|
||||
.attr("transform", `translate(${margin.left},${margin.top})`);
|
||||
|
||||
// Create scales
|
||||
const xScale = d3.scaleLinear()
|
||||
.domain([0, 100])
|
||||
.range([0, width]);
|
||||
|
||||
const yScale = d3.scaleBand()
|
||||
.domain(data.map(d => d.name))
|
||||
.range([0, height])
|
||||
.padding(0.2);
|
||||
|
||||
// Color scale based on adoption rate
|
||||
const colorScale = (adoption) => {
|
||||
if (adoption >= 70) return "#3498db";
|
||||
if (adoption >= 40) return "#2ecc71";
|
||||
return "#f39c12";
|
||||
};
|
||||
|
||||
// Add axes
|
||||
const xAxis = d3.axisBottom(xScale)
|
||||
.ticks(10)
|
||||
.tickFormat(d => d + "%");
|
||||
|
||||
const yAxis = d3.axisLeft(yScale);
|
||||
|
||||
svg.append("g")
|
||||
.attr("class", "axis x-axis")
|
||||
.attr("transform", `translate(0,${height})`)
|
||||
.call(xAxis)
|
||||
.append("text")
|
||||
.attr("class", "axis-label")
|
||||
.attr("x", width / 2)
|
||||
.attr("y", 40)
|
||||
.attr("fill", "#2c3e50")
|
||||
.text("Adoption Rate (%)");
|
||||
|
||||
svg.append("g")
|
||||
.attr("class", "axis y-axis")
|
||||
.call(yAxis);
|
||||
|
||||
// TECHNIQUE 2: selectAll() with data() and join() - The core data binding pattern
|
||||
// This demonstrates the enter/update/exit pattern with join()
|
||||
function updateChart(animationDuration = 750) {
|
||||
// Update yScale domain with new data order
|
||||
yScale.domain(data.map(d => d.name));
|
||||
|
||||
// TECHNIQUE 3: Data join with enter/update/exit using join()
|
||||
// selectAll() selects all bars (even if they don't exist yet)
|
||||
// data() binds our dataset
|
||||
// join() handles enter/update/exit automatically
|
||||
const bars = svg.selectAll(".bar")
|
||||
.data(data, d => d.name) // Key function ensures object constancy
|
||||
.join(
|
||||
// Enter: new elements
|
||||
enter => enter.append("rect")
|
||||
.attr("class", "bar")
|
||||
.attr("x", 0)
|
||||
.attr("y", d => yScale(d.name))
|
||||
.attr("width", 0)
|
||||
.attr("height", yScale.bandwidth())
|
||||
.attr("fill", d => colorScale(d.adoption))
|
||||
.attr("rx", 4),
|
||||
// Update: existing elements
|
||||
update => update,
|
||||
// Exit: removed elements
|
||||
exit => exit.transition()
|
||||
.duration(animationDuration)
|
||||
.attr("width", 0)
|
||||
.remove()
|
||||
);
|
||||
|
||||
// TECHNIQUE 4: Method chaining with attr() and style()
|
||||
// Demonstrates fluent API pattern for DOM manipulation
|
||||
bars.transition()
|
||||
.duration(animationDuration)
|
||||
.attr("y", d => yScale(d.name))
|
||||
.attr("width", d => xScale(d.adoption))
|
||||
.attr("height", yScale.bandwidth())
|
||||
.attr("fill", d => colorScale(d.adoption));
|
||||
|
||||
// TECHNIQUE 5: Event handling with on()
|
||||
// Adding interactive behavior to selections
|
||||
bars.on("click", function(event, d) {
|
||||
// 'this' refers to the DOM element
|
||||
// Remove previous selection highlighting
|
||||
d3.selectAll(".bar").attr("stroke", "none").attr("stroke-width", 0);
|
||||
|
||||
// Highlight selected bar using select() on 'this'
|
||||
d3.select(this)
|
||||
.attr("stroke", "#2c3e50")
|
||||
.attr("stroke-width", 3);
|
||||
|
||||
// Update info panel using select() and html()
|
||||
d3.select("#selected-info")
|
||||
.html(`
|
||||
<strong style="font-size: 1.2em; color: #2c3e50;">${d.name}</strong><br>
|
||||
<strong>Category:</strong> ${d.category} |
|
||||
<strong>Adoption:</strong> ${d.adoption}% |
|
||||
<strong>Growth:</strong> ${d.growth > 0 ? '+' : ''}${d.growth}% |
|
||||
<strong>Users:</strong> ${d.users}
|
||||
`);
|
||||
})
|
||||
.on("mouseenter", function(event, d) {
|
||||
// Demonstrate style() method for CSS manipulation
|
||||
d3.select(this)
|
||||
.style("filter", "brightness(1.1)")
|
||||
.style("transform", "translateX(5px)");
|
||||
})
|
||||
.on("mouseleave", function(event, d) {
|
||||
d3.select(this)
|
||||
.style("filter", "brightness(1)")
|
||||
.style("transform", "translateX(0)");
|
||||
});
|
||||
|
||||
// Update value labels using selectAll(), data(), and join()
|
||||
const labels = svg.selectAll(".value-label")
|
||||
.data(data, d => d.name)
|
||||
.join(
|
||||
enter => enter.append("text")
|
||||
.attr("class", "value-label")
|
||||
.attr("x", 0)
|
||||
.attr("y", d => yScale(d.name) + yScale.bandwidth() / 2)
|
||||
.attr("dy", "0.35em")
|
||||
.attr("dx", "8px")
|
||||
.text(d => d.adoption + "%"),
|
||||
update => update,
|
||||
exit => exit.remove()
|
||||
);
|
||||
|
||||
// Chain multiple attr() calls for positioning
|
||||
labels.transition()
|
||||
.duration(animationDuration)
|
||||
.attr("x", d => xScale(d.adoption))
|
||||
.attr("y", d => yScale(d.name) + yScale.bandwidth() / 2)
|
||||
.tween("text", function(d) {
|
||||
// Animate the number
|
||||
const i = d3.interpolate(+this.textContent.replace('%', '') || 0, d.adoption);
|
||||
return function(t) {
|
||||
this.textContent = Math.round(i(t)) + "%";
|
||||
};
|
||||
});
|
||||
|
||||
// Update Y axis with transition
|
||||
svg.select(".y-axis")
|
||||
.transition()
|
||||
.duration(animationDuration)
|
||||
.call(yAxis);
|
||||
}
|
||||
|
||||
// Initial chart render
|
||||
updateChart(1000);
|
||||
|
||||
// TECHNIQUE 6: selectAll() for control buttons with on() for events
|
||||
// Demonstrates selecting multiple elements and attaching event handlers
|
||||
d3.selectAll(".control-btn").on("click", function(event) {
|
||||
const btn = d3.select(this); // select() on 'this' DOM element
|
||||
const sortBy = btn.attr("data-sort"); // attr() to read attribute
|
||||
const action = btn.attr("data-action");
|
||||
|
||||
if (sortBy) {
|
||||
// Remove active class from all buttons, add to clicked
|
||||
d3.selectAll(".control-btn").classed("active", false);
|
||||
btn.classed("active", true);
|
||||
|
||||
// Sort data based on selection
|
||||
switch(sortBy) {
|
||||
case "name":
|
||||
data.sort((a, b) => a.name.localeCompare(b.name));
|
||||
break;
|
||||
case "adoption":
|
||||
data.sort((a, b) => b.adoption - a.adoption);
|
||||
break;
|
||||
case "growth":
|
||||
data.sort((a, b) => b.growth - a.growth);
|
||||
break;
|
||||
}
|
||||
updateChart();
|
||||
}
|
||||
|
||||
if (action === "randomize") {
|
||||
// Randomize adoption values
|
||||
data.forEach(d => {
|
||||
d.adoption = Math.floor(Math.random() * 80) + 20;
|
||||
d.growth = Math.floor(Math.random() * 60) - 10;
|
||||
});
|
||||
updateChart();
|
||||
}
|
||||
|
||||
if (action === "reset") {
|
||||
// Reset to original data
|
||||
data = JSON.parse(JSON.stringify(originalData));
|
||||
data.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
// Reset selection info using select() and html()
|
||||
d3.select("#selected-info")
|
||||
.html('<em style="color: #7f8c8d;">Select a technology to see details...</em>');
|
||||
|
||||
// Remove highlighting using selectAll() and attr()
|
||||
d3.selectAll(".bar").attr("stroke", "none").attr("stroke-width", 0);
|
||||
|
||||
updateChart();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<footer>
|
||||
<h3>Iteration 1 - Web Learning Applied</h3>
|
||||
<ul>
|
||||
<li><strong>Web Source:</strong> https://d3js.org/d3-selection</li>
|
||||
<li><strong>Topic:</strong> D3 Selections API - Core DOM manipulation patterns</li>
|
||||
<li><strong>Techniques Learned & Applied:</strong>
|
||||
<ul style="margin-left: 20px; margin-top: 8px;">
|
||||
<li><strong>select() & selectAll():</strong> Used throughout for querying single (#viz) and multiple (.bar, .control-btn) elements</li>
|
||||
<li><strong>data() & join():</strong> Implemented modern enter/update/exit pattern for dynamic bar chart updates with object constancy</li>
|
||||
<li><strong>attr(), style(), html(), text():</strong> Chained DOM manipulation methods for setting SVG attributes, CSS styles, and content</li>
|
||||
<li><strong>on() event handling:</strong> Interactive click, mouseenter, mouseleave events with 'this' context and d3.select(this) pattern</li>
|
||||
<li><strong>Method chaining:</strong> Fluent API usage throughout for concise, readable code</li>
|
||||
<li><strong>classed() method:</strong> Toggle CSS classes on button selections for active states</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>What This Demonstrates:</strong> An interactive horizontal bar chart showing technology adoption rates. Users can click bars to see details, sort by different criteria, randomize data, and reset. The visualization showcases all core D3 selection patterns: querying elements (select/selectAll), binding data (data/join), manipulating DOM (attr/style/html/text), and handling events (on). The enter/update/exit pattern via join() ensures smooth transitions when data changes, demonstrating D3's power for data-driven document transformation.</li>
|
||||
<li><strong>Data:</strong> 20 real-world technologies with adoption rates, growth percentages, categories, and user counts</li>
|
||||
<li><strong>Interactive Features:</strong> Click bars for details, hover for effects, sort controls, data randomization, full reset capability</li>
|
||||
</ul>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,749 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>D3 Visualization 2: Multi-Scale Temperature Analysis</title>
|
||||
<script src="https://d3js.org/d3.v7.min.js"></script>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
padding: 20px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
#visualization-container {
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 10px 40px rgba(0,0,0,0.3);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
h1 {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 30px;
|
||||
text-align: center;
|
||||
font-size: 2.2em;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
#controls {
|
||||
padding: 20px 40px;
|
||||
background: #f8f9fa;
|
||||
border-bottom: 2px solid #e9ecef;
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.control-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.control-group label {
|
||||
font-weight: 600;
|
||||
color: #495057;
|
||||
}
|
||||
|
||||
.control-group select {
|
||||
padding: 8px 12px;
|
||||
border: 2px solid #dee2e6;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
}
|
||||
|
||||
.control-group select:hover {
|
||||
border-color: #667eea;
|
||||
}
|
||||
|
||||
#viz {
|
||||
padding: 40px;
|
||||
min-height: 600px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 40px;
|
||||
}
|
||||
|
||||
.chart-section {
|
||||
background: #f8f9fa;
|
||||
padding: 30px;
|
||||
border-radius: 8px;
|
||||
border-left: 4px solid #667eea;
|
||||
}
|
||||
|
||||
.chart-title {
|
||||
font-size: 1.4em;
|
||||
color: #495057;
|
||||
margin-bottom: 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.chart-description {
|
||||
color: #6c757d;
|
||||
margin-bottom: 20px;
|
||||
font-size: 0.95em;
|
||||
}
|
||||
|
||||
#insights {
|
||||
padding: 30px 40px;
|
||||
background: #f8f9fa;
|
||||
border-top: 2px solid #e9ecef;
|
||||
}
|
||||
|
||||
#insights h2 {
|
||||
color: #495057;
|
||||
margin-bottom: 15px;
|
||||
font-size: 1.5em;
|
||||
}
|
||||
|
||||
.insight-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 20px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
border-left: 4px solid #667eea;
|
||||
}
|
||||
|
||||
.insight-card h3 {
|
||||
color: #667eea;
|
||||
margin-bottom: 10px;
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
.insight-card p {
|
||||
color: #6c757d;
|
||||
line-height: 1.6;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.scale-legend {
|
||||
margin-top: 15px;
|
||||
padding: 15px;
|
||||
background: white;
|
||||
border-radius: 6px;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.legend-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.legend-color {
|
||||
width: 30px;
|
||||
height: 20px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #dee2e6;
|
||||
}
|
||||
|
||||
footer {
|
||||
margin-top: 0;
|
||||
padding: 30px 40px;
|
||||
background: #343a40;
|
||||
color: white;
|
||||
}
|
||||
|
||||
footer h3 {
|
||||
color: #667eea;
|
||||
margin-bottom: 20px;
|
||||
font-size: 1.6em;
|
||||
}
|
||||
|
||||
footer ul {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
footer li {
|
||||
margin: 12px 0;
|
||||
padding-left: 20px;
|
||||
position: relative;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
footer li:before {
|
||||
content: "▸";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
color: #667eea;
|
||||
}
|
||||
|
||||
footer strong {
|
||||
color: #a5b4fc;
|
||||
}
|
||||
|
||||
.axis {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.axis path,
|
||||
.axis line {
|
||||
stroke: #495057;
|
||||
}
|
||||
|
||||
.axis text {
|
||||
fill: #495057;
|
||||
}
|
||||
|
||||
.bar {
|
||||
transition: opacity 0.3s;
|
||||
}
|
||||
|
||||
.bar:hover {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.data-point {
|
||||
transition: all 0.3s;
|
||||
}
|
||||
|
||||
.data-point:hover {
|
||||
r: 8;
|
||||
stroke-width: 3;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="visualization-container">
|
||||
<h1>Multi-Scale Temperature Analysis Dashboard</h1>
|
||||
|
||||
<div id="controls">
|
||||
<div class="control-group">
|
||||
<label for="scaleType">Time Scale Type:</label>
|
||||
<select id="scaleType">
|
||||
<option value="linear">Linear Scale</option>
|
||||
<option value="time" selected>Time Scale</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label for="colorScheme">Color Scheme:</label>
|
||||
<select id="colorScheme">
|
||||
<option value="sequential" selected>Sequential (Cool to Hot)</option>
|
||||
<option value="diverging">Diverging (Below/Above Average)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="viz">
|
||||
<div class="chart-section">
|
||||
<div class="chart-title">1. Time Scale + Sequential Color Scale</div>
|
||||
<div class="chart-description">
|
||||
Using <strong>scaleTime()</strong> for temporal data mapping and <strong>scaleSequential()</strong> for temperature color encoding
|
||||
</div>
|
||||
<svg id="timeChart"></svg>
|
||||
</div>
|
||||
|
||||
<div class="chart-section">
|
||||
<div class="chart-title">2. Band Scale + Linear Scale + Threshold Color Scale</div>
|
||||
<div class="chart-description">
|
||||
Using <strong>scaleBand()</strong> for categorical positioning, <strong>scaleLinear()</strong> for height, and <strong>scaleThreshold()</strong> for discrete color ranges
|
||||
</div>
|
||||
<svg id="barChart"></svg>
|
||||
</div>
|
||||
|
||||
<div class="chart-section">
|
||||
<div class="chart-title">3. Point Scale + Log Scale</div>
|
||||
<div class="chart-description">
|
||||
Using <strong>scalePoint()</strong> for precise categorical positioning and <strong>scaleLog()</strong> for exponential temperature variance display
|
||||
</div>
|
||||
<svg id="pointChart"></svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="insights">
|
||||
<h2>Scale Mappings Explained</h2>
|
||||
<div class="insight-grid">
|
||||
<div class="insight-card">
|
||||
<h3>Time Scale (scaleTime)</h3>
|
||||
<p>Maps JavaScript Date objects to pixel positions. Domain: [earliest date, latest date] → Range: [0, chartWidth]. Automatically handles date arithmetic and tick formatting.</p>
|
||||
</div>
|
||||
<div class="insight-card">
|
||||
<h3>Sequential Color Scale</h3>
|
||||
<p>Maps continuous temperature values to smooth color gradients. Domain: [minTemp, maxTemp] → Range: color interpolation. Perfect for showing intensity variations.</p>
|
||||
</div>
|
||||
<div class="insight-card">
|
||||
<h3>Band Scale (scaleBand)</h3>
|
||||
<p>Maps categorical city names to positions with automatic padding. Divides available space evenly with configurable inner/outer padding for bar charts.</p>
|
||||
</div>
|
||||
<div class="insight-card">
|
||||
<h3>Linear Scale (scaleLinear)</h3>
|
||||
<p>Standard numeric mapping. Domain: [0, maxTemp] → Range: [chartHeight, 0]. Inverted for SVG coordinate system where y=0 is at top.</p>
|
||||
</div>
|
||||
<div class="insight-card">
|
||||
<h3>Threshold Scale</h3>
|
||||
<p>Maps continuous input to discrete output using breakpoints. Temperature thresholds: [10°, 20°, 30°] create 4 color categories for "cold", "cool", "warm", "hot".</p>
|
||||
</div>
|
||||
<div class="insight-card">
|
||||
<h3>Log Scale (scaleLog)</h3>
|
||||
<p>Maps wide-range data using logarithmic transformation. Domain: [1, maxVariance] → Range: [0, height]. Compresses large values, expands small ones for better visibility.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Embedded realistic temperature data for multiple cities over time
|
||||
const rawData = [
|
||||
{ date: new Date(2024, 0, 1), city: 'New York', temp: 2, variance: 5 },
|
||||
{ date: new Date(2024, 1, 1), city: 'New York', temp: 4, variance: 8 },
|
||||
{ date: new Date(2024, 2, 1), city: 'New York', temp: 10, variance: 12 },
|
||||
{ date: new Date(2024, 3, 1), city: 'New York', temp: 16, variance: 15 },
|
||||
{ date: new Date(2024, 4, 1), city: 'New York', temp: 22, variance: 10 },
|
||||
{ date: new Date(2024, 5, 1), city: 'New York', temp: 27, variance: 8 },
|
||||
{ date: new Date(2024, 6, 1), city: 'New York', temp: 30, variance: 6 },
|
||||
{ date: new Date(2024, 7, 1), city: 'New York', temp: 28, variance: 7 },
|
||||
{ date: new Date(2024, 8, 1), city: 'New York', temp: 23, variance: 11 },
|
||||
{ date: new Date(2024, 9, 1), city: 'New York', temp: 16, variance: 14 },
|
||||
{ date: new Date(2024, 10, 1), city: 'New York', temp: 9, variance: 18 },
|
||||
{ date: new Date(2024, 11, 1), city: 'New York', temp: 3, variance: 9 },
|
||||
|
||||
{ date: new Date(2024, 0, 1), city: 'Los Angeles', temp: 15, variance: 3 },
|
||||
{ date: new Date(2024, 1, 1), city: 'Los Angeles', temp: 16, variance: 4 },
|
||||
{ date: new Date(2024, 2, 1), city: 'Los Angeles', temp: 17, variance: 5 },
|
||||
{ date: new Date(2024, 3, 1), city: 'Los Angeles', temp: 19, variance: 4 },
|
||||
{ date: new Date(2024, 4, 1), city: 'Los Angeles', temp: 21, variance: 3 },
|
||||
{ date: new Date(2024, 5, 1), city: 'Los Angeles', temp: 24, variance: 2 },
|
||||
{ date: new Date(2024, 6, 1), city: 'Los Angeles', temp: 26, variance: 2 },
|
||||
{ date: new Date(2024, 7, 1), city: 'Los Angeles', temp: 27, variance: 2 },
|
||||
{ date: new Date(2024, 8, 1), city: 'Los Angeles', temp: 25, variance: 3 },
|
||||
{ date: new Date(2024, 9, 1), city: 'Los Angeles', temp: 22, variance: 4 },
|
||||
{ date: new Date(2024, 10, 1), city: 'Los Angeles', temp: 18, variance: 5 },
|
||||
{ date: new Date(2024, 11, 1), city: 'Los Angeles', temp: 15, variance: 4 },
|
||||
|
||||
{ date: new Date(2024, 0, 1), city: 'Chicago', temp: -5, variance: 12 },
|
||||
{ date: new Date(2024, 1, 1), city: 'Chicago', temp: -2, variance: 15 },
|
||||
{ date: new Date(2024, 2, 1), city: 'Chicago', temp: 6, variance: 18 },
|
||||
{ date: new Date(2024, 3, 1), city: 'Chicago', temp: 13, variance: 16 },
|
||||
{ date: new Date(2024, 4, 1), city: 'Chicago', temp: 20, variance: 12 },
|
||||
{ date: new Date(2024, 5, 1), city: 'Chicago', temp: 26, variance: 9 },
|
||||
{ date: new Date(2024, 6, 1), city: 'Chicago', temp: 29, variance: 7 },
|
||||
{ date: new Date(2024, 7, 1), city: 'Chicago', temp: 27, variance: 8 },
|
||||
{ date: new Date(2024, 8, 1), city: 'Chicago', temp: 21, variance: 11 },
|
||||
{ date: new Date(2024, 9, 1), city: 'Chicago', temp: 14, variance: 15 },
|
||||
{ date: new Date(2024, 10, 1), city: 'Chicago', temp: 5, variance: 20 },
|
||||
{ date: new Date(2024, 11, 1), city: 'Chicago', temp: -3, variance: 14 },
|
||||
|
||||
{ date: new Date(2024, 0, 1), city: 'Miami', temp: 20, variance: 4 },
|
||||
{ date: new Date(2024, 1, 1), city: 'Miami', temp: 21, variance: 5 },
|
||||
{ date: new Date(2024, 2, 1), city: 'Miami', temp: 23, variance: 6 },
|
||||
{ date: new Date(2024, 3, 1), city: 'Miami', temp: 25, variance: 5 },
|
||||
{ date: new Date(2024, 4, 1), city: 'Miami', temp: 28, variance: 4 },
|
||||
{ date: new Date(2024, 5, 1), city: 'Miami', temp: 30, variance: 3 },
|
||||
{ date: new Date(2024, 6, 1), city: 'Miami', temp: 32, variance: 3 },
|
||||
{ date: new Date(2024, 7, 1), city: 'Miami', temp: 32, variance: 3 },
|
||||
{ date: new Date(2024, 8, 1), city: 'Miami', temp: 30, variance: 4 },
|
||||
{ date: new Date(2024, 9, 1), city: 'Miami', temp: 27, variance: 5 },
|
||||
{ date: new Date(2024, 10, 1), city: 'Miami', temp: 24, variance: 5 },
|
||||
{ date: new Date(2024, 11, 1), city: 'Miami', temp: 21, variance: 4 },
|
||||
|
||||
{ date: new Date(2024, 0, 1), city: 'Seattle', temp: 6, variance: 8 },
|
||||
{ date: new Date(2024, 1, 1), city: 'Seattle', temp: 8, variance: 9 },
|
||||
{ date: new Date(2024, 2, 1), city: 'Seattle', temp: 11, variance: 10 },
|
||||
{ date: new Date(2024, 3, 1), city: 'Seattle', temp: 13, variance: 11 },
|
||||
{ date: new Date(2024, 4, 1), city: 'Seattle', temp: 16, variance: 9 },
|
||||
{ date: new Date(2024, 5, 1), city: 'Seattle', temp: 19, variance: 7 },
|
||||
{ date: new Date(2024, 6, 1), city: 'Seattle', temp: 22, variance: 6 },
|
||||
{ date: new Date(2024, 7, 1), city: 'Seattle', temp: 23, variance: 6 },
|
||||
{ date: new Date(2024, 8, 1), city: 'Seattle', temp: 19, variance: 8 },
|
||||
{ date: new Date(2024, 9, 1), city: 'Seattle', temp: 14, variance: 10 },
|
||||
{ date: new Date(2024, 10, 1), city: 'Seattle', temp: 9, variance: 11 },
|
||||
{ date: new Date(2024, 11, 1), city: 'Seattle', temp: 6, variance: 9 }
|
||||
];
|
||||
|
||||
// Calculate average temperatures by city for bar chart
|
||||
const cityAverages = d3.rollup(
|
||||
rawData,
|
||||
v => ({
|
||||
avgTemp: d3.mean(v, d => d.temp),
|
||||
maxVariance: d3.max(v, d => d.variance)
|
||||
}),
|
||||
d => d.city
|
||||
);
|
||||
|
||||
const barData = Array.from(cityAverages, ([city, stats]) => ({
|
||||
city,
|
||||
avgTemp: stats.avgTemp,
|
||||
maxVariance: stats.maxVariance
|
||||
}));
|
||||
|
||||
// CHART 1: Time Scale + Sequential Color Scale
|
||||
function renderTimeChart() {
|
||||
const margin = { top: 20, right: 30, bottom: 50, left: 60 };
|
||||
const width = 1200 - margin.left - margin.right;
|
||||
const height = 400 - margin.top - margin.bottom;
|
||||
|
||||
// Clear existing chart
|
||||
d3.select('#timeChart').selectAll('*').remove();
|
||||
|
||||
const svg = d3.select('#timeChart')
|
||||
.attr('width', width + margin.left + margin.right)
|
||||
.attr('height', height + margin.top + margin.bottom)
|
||||
.append('g')
|
||||
.attr('transform', `translate(${margin.left},${margin.top})`);
|
||||
|
||||
// SCALE 1: Time Scale - maps dates to x positions
|
||||
const xScale = d3.scaleTime()
|
||||
.domain(d3.extent(rawData, d => d.date))
|
||||
.range([0, width]);
|
||||
|
||||
// SCALE 2: Linear Scale - maps temperature to y positions
|
||||
const yScale = d3.scaleLinear()
|
||||
.domain([
|
||||
d3.min(rawData, d => d.temp) - 5,
|
||||
d3.max(rawData, d => d.temp) + 5
|
||||
])
|
||||
.range([height, 0]);
|
||||
|
||||
// SCALE 3: Sequential Color Scale - maps temperature to colors
|
||||
const colorScale = d3.scaleSequential()
|
||||
.domain([d3.min(rawData, d => d.temp), d3.max(rawData, d => d.temp)])
|
||||
.interpolator(d3.interpolateRdYlBu)
|
||||
.unknown('#ccc');
|
||||
|
||||
// Group data by city for line rendering
|
||||
const cities = d3.group(rawData, d => d.city);
|
||||
|
||||
// Draw lines for each city
|
||||
const line = d3.line()
|
||||
.x(d => xScale(d.date))
|
||||
.y(d => yScale(d.temp))
|
||||
.curve(d3.curveMonotoneX);
|
||||
|
||||
cities.forEach((values, city) => {
|
||||
svg.append('path')
|
||||
.datum(values)
|
||||
.attr('fill', 'none')
|
||||
.attr('stroke', '#667eea')
|
||||
.attr('stroke-width', 2)
|
||||
.attr('opacity', 0.3)
|
||||
.attr('d', line);
|
||||
});
|
||||
|
||||
// Draw data points with color scale
|
||||
svg.selectAll('.data-point')
|
||||
.data(rawData)
|
||||
.join('circle')
|
||||
.attr('class', 'data-point')
|
||||
.attr('cx', d => xScale(d.date))
|
||||
.attr('cy', d => yScale(d.temp))
|
||||
.attr('r', 5)
|
||||
.attr('fill', d => colorScale(d.temp))
|
||||
.attr('stroke', 'white')
|
||||
.attr('stroke-width', 2)
|
||||
.append('title')
|
||||
.text(d => `${d.city}\n${d.date.toLocaleDateString()}\n${d.temp}°C`);
|
||||
|
||||
// Add X axis using time scale
|
||||
svg.append('g')
|
||||
.attr('class', 'axis')
|
||||
.attr('transform', `translate(0,${height})`)
|
||||
.call(d3.axisBottom(xScale).ticks(12))
|
||||
.selectAll('text')
|
||||
.attr('transform', 'rotate(-45)')
|
||||
.style('text-anchor', 'end');
|
||||
|
||||
// Add Y axis
|
||||
svg.append('g')
|
||||
.attr('class', 'axis')
|
||||
.call(d3.axisLeft(yScale))
|
||||
.append('text')
|
||||
.attr('transform', 'rotate(-90)')
|
||||
.attr('y', -45)
|
||||
.attr('x', -height / 2)
|
||||
.attr('fill', '#495057')
|
||||
.style('text-anchor', 'middle')
|
||||
.text('Temperature (°C)');
|
||||
|
||||
// Color legend
|
||||
const legendWidth = 300;
|
||||
const legendHeight = 20;
|
||||
const legendScale = d3.scaleLinear()
|
||||
.domain(colorScale.domain())
|
||||
.range([0, legendWidth]);
|
||||
|
||||
const legendGroup = svg.append('g')
|
||||
.attr('transform', `translate(${width - legendWidth - 10}, ${height + 40})`);
|
||||
|
||||
// Gradient for legend
|
||||
const defs = svg.append('defs');
|
||||
const gradient = defs.append('linearGradient')
|
||||
.attr('id', 'temp-gradient');
|
||||
|
||||
gradient.selectAll('stop')
|
||||
.data(d3.range(0, 1.01, 0.1))
|
||||
.join('stop')
|
||||
.attr('offset', d => `${d * 100}%`)
|
||||
.attr('stop-color', d => colorScale(
|
||||
colorScale.domain()[0] + d * (colorScale.domain()[1] - colorScale.domain()[0])
|
||||
));
|
||||
|
||||
legendGroup.append('rect')
|
||||
.attr('width', legendWidth)
|
||||
.attr('height', legendHeight)
|
||||
.style('fill', 'url(#temp-gradient)')
|
||||
.attr('stroke', '#495057');
|
||||
|
||||
legendGroup.append('g')
|
||||
.attr('transform', `translate(0, ${legendHeight})`)
|
||||
.call(d3.axisBottom(legendScale).ticks(5).tickFormat(d => `${d}°C`));
|
||||
}
|
||||
|
||||
// CHART 2: Band Scale + Linear Scale + Threshold Color Scale
|
||||
function renderBarChart() {
|
||||
const margin = { top: 20, right: 30, bottom: 60, left: 60 };
|
||||
const width = 1200 - margin.left - margin.right;
|
||||
const height = 350 - margin.top - margin.bottom;
|
||||
|
||||
d3.select('#barChart').selectAll('*').remove();
|
||||
|
||||
const svg = d3.select('#barChart')
|
||||
.attr('width', width + margin.left + margin.right)
|
||||
.attr('height', height + margin.top + margin.bottom)
|
||||
.append('g')
|
||||
.attr('transform', `translate(${margin.left},${margin.top})`);
|
||||
|
||||
// SCALE 4: Band Scale - maps cities to x positions with automatic spacing
|
||||
const xScale = d3.scaleBand()
|
||||
.domain(barData.map(d => d.city))
|
||||
.range([0, width])
|
||||
.padding(0.2); // Automatic padding between bars
|
||||
|
||||
// SCALE 5: Linear Scale - maps temperature to bar height
|
||||
const yScale = d3.scaleLinear()
|
||||
.domain([0, d3.max(barData, d => d.avgTemp) + 5])
|
||||
.range([height, 0]);
|
||||
|
||||
// SCALE 6: Threshold Scale - discrete color categories
|
||||
const colorScale = d3.scaleThreshold()
|
||||
.domain([10, 20, 30]) // Temperature breakpoints
|
||||
.range(['#3b82f6', '#10b981', '#f59e0b', '#ef4444']); // cold, cool, warm, hot
|
||||
|
||||
// Draw bars
|
||||
svg.selectAll('.bar')
|
||||
.data(barData)
|
||||
.join('rect')
|
||||
.attr('class', 'bar')
|
||||
.attr('x', d => xScale(d.city))
|
||||
.attr('y', d => yScale(d.avgTemp))
|
||||
.attr('width', xScale.bandwidth())
|
||||
.attr('height', d => height - yScale(d.avgTemp))
|
||||
.attr('fill', d => colorScale(d.avgTemp))
|
||||
.attr('stroke', '#495057')
|
||||
.attr('stroke-width', 2)
|
||||
.append('title')
|
||||
.text(d => `${d.city}: ${d.avgTemp.toFixed(1)}°C`);
|
||||
|
||||
// Add value labels on bars
|
||||
svg.selectAll('.bar-label')
|
||||
.data(barData)
|
||||
.join('text')
|
||||
.attr('class', 'bar-label')
|
||||
.attr('x', d => xScale(d.city) + xScale.bandwidth() / 2)
|
||||
.attr('y', d => yScale(d.avgTemp) - 5)
|
||||
.attr('text-anchor', 'middle')
|
||||
.attr('fill', '#495057')
|
||||
.attr('font-weight', 'bold')
|
||||
.attr('font-size', '14px')
|
||||
.text(d => `${d.avgTemp.toFixed(1)}°C`);
|
||||
|
||||
// Add axes
|
||||
svg.append('g')
|
||||
.attr('class', 'axis')
|
||||
.attr('transform', `translate(0,${height})`)
|
||||
.call(d3.axisBottom(xScale))
|
||||
.selectAll('text')
|
||||
.attr('transform', 'rotate(-15)')
|
||||
.style('text-anchor', 'end');
|
||||
|
||||
svg.append('g')
|
||||
.attr('class', 'axis')
|
||||
.call(d3.axisLeft(yScale))
|
||||
.append('text')
|
||||
.attr('transform', 'rotate(-90)')
|
||||
.attr('y', -45)
|
||||
.attr('x', -height / 2)
|
||||
.attr('fill', '#495057')
|
||||
.style('text-anchor', 'middle')
|
||||
.text('Average Temperature (°C)');
|
||||
|
||||
// Threshold legend
|
||||
const thresholds = [
|
||||
{ range: '< 10°C', color: '#3b82f6', label: 'Cold' },
|
||||
{ range: '10-20°C', color: '#10b981', label: 'Cool' },
|
||||
{ range: '20-30°C', color: '#f59e0b', label: 'Warm' },
|
||||
{ range: '> 30°C', color: '#ef4444', label: 'Hot' }
|
||||
];
|
||||
|
||||
const legend = svg.append('g')
|
||||
.attr('transform', `translate(${width - 150}, 20)`);
|
||||
|
||||
thresholds.forEach((t, i) => {
|
||||
const item = legend.append('g')
|
||||
.attr('transform', `translate(0, ${i * 25})`);
|
||||
|
||||
item.append('rect')
|
||||
.attr('width', 20)
|
||||
.attr('height', 20)
|
||||
.attr('fill', t.color)
|
||||
.attr('stroke', '#495057');
|
||||
|
||||
item.append('text')
|
||||
.attr('x', 28)
|
||||
.attr('y', 15)
|
||||
.attr('font-size', '12px')
|
||||
.attr('fill', '#495057')
|
||||
.text(`${t.label}: ${t.range}`);
|
||||
});
|
||||
}
|
||||
|
||||
// CHART 3: Point Scale + Log Scale
|
||||
function renderPointChart() {
|
||||
const margin = { top: 20, right: 30, bottom: 60, left: 80 };
|
||||
const width = 1200 - margin.left - margin.right;
|
||||
const height = 350 - margin.top - margin.bottom;
|
||||
|
||||
d3.select('#pointChart').selectAll('*').remove();
|
||||
|
||||
const svg = d3.select('#pointChart')
|
||||
.attr('width', width + margin.left + margin.right)
|
||||
.attr('height', height + margin.top + margin.bottom)
|
||||
.append('g')
|
||||
.attr('transform', `translate(${margin.left},${margin.top})`);
|
||||
|
||||
// SCALE 7: Point Scale - precise categorical positioning
|
||||
const xScale = d3.scalePoint()
|
||||
.domain(barData.map(d => d.city))
|
||||
.range([0, width])
|
||||
.padding(0.5);
|
||||
|
||||
// SCALE 8: Log Scale - logarithmic mapping for variance
|
||||
const yScale = d3.scaleLog()
|
||||
.domain([1, d3.max(barData, d => d.maxVariance) + 5])
|
||||
.range([height, 0])
|
||||
.clamp(true);
|
||||
|
||||
// Size scale for visual emphasis
|
||||
const sizeScale = d3.scaleLinear()
|
||||
.domain([0, d3.max(barData, d => d.avgTemp)])
|
||||
.range([5, 20]);
|
||||
|
||||
// Draw connecting line
|
||||
svg.append('path')
|
||||
.datum(barData)
|
||||
.attr('fill', 'none')
|
||||
.attr('stroke', '#667eea')
|
||||
.attr('stroke-width', 3)
|
||||
.attr('opacity', 0.3)
|
||||
.attr('d', d3.line()
|
||||
.x(d => xScale(d.city))
|
||||
.y(d => yScale(d.maxVariance))
|
||||
);
|
||||
|
||||
// Draw points
|
||||
svg.selectAll('.variance-point')
|
||||
.data(barData)
|
||||
.join('circle')
|
||||
.attr('class', 'variance-point data-point')
|
||||
.attr('cx', d => xScale(d.city))
|
||||
.attr('cy', d => yScale(d.maxVariance))
|
||||
.attr('r', d => sizeScale(d.avgTemp))
|
||||
.attr('fill', '#764ba2')
|
||||
.attr('stroke', '#fff')
|
||||
.attr('stroke-width', 2)
|
||||
.append('title')
|
||||
.text(d => `${d.city}\nVariance: ${d.maxVariance}°C\nAvg Temp: ${d.avgTemp.toFixed(1)}°C`);
|
||||
|
||||
// Add axes
|
||||
svg.append('g')
|
||||
.attr('class', 'axis')
|
||||
.attr('transform', `translate(0,${height})`)
|
||||
.call(d3.axisBottom(xScale))
|
||||
.selectAll('text')
|
||||
.attr('transform', 'rotate(-15)')
|
||||
.style('text-anchor', 'end');
|
||||
|
||||
svg.append('g')
|
||||
.attr('class', 'axis')
|
||||
.call(d3.axisLeft(yScale).ticks(5, '.0f'))
|
||||
.append('text')
|
||||
.attr('transform', 'rotate(-90)')
|
||||
.attr('y', -60)
|
||||
.attr('x', -height / 2)
|
||||
.attr('fill', '#495057')
|
||||
.style('text-anchor', 'middle')
|
||||
.text('Temperature Variance (°C) - Log Scale');
|
||||
|
||||
// Add note about log scale
|
||||
svg.append('text')
|
||||
.attr('x', width / 2)
|
||||
.attr('y', -5)
|
||||
.attr('text-anchor', 'middle')
|
||||
.attr('fill', '#6c757d')
|
||||
.attr('font-size', '13px')
|
||||
.attr('font-style', 'italic')
|
||||
.text('Point size represents average temperature | Log scale compresses high variance values');
|
||||
}
|
||||
|
||||
// Initial render
|
||||
renderTimeChart();
|
||||
renderBarChart();
|
||||
renderPointChart();
|
||||
|
||||
// Event listeners for controls
|
||||
document.getElementById('scaleType').addEventListener('change', renderTimeChart);
|
||||
document.getElementById('colorScheme').addEventListener('change', renderTimeChart);
|
||||
</script>
|
||||
|
||||
<footer>
|
||||
<h3>Iteration 2 - Web Learning Applied</h3>
|
||||
<ul>
|
||||
<li><strong>Web Source:</strong> https://d3js.org/d3-scale</li>
|
||||
<li><strong>Topic:</strong> D3 Scale Functions for Data-to-Visual Mapping</li>
|
||||
<li><strong>Techniques Learned:</strong>
|
||||
<ol style="margin-top: 10px; margin-left: 20px;">
|
||||
<li><strong>scaleTime()</strong> - Temporal data mapping with automatic date handling and tick formatting</li>
|
||||
<li><strong>scaleSequential()</strong> - Continuous color encoding with smooth interpolation (RdYlBu color scheme)</li>
|
||||
<li><strong>scaleBand()</strong> - Categorical positioning with automatic padding for bar charts</li>
|
||||
<li><strong>scaleLinear()</strong> - Standard numeric domain-to-range mapping with inverted y-axis</li>
|
||||
<li><strong>scaleThreshold()</strong> - Discrete binning with custom breakpoints (10°, 20°, 30°) for color categories</li>
|
||||
<li><strong>scalePoint()</strong> - Precise categorical positioning without bandwidth (point charts)</li>
|
||||
<li><strong>scaleLog()</strong> - Logarithmic transformation for wide-range variance data compression</li>
|
||||
</ol>
|
||||
</li>
|
||||
<li><strong>What This Demonstrates:</strong> Scales are the foundation of D3 visualizations - they map abstract data domains (temperatures from -5°C to 32°C, dates from Jan-Dec, city names) to visual ranges (pixel positions, colors, sizes). Each scale type solves specific mapping challenges: time scales handle temporal data, band scales divide categorical space evenly, threshold scales create discrete bins, and log scales compress exponential ranges.</li>
|
||||
<li><strong>Improvement over Iteration 1:</strong> While Iteration 1 focused on DOM selection and manipulation (the "how to change elements" foundation), Iteration 2 demonstrates the "how to map data" layer. We now transform raw temperature data through 8 different scale types to create meaningful visual encodings. The progression shows D3's architecture: selections manipulate the DOM, scales transform the data before it reaches the DOM.</li>
|
||||
<li><strong>Scale Mapping Examples:</strong>
|
||||
<ul style="margin-top: 8px; margin-left: 20px; list-style: circle;">
|
||||
<li>Time: <code>new Date(2024, 6, 1)</code> → 600px (middle of chart)</li>
|
||||
<li>Sequential: <code>30°C</code> → <code>#d73027</code> (red/hot)</li>
|
||||
<li>Band: <code>"Miami"</code> → x position with automatic 20% padding</li>
|
||||
<li>Threshold: <code>25°C</code> → <code>#f59e0b</code> (warm category)</li>
|
||||
<li>Log: <code>variance=20</code> → compressed visual height vs linear display</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,563 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>D3 Visualization 3: Global Coffee Production Analysis</title>
|
||||
<script src="https://d3js.org/d3.v7.min.js"></script>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
padding: 20px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
#visualization-container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
h1 {
|
||||
background: linear-gradient(135deg, #4a5568 0%, #2d3748 100%);
|
||||
color: white;
|
||||
padding: 30px;
|
||||
text-align: center;
|
||||
font-size: 2em;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
#controls {
|
||||
padding: 20px 30px;
|
||||
background: #f7fafc;
|
||||
border-bottom: 2px solid #e2e8f0;
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.control-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.control-group label {
|
||||
font-weight: 600;
|
||||
color: #2d3748;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 10px 20px;
|
||||
background: #667eea;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: #5a67d8;
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
button.active {
|
||||
background: #48bb78;
|
||||
}
|
||||
|
||||
#viz {
|
||||
padding: 40px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
#insights {
|
||||
padding: 30px;
|
||||
background: #edf2f7;
|
||||
border-top: 3px solid #cbd5e0;
|
||||
}
|
||||
|
||||
#insights h3 {
|
||||
color: #2d3748;
|
||||
margin-bottom: 15px;
|
||||
font-size: 1.3em;
|
||||
}
|
||||
|
||||
.insight-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.insight-card {
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.insight-card h4 {
|
||||
color: #667eea;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.insight-card p {
|
||||
color: #4a5568;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.tooltip {
|
||||
position: absolute;
|
||||
background: rgba(0, 0, 0, 0.9);
|
||||
color: white;
|
||||
padding: 12px 16px;
|
||||
border-radius: 6px;
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s;
|
||||
font-size: 14px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
|
||||
}
|
||||
|
||||
.tooltip.visible {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.bar {
|
||||
transition: all 0.3s ease;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.bar:hover {
|
||||
opacity: 0.8;
|
||||
filter: brightness(1.1);
|
||||
}
|
||||
|
||||
.axis text {
|
||||
font-size: 12px;
|
||||
color: #4a5568;
|
||||
}
|
||||
|
||||
.axis path,
|
||||
.axis line {
|
||||
stroke: #cbd5e0;
|
||||
}
|
||||
|
||||
.axis-label {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
fill: #2d3748;
|
||||
}
|
||||
|
||||
footer {
|
||||
margin-top: 0;
|
||||
padding: 30px;
|
||||
background: #2d3748;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
footer h3 {
|
||||
color: #a0aec0;
|
||||
margin-bottom: 15px;
|
||||
border-bottom: 2px solid #4a5568;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
footer ul {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
footer li {
|
||||
margin-bottom: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
footer strong {
|
||||
color: #90cdf4;
|
||||
}
|
||||
|
||||
footer a {
|
||||
color: #90cdf4;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
footer a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="visualization-container">
|
||||
<h1>Global Coffee Production by Country (2024)</h1>
|
||||
|
||||
<div id="controls">
|
||||
<div class="control-group">
|
||||
<label>Sort by:</label>
|
||||
<button id="sortDefault" class="active">Default</button>
|
||||
<button id="sortAsc">Production ↑</button>
|
||||
<button id="sortDesc">Production ↓</button>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<button id="toggleColors">Toggle Color Theme</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="viz">
|
||||
<!-- D3 bar chart renders here -->
|
||||
</div>
|
||||
|
||||
<div id="insights">
|
||||
<h3>Key Insights from Coffee Production Data</h3>
|
||||
<div class="insight-grid">
|
||||
<div class="insight-card">
|
||||
<h4>🏆 Top Producer</h4>
|
||||
<p id="topProducer">Loading...</p>
|
||||
</div>
|
||||
<div class="insight-card">
|
||||
<h4>📊 Total Production</h4>
|
||||
<p id="totalProduction">Loading...</p>
|
||||
</div>
|
||||
<div class="insight-card">
|
||||
<h4>📈 Average Production</h4>
|
||||
<p id="avgProduction">Loading...</p>
|
||||
</div>
|
||||
<div class="insight-card">
|
||||
<h4>🌍 Market Concentration</h4>
|
||||
<p id="marketShare">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tooltip" id="tooltip"></div>
|
||||
|
||||
<script>
|
||||
// ============================================
|
||||
// DATA: Global Coffee Production (Million 60kg bags)
|
||||
// ============================================
|
||||
const coffeeData = [
|
||||
{ country: "Brazil", production: 69.0, region: "South America" },
|
||||
{ country: "Vietnam", production: 29.0, region: "Asia" },
|
||||
{ country: "Colombia", production: 14.5, region: "South America" },
|
||||
{ country: "Indonesia", production: 11.5, region: "Asia" },
|
||||
{ country: "Ethiopia", production: 8.2, region: "Africa" },
|
||||
{ country: "Honduras", production: 7.8, region: "Central America" },
|
||||
{ country: "India", production: 5.8, region: "Asia" },
|
||||
{ country: "Uganda", production: 5.5, region: "Africa" },
|
||||
{ country: "Peru", production: 5.2, region: "South America" },
|
||||
{ country: "Guatemala", production: 4.0, region: "Central America" },
|
||||
{ country: "Mexico", production: 3.8, region: "North America" },
|
||||
{ country: "Nicaragua", production: 3.2, region: "Central America" },
|
||||
{ country: "Côte d'Ivoire", production: 2.1, region: "Africa" },
|
||||
{ country: "Costa Rica", production: 1.5, region: "Central America" },
|
||||
{ country: "Tanzania", production: 1.3, region: "Africa" },
|
||||
{ country: "El Salvador", production: 0.7, region: "Central America" }
|
||||
];
|
||||
|
||||
// ============================================
|
||||
// MARGIN CONVENTION (from Observable tutorial)
|
||||
// ============================================
|
||||
const margin = { top: 20, right: 30, bottom: 70, left: 80 };
|
||||
const width = 1000;
|
||||
const height = 500;
|
||||
const innerWidth = width - margin.left - margin.right;
|
||||
const innerHeight = height - margin.top - margin.bottom;
|
||||
|
||||
// ============================================
|
||||
// COLOR SCHEMES (toggleable)
|
||||
// ============================================
|
||||
const colorSchemes = {
|
||||
gradient: d3.interpolateRgbBasis(["#f093fb", "#4facfe"]),
|
||||
earth: d3.interpolateRgbBasis(["#fa709a", "#fee140"]),
|
||||
ocean: d3.interpolateRgbBasis(["#667eea", "#764ba2"])
|
||||
};
|
||||
let currentScheme = "gradient";
|
||||
|
||||
// ============================================
|
||||
// CREATE SVG WITH VIEWBOX (responsive design)
|
||||
// ============================================
|
||||
const svg = d3.select("#viz")
|
||||
.append("svg")
|
||||
.attr("width", width)
|
||||
.attr("height", height)
|
||||
.attr("viewBox", [0, 0, width, height])
|
||||
.attr("style", "max-width: 100%; height: auto;");
|
||||
|
||||
// Main chart group with margin transform
|
||||
const chart = svg.append("g")
|
||||
.attr("transform", `translate(${margin.left},${margin.top})`);
|
||||
|
||||
// ============================================
|
||||
// SCALES (Synthesis of Iteration 2 learnings)
|
||||
// ============================================
|
||||
// X Scale: Band scale for categorical data (countries)
|
||||
const xScale = d3.scaleBand()
|
||||
.domain(coffeeData.map(d => d.country))
|
||||
.range([0, innerWidth])
|
||||
.padding(0.2);
|
||||
|
||||
// Y Scale: Linear scale for production values
|
||||
const yScale = d3.scaleLinear()
|
||||
.domain([0, d3.max(coffeeData, d => d.production)])
|
||||
.range([innerHeight, 0])
|
||||
.nice();
|
||||
|
||||
// Color Scale: For visual encoding based on production value
|
||||
const colorScale = d3.scaleSequential()
|
||||
.domain([0, d3.max(coffeeData, d => d.production)])
|
||||
.interpolator(colorSchemes[currentScheme]);
|
||||
|
||||
// ============================================
|
||||
// AXES (from Observable bar chart pattern)
|
||||
// ============================================
|
||||
const xAxis = d3.axisBottom(xScale)
|
||||
.tickSizeOuter(0);
|
||||
|
||||
const yAxis = d3.axisLeft(yScale)
|
||||
.ticks(height / 40)
|
||||
.tickFormat(d => d + "M");
|
||||
|
||||
// Append X Axis
|
||||
const xAxisGroup = chart.append("g")
|
||||
.attr("class", "axis x-axis")
|
||||
.attr("transform", `translate(0,${innerHeight})`)
|
||||
.call(xAxis)
|
||||
.selectAll("text")
|
||||
.attr("transform", "rotate(-45)")
|
||||
.style("text-anchor", "end");
|
||||
|
||||
// Append Y Axis
|
||||
chart.append("g")
|
||||
.attr("class", "axis y-axis")
|
||||
.call(yAxis);
|
||||
|
||||
// Axis Labels
|
||||
svg.append("text")
|
||||
.attr("class", "axis-label")
|
||||
.attr("x", width / 2)
|
||||
.attr("y", height - 10)
|
||||
.attr("text-anchor", "middle")
|
||||
.text("Country");
|
||||
|
||||
svg.append("text")
|
||||
.attr("class", "axis-label")
|
||||
.attr("transform", "rotate(-90)")
|
||||
.attr("x", -height / 2)
|
||||
.attr("y", 20)
|
||||
.attr("text-anchor", "middle")
|
||||
.text("Production (Million 60kg bags)");
|
||||
|
||||
// ============================================
|
||||
// TOOLTIP (for interactivity)
|
||||
// ============================================
|
||||
const tooltip = d3.select("#tooltip");
|
||||
|
||||
// ============================================
|
||||
// BARS (Synthesis of Iterations 1, 2, & 3)
|
||||
// Uses selections (Iteration 1), scales (Iteration 2),
|
||||
// and bar chart patterns (Iteration 3)
|
||||
// ============================================
|
||||
function renderBars(data) {
|
||||
// DATA JOIN: bind data to rect elements
|
||||
const bars = chart.selectAll(".bar")
|
||||
.data(data, d => d.country);
|
||||
|
||||
// EXIT: remove bars that no longer have data
|
||||
bars.exit()
|
||||
.transition()
|
||||
.duration(750)
|
||||
.attr("y", innerHeight)
|
||||
.attr("height", 0)
|
||||
.remove();
|
||||
|
||||
// ENTER + UPDATE: create new bars and update existing
|
||||
bars.enter()
|
||||
.append("rect")
|
||||
.attr("class", "bar")
|
||||
.attr("x", d => xScale(d.country))
|
||||
.attr("y", innerHeight)
|
||||
.attr("width", xScale.bandwidth())
|
||||
.attr("height", 0)
|
||||
.attr("fill", d => colorScale(d.production))
|
||||
.merge(bars)
|
||||
.on("mouseenter", handleMouseEnter)
|
||||
.on("mousemove", handleMouseMove)
|
||||
.on("mouseleave", handleMouseLeave)
|
||||
.transition()
|
||||
.duration(750)
|
||||
.attr("x", d => xScale(d.country))
|
||||
.attr("y", d => yScale(d.production))
|
||||
.attr("width", xScale.bandwidth())
|
||||
.attr("height", d => innerHeight - yScale(d.production))
|
||||
.attr("fill", d => colorScale(d.production));
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// INTERACTIVITY: Tooltip handlers
|
||||
// ============================================
|
||||
function handleMouseEnter(event, d) {
|
||||
d3.select(this)
|
||||
.transition()
|
||||
.duration(200)
|
||||
.attr("opacity", 0.7);
|
||||
|
||||
tooltip
|
||||
.html(`
|
||||
<strong>${d.country}</strong><br/>
|
||||
Production: ${d.production}M bags<br/>
|
||||
Region: ${d.region}
|
||||
`)
|
||||
.classed("visible", true);
|
||||
}
|
||||
|
||||
function handleMouseMove(event) {
|
||||
tooltip
|
||||
.style("left", (event.pageX + 15) + "px")
|
||||
.style("top", (event.pageY - 28) + "px");
|
||||
}
|
||||
|
||||
function handleMouseLeave(event, d) {
|
||||
d3.select(this)
|
||||
.transition()
|
||||
.duration(200)
|
||||
.attr("opacity", 1);
|
||||
|
||||
tooltip.classed("visible", false);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// SORTING CONTROLS
|
||||
// ============================================
|
||||
let currentData = [...coffeeData];
|
||||
|
||||
document.getElementById("sortDefault").addEventListener("click", function() {
|
||||
currentData = [...coffeeData];
|
||||
updateChart();
|
||||
updateActiveButton(this);
|
||||
});
|
||||
|
||||
document.getElementById("sortAsc").addEventListener("click", function() {
|
||||
currentData = [...coffeeData].sort((a, b) => a.production - b.production);
|
||||
updateChart();
|
||||
updateActiveButton(this);
|
||||
});
|
||||
|
||||
document.getElementById("sortDesc").addEventListener("click", function() {
|
||||
currentData = [...coffeeData].sort((a, b) => b.production - a.production);
|
||||
updateChart();
|
||||
updateActiveButton(this);
|
||||
});
|
||||
|
||||
function updateActiveButton(button) {
|
||||
document.querySelectorAll("#controls button").forEach(btn => {
|
||||
btn.classList.remove("active");
|
||||
});
|
||||
button.classList.add("active");
|
||||
}
|
||||
|
||||
function updateChart() {
|
||||
// Update X scale domain with new order
|
||||
xScale.domain(currentData.map(d => d.country));
|
||||
|
||||
// Update X axis
|
||||
chart.select(".x-axis")
|
||||
.transition()
|
||||
.duration(750)
|
||||
.call(xAxis)
|
||||
.selectAll("text")
|
||||
.attr("transform", "rotate(-45)")
|
||||
.style("text-anchor", "end");
|
||||
|
||||
// Re-render bars
|
||||
renderBars(currentData);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// COLOR THEME TOGGLE
|
||||
// ============================================
|
||||
const colorSchemeKeys = Object.keys(colorSchemes);
|
||||
let colorSchemeIndex = 0;
|
||||
|
||||
document.getElementById("toggleColors").addEventListener("click", function() {
|
||||
colorSchemeIndex = (colorSchemeIndex + 1) % colorSchemeKeys.length;
|
||||
currentScheme = colorSchemeKeys[colorSchemeIndex];
|
||||
|
||||
colorScale.interpolator(colorSchemes[currentScheme]);
|
||||
|
||||
chart.selectAll(".bar")
|
||||
.transition()
|
||||
.duration(500)
|
||||
.attr("fill", d => colorScale(d.production));
|
||||
});
|
||||
|
||||
// ============================================
|
||||
// INSIGHTS CALCULATION
|
||||
// ============================================
|
||||
function calculateInsights() {
|
||||
const total = d3.sum(coffeeData, d => d.production);
|
||||
const avg = d3.mean(coffeeData, d => d.production);
|
||||
const topProducer = coffeeData[0];
|
||||
const topThreeTotal = d3.sum(coffeeData.slice(0, 3), d => d.production);
|
||||
const marketShare = (topThreeTotal / total * 100).toFixed(1);
|
||||
|
||||
document.getElementById("topProducer").textContent =
|
||||
`${topProducer.country} leads with ${topProducer.production}M bags`;
|
||||
|
||||
document.getElementById("totalProduction").textContent =
|
||||
`${total.toFixed(1)}M bags globally`;
|
||||
|
||||
document.getElementById("avgProduction").textContent =
|
||||
`${avg.toFixed(1)}M bags per country`;
|
||||
|
||||
document.getElementById("marketShare").textContent =
|
||||
`Top 3 countries control ${marketShare}% of global production`;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// INITIALIZE
|
||||
// ============================================
|
||||
renderBars(currentData);
|
||||
calculateInsights();
|
||||
</script>
|
||||
|
||||
<footer>
|
||||
<h3>Iteration 3 - Web Learning Applied: Complete Bar Chart Visualization</h3>
|
||||
<ul>
|
||||
<li><strong>Web Source:</strong> <a href="https://observablehq.com/@d3/bar-chart" target="_blank">https://observablehq.com/@d3/bar-chart</a></li>
|
||||
<li><strong>Topic:</strong> D3 Bar Charts - Creating complete data visualizations with axes, scales, and interactivity</li>
|
||||
<li><strong>Techniques Learned:</strong>
|
||||
<ol style="margin-left: 20px; margin-top: 8px;">
|
||||
<li><strong>Margin Convention:</strong> Proper SVG layout using margin object to create space for axes and labels</li>
|
||||
<li><strong>Band Scales:</strong> Using scaleBand() for categorical data positioning with automatic spacing</li>
|
||||
<li><strong>Axis Creation:</strong> Creating and positioning axes with axisBottom() and axisLeft(), removing outer ticks for cleaner appearance</li>
|
||||
</ol>
|
||||
</li>
|
||||
<li><strong>What This Demonstrates:</strong> A complete, interactive bar chart showing global coffee production by country. Features dynamic sorting (default, ascending, descending), color theme toggling, smooth transitions, hover tooltips, and automated insights calculation.</li>
|
||||
<li><strong>Knowledge Synthesis:</strong>
|
||||
<ul style="margin-left: 20px; margin-top: 8px;">
|
||||
<li><strong>From Iteration 1 (Selections):</strong> Used data joins with enter/exit/update pattern, event handlers for interactivity, and dynamic DOM manipulation</li>
|
||||
<li><strong>From Iteration 2 (Scales):</strong> Applied scaleBand for X-axis categorical positioning, scaleLinear for Y-axis numerical mapping, and scaleSequential for color encoding</li>
|
||||
<li><strong>From Iteration 3 (Bar Charts):</strong> Implemented margin convention, responsive SVG with viewBox, proper axis creation and positioning, and bar height calculation using scale inversion</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><strong>Improvement over Previous:</strong> This is a complete, production-ready visualization combining all learned concepts. Unlike isolated examples of selections (Iteration 1) or scales (Iteration 2), this demonstrates a fully functional chart with professional styling, multiple interaction patterns, data-driven insights, and responsive design. The bar chart brings together DOM manipulation, data transformation, visual encoding, and user interactivity into a cohesive whole.</li>
|
||||
</ul>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,270 @@
|
|||
{
|
||||
"priming_urls": [
|
||||
{
|
||||
"url": "https://d3js.org/what-is-d3",
|
||||
"topic": "D3 Fundamentals",
|
||||
"description": "Core concepts and philosophy of D3"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/learn-d3",
|
||||
"topic": "D3 Tutorial",
|
||||
"description": "Comprehensive introduction to D3"
|
||||
},
|
||||
{
|
||||
"url": "https://d3-graph-gallery.com/",
|
||||
"topic": "D3 Pattern Library",
|
||||
"description": "Gallery of common D3 visualizations"
|
||||
}
|
||||
],
|
||||
|
||||
"foundation_urls": [
|
||||
{
|
||||
"iteration_range": [1, 5],
|
||||
"urls": [
|
||||
{
|
||||
"url": "https://d3js.org/d3-selection",
|
||||
"topic": "Selections",
|
||||
"description": "Core selection API for DOM manipulation"
|
||||
},
|
||||
{
|
||||
"url": "https://d3js.org/d3-scale",
|
||||
"topic": "Scales",
|
||||
"description": "Mapping data to visual dimensions"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/bar-chart",
|
||||
"topic": "Bar Charts",
|
||||
"description": "Creating basic bar charts"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/line-chart",
|
||||
"topic": "Line Charts",
|
||||
"description": "Time series and line visualizations"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/scatterplot",
|
||||
"topic": "Scatter Plots",
|
||||
"description": "Plotting points in 2D space"
|
||||
},
|
||||
{
|
||||
"url": "https://d3js.org/d3-axis",
|
||||
"topic": "Axes",
|
||||
"description": "Creating and customizing axes"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/margin-convention",
|
||||
"topic": "Margin Convention",
|
||||
"description": "Standard layout pattern for charts"
|
||||
},
|
||||
{
|
||||
"url": "https://d3js.org/d3-array",
|
||||
"topic": "Data Arrays",
|
||||
"description": "Data transformation and statistics"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"intermediate_urls": [
|
||||
{
|
||||
"iteration_range": [6, 12],
|
||||
"urls": [
|
||||
{
|
||||
"url": "https://d3js.org/d3-transition",
|
||||
"topic": "Transitions",
|
||||
"description": "Smooth animated transitions"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/d3-hierarchy",
|
||||
"topic": "Hierarchies",
|
||||
"description": "Tree and hierarchical data layouts"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/force-directed-graph",
|
||||
"topic": "Force Layouts",
|
||||
"description": "Physics-based network graphs"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/color-schemes",
|
||||
"topic": "Color Scales",
|
||||
"description": "Color theory and palettes"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/zoom",
|
||||
"topic": "Zoom & Pan",
|
||||
"description": "Interactive zoom and pan behaviors"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/brush",
|
||||
"topic": "Brushing",
|
||||
"description": "Interactive selection with brush"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/treemap",
|
||||
"topic": "Treemaps",
|
||||
"description": "Hierarchical space-filling visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/sunburst",
|
||||
"topic": "Sunburst",
|
||||
"description": "Radial hierarchical visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/chord-diagram",
|
||||
"topic": "Chord Diagrams",
|
||||
"description": "Circular relationship visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/sankey",
|
||||
"topic": "Sankey Diagrams",
|
||||
"description": "Flow and network visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/focus-context",
|
||||
"topic": "Focus + Context",
|
||||
"description": "Linked overview and detail views"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/streamgraph",
|
||||
"topic": "Streamgraph",
|
||||
"description": "Stacked area charts with smooth curves"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
"advanced_urls": [
|
||||
{
|
||||
"iteration_range": [13, 20],
|
||||
"urls": [
|
||||
{
|
||||
"url": "https://d3js.org/d3-geo",
|
||||
"topic": "Geographic Projections",
|
||||
"description": "Map projections and transformations"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/world-map",
|
||||
"topic": "Choropleth Maps",
|
||||
"description": "Geographic data visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/versor-dragging",
|
||||
"topic": "Globe Rotation",
|
||||
"description": "Interactive 3D globe projection"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/contours",
|
||||
"topic": "Contour Plots",
|
||||
"description": "Density and elevation visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/voronoi",
|
||||
"topic": "Voronoi Diagrams",
|
||||
"description": "Spatial partitioning visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/hierarchical-edge-bundling",
|
||||
"topic": "Edge Bundling",
|
||||
"description": "Advanced network visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/parallel-coordinates",
|
||||
"topic": "Parallel Coordinates",
|
||||
"description": "Multi-dimensional data visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/calendar",
|
||||
"topic": "Calendar View",
|
||||
"description": "Time-based heatmap visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/horizon-chart",
|
||||
"topic": "Horizon Charts",
|
||||
"description": "Compact time series visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/collision-detection",
|
||||
"topic": "Force Simulation",
|
||||
"description": "Advanced physics-based layouts"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/multi-line-chart",
|
||||
"topic": "Multi-Series Charts",
|
||||
"description": "Complex time series with interactions"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/zoomable-sunburst",
|
||||
"topic": "Zoomable Hierarchies",
|
||||
"description": "Interactive hierarchical exploration"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
"expert_urls": [
|
||||
{
|
||||
"iteration_range": [21, 999],
|
||||
"urls": [
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/canvas-scatterplot",
|
||||
"topic": "Canvas Rendering",
|
||||
"description": "High-performance canvas visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/webgl-scatterplot",
|
||||
"topic": "WebGL Integration",
|
||||
"description": "GPU-accelerated visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/seamless-zoomable-map-tiles",
|
||||
"topic": "Map Tiles",
|
||||
"description": "Advanced geographic visualization"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/radial-stacked-bar-chart",
|
||||
"topic": "Radial Layouts",
|
||||
"description": "Creative circular visualizations"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/gradient-encoding",
|
||||
"topic": "Advanced Encodings",
|
||||
"description": "Novel visual encoding techniques"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/streamgraph-transitions",
|
||||
"topic": "Complex Transitions",
|
||||
"description": "Sophisticated animated transitions"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/force-directed-lattice",
|
||||
"topic": "Custom Force Simulations",
|
||||
"description": "Advanced physics-based interactions"
|
||||
},
|
||||
{
|
||||
"url": "https://observablehq.com/@d3/cluster-dendrogram",
|
||||
"topic": "Advanced Clustering",
|
||||
"description": "Hierarchical clustering visualization"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"web_search_templates": [
|
||||
"D3.js {technique} tutorial site:observablehq.com",
|
||||
"D3 {chart_type} best practices",
|
||||
"D3.js {feature} examples",
|
||||
"Advanced D3 {area} techniques",
|
||||
"D3 interactive {element} implementation",
|
||||
"D3.js performance optimization {context}",
|
||||
"D3 {visualization_type} accessibility",
|
||||
"D3 responsive {chart_type} design"
|
||||
],
|
||||
|
||||
"url_selection_strategy": {
|
||||
"mode": "progressive",
|
||||
"description": "Select URLs based on iteration number and previous learnings",
|
||||
"fallback": "dynamic_search",
|
||||
"avoid_duplicates": true,
|
||||
"track_used_urls": true
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,331 @@
|
|||
# D3 Data Visualization - Progressive Web-Enhanced Specification
|
||||
|
||||
## Core Challenge
|
||||
Create progressively sophisticated D3.js data visualizations that improve with each iteration by integrating knowledge from web documentation, tutorials, and examples. Each iteration should represent a measurable improvement in visual design, interactivity, data handling, or technical implementation.
|
||||
|
||||
## Output Requirements
|
||||
|
||||
**File Naming**: `d3_viz_[iteration_number].html`
|
||||
|
||||
**Content Structure**: Self-contained D3 visualization with embedded data
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>D3 Visualization [iteration_number]: [Descriptive Name]</title>
|
||||
<script src="https://d3js.org/d3.v7.min.js"></script>
|
||||
<style>
|
||||
/* Visualization-specific styling */
|
||||
/* Progressive enhancement of visual design */
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="visualization-container">
|
||||
<h1>[Descriptive Visualization Title]</h1>
|
||||
<div id="controls">
|
||||
<!-- Interactive controls for the visualization -->
|
||||
</div>
|
||||
<div id="viz">
|
||||
<!-- D3 renders here -->
|
||||
</div>
|
||||
<div id="insights">
|
||||
<!-- Data insights, legends, annotations -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Embedded data (realistic, demonstrative)
|
||||
const data = [/* data here */];
|
||||
|
||||
// D3 visualization implementation
|
||||
// Progressive improvements from web research
|
||||
// New techniques learned from current iteration's URL
|
||||
|
||||
// Iteration-specific innovations
|
||||
// Accessibility features
|
||||
// Responsive design
|
||||
// Interactive elements
|
||||
</script>
|
||||
|
||||
<!-- Documentation footer -->
|
||||
<footer>
|
||||
<h3>Iteration [N] Improvements</h3>
|
||||
<ul>
|
||||
<li><strong>Web Source:</strong> [URL fetched for this iteration]</li>
|
||||
<li><strong>New Technique:</strong> [What was learned and applied]</li>
|
||||
<li><strong>Enhancement:</strong> [Specific improvement over previous iteration]</li>
|
||||
</ul>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## Progressive Enhancement Dimensions
|
||||
|
||||
### **Visual Design Evolution**
|
||||
- **Iteration 1-3**: Basic chart types (bar, line, scatter) with clean styling
|
||||
- **Iteration 4-6**: Advanced color schemes, gradients, annotations, responsive layouts
|
||||
- **Iteration 7-10**: Complex compositions, small multiples, linked views, brushing
|
||||
- **Iteration 11+**: Innovative visual encodings, custom force simulations, advanced interactions
|
||||
|
||||
### **Interactivity Sophistication**
|
||||
- **Basic**: Tooltips, hover effects, clickable elements
|
||||
- **Intermediate**: Zooming, panning, brushing, filtering, transitions
|
||||
- **Advanced**: Drag interactions, real-time data updates, coordinated multi-view
|
||||
- **Expert**: Custom force simulations, physics-based interactions, generative animations
|
||||
|
||||
### **Data Handling Complexity**
|
||||
- **Simple**: Embedded arrays, basic data structures
|
||||
- **Moderate**: Hierarchical data, nested structures, data transformations
|
||||
- **Advanced**: Time-series data, geospatial data, network graphs
|
||||
- **Expert**: Real-time data streams, large datasets with virtualization, external APIs
|
||||
|
||||
### **Technical Implementation**
|
||||
- **Foundation**: Core D3 selections, scales, axes, basic shapes
|
||||
- **Intermediate**: Layouts (hierarchy, force, chord), transitions, generators
|
||||
- **Advanced**: Custom scales, advanced projections, data joins, enter/exit/update patterns
|
||||
- **Expert**: WebGL integration, canvas rendering for performance, worker threads
|
||||
|
||||
## Web Research Integration Strategy
|
||||
|
||||
### **Initial Priming Phase URLs**
|
||||
The priming agent should research these foundational topics:
|
||||
1. D3.js official documentation (d3js.org)
|
||||
2. Observable D3 tutorials and examples
|
||||
3. D3 Graph Gallery for pattern library
|
||||
4. Mike Bostock's blocks and articles
|
||||
5. Recent D3.js best practices and v7+ features
|
||||
|
||||
### **Iteration URL Strategy**
|
||||
|
||||
**URL Categories for Progressive Learning:**
|
||||
|
||||
1. **Foundation URLs (Iterations 1-5)**
|
||||
- D3 official API documentation pages
|
||||
- Basic chart tutorials (bar, line, scatter, pie)
|
||||
- Scale and axis fundamentals
|
||||
- Selection and data binding basics
|
||||
|
||||
2. **Intermediate URLs (Iterations 6-12)**
|
||||
- D3 layout documentation (force, hierarchy, chord)
|
||||
- Transition and animation guides
|
||||
- Interactive visualization tutorials
|
||||
- Color theory and D3 color scales
|
||||
- Responsive D3 patterns
|
||||
|
||||
3. **Advanced URLs (Iterations 13-20)**
|
||||
- Complex force simulations
|
||||
- Geographic projections and maps
|
||||
- Network visualization techniques
|
||||
- Performance optimization for large datasets
|
||||
- Custom interpolators and transitions
|
||||
|
||||
4. **Expert URLs (Iterations 21+)**
|
||||
- Cutting-edge D3 techniques
|
||||
- WebGL integration with D3
|
||||
- Real-time data visualization
|
||||
- Advanced interaction patterns
|
||||
- Novel visual encoding research papers
|
||||
|
||||
### **Dynamic URL Discovery**
|
||||
Each iteration can also perform targeted web searches:
|
||||
- "D3.js [specific technique] tutorial"
|
||||
- "D3 [chart type] best practices"
|
||||
- "D3 interactive [feature] example"
|
||||
- "Advanced D3 [specific area] technique"
|
||||
|
||||
## Visualization Types to Explore
|
||||
|
||||
### **Statistical Visualizations**
|
||||
- Bar charts (vertical, horizontal, grouped, stacked)
|
||||
- Line charts (single, multi-series, area, streamgraph)
|
||||
- Scatter plots (basic, bubble, matrix)
|
||||
- Box plots, violin plots, beeswarm plots
|
||||
- Histograms and distribution plots
|
||||
|
||||
### **Hierarchical Visualizations**
|
||||
- Tree diagrams (tidy tree, radial tree)
|
||||
- Treemaps (squarified, binary, slice-dice)
|
||||
- Sunburst diagrams
|
||||
- Circle packing
|
||||
- Icicle plots
|
||||
|
||||
### **Network Visualizations**
|
||||
- Force-directed graphs
|
||||
- Arc diagrams
|
||||
- Chord diagrams
|
||||
- Sankey diagrams
|
||||
- Hierarchical edge bundling
|
||||
|
||||
### **Geographic Visualizations**
|
||||
- Choropleth maps
|
||||
- Point maps with clustering
|
||||
- Flow maps
|
||||
- Cartograms
|
||||
- Globe projections
|
||||
|
||||
### **Temporal Visualizations**
|
||||
- Time series with brushing
|
||||
- Calendar heatmaps
|
||||
- Gantt charts
|
||||
- Horizon charts
|
||||
- Streamgraphs
|
||||
|
||||
### **Advanced/Novel Visualizations**
|
||||
- Parallel coordinates
|
||||
- Voronoi diagrams
|
||||
- Contour plots
|
||||
- Custom force simulations
|
||||
- Generative/algorithmic art with data
|
||||
|
||||
## Quality Standards
|
||||
|
||||
### **Code Quality**
|
||||
- **D3 Best Practices**: Proper data joins, efficient updates, semantic selections
|
||||
- **Performance**: Optimized for 60fps animations, efficient rendering
|
||||
- **Accessibility**: ARIA labels, keyboard navigation, screen reader support
|
||||
- **Responsive**: Works on mobile, tablet, desktop with appropriate scaling
|
||||
- **Clean Code**: Well-organized, commented, maintainable JavaScript
|
||||
|
||||
### **Visual Excellence**
|
||||
- **Clarity**: Information is immediately understandable
|
||||
- **Aesthetics**: Professional design, harmonious colors, appropriate typography
|
||||
- **Innovation**: Each iteration introduces novel elements or techniques
|
||||
- **Data-Ink Ratio**: Maximize information, minimize clutter
|
||||
- **Storytelling**: Visualization reveals insights and supports understanding
|
||||
|
||||
### **Web Integration Quality**
|
||||
- **Source Attribution**: Each iteration credits the web source that inspired it
|
||||
- **Knowledge Application**: Demonstrates specific technique learned from URL
|
||||
- **Progressive Learning**: Shows clear improvement over previous iteration
|
||||
- **Novel Synthesis**: Combines multiple web sources creatively when appropriate
|
||||
|
||||
## Iteration Evolution Pattern
|
||||
|
||||
### **Knowledge Accumulation Strategy**
|
||||
|
||||
**Wave 1 (Iterations 1-5): Foundation Building**
|
||||
- Learn core D3 APIs and patterns
|
||||
- Master basic chart types
|
||||
- Establish coding standards and structure
|
||||
- Focus: Technical competence
|
||||
|
||||
**Wave 2 (Iterations 6-12): Enhancement & Interaction**
|
||||
- Add sophisticated interactions
|
||||
- Improve visual design substantially
|
||||
- Introduce advanced D3 layouts
|
||||
- Focus: User experience
|
||||
|
||||
**Wave 3 (Iterations 13-20): Innovation & Complexity**
|
||||
- Tackle complex data structures
|
||||
- Create novel visualization types
|
||||
- Optimize for performance
|
||||
- Focus: Technical excellence
|
||||
|
||||
**Wave 4 (Iterations 21+): Mastery & Experimentation**
|
||||
- Push D3 boundaries
|
||||
- Integrate cutting-edge techniques
|
||||
- Create publication-quality visualizations
|
||||
- Focus: Artistic and technical mastery
|
||||
|
||||
### **Improvement Metrics**
|
||||
|
||||
Each iteration should improve on at least one dimension:
|
||||
- **Visual Design**: Better colors, layout, typography, spacing
|
||||
- **Interactivity**: New interaction patterns, smoother transitions
|
||||
- **Data Handling**: More complex data, better transformations
|
||||
- **Performance**: Faster rendering, smoother animations
|
||||
- **Accessibility**: Better keyboard support, ARIA labels, color contrast
|
||||
- **Code Quality**: Cleaner architecture, better patterns
|
||||
- **Innovation**: Novel techniques, creative applications
|
||||
|
||||
## Web Research Directive
|
||||
|
||||
### **For Each Iteration**
|
||||
|
||||
**Before Generating:**
|
||||
1. Fetch assigned web URL
|
||||
2. Analyze the content for:
|
||||
- New D3 techniques or APIs
|
||||
- Design patterns and best practices
|
||||
- Code examples and implementations
|
||||
- Visual design inspiration
|
||||
- Interaction patterns
|
||||
3. Identify 1-3 specific learnings to apply
|
||||
4. Plan how to integrate learnings with previous iterations
|
||||
|
||||
**During Generation:**
|
||||
1. Apply new technique from web source
|
||||
2. Maintain continuity with previous work where appropriate
|
||||
3. Document what was learned and how it was applied
|
||||
4. Ensure the iteration is genuinely improved, not just different
|
||||
|
||||
**After Generation:**
|
||||
1. Document the web source in the footer
|
||||
2. Explicitly state the improvement over previous iteration
|
||||
3. Note what future iterations could explore
|
||||
|
||||
## Data Strategy
|
||||
|
||||
### **Embedded Data Requirements**
|
||||
- Use realistic, meaningful datasets
|
||||
- Data should be appropriate for the visualization type
|
||||
- Include enough data to demonstrate the technique (50-500 data points typically)
|
||||
- For hierarchical data, ensure proper nesting
|
||||
- For network data, ensure connected graph structure
|
||||
|
||||
### **Example Data Domains**
|
||||
- Sales/business metrics (revenue, growth, segments)
|
||||
- Scientific data (measurements, experiments, observations)
|
||||
- Social network data (connections, interactions, communities)
|
||||
- Geographic data (countries, cities, regions, statistics)
|
||||
- Temporal data (events over time, trends, patterns)
|
||||
- Categorical data (comparisons, distributions, rankings)
|
||||
|
||||
## Ultra-Thinking Directive
|
||||
|
||||
Before each iteration, deeply consider:
|
||||
|
||||
**Web Source Integration:**
|
||||
- What is the core lesson from the fetched URL?
|
||||
- How can this technique improve upon the previous iteration?
|
||||
- What aspects of the web example are most valuable?
|
||||
- How can I adapt this learning to my specific visualization goal?
|
||||
|
||||
**Progressive Improvement:**
|
||||
- What was limiting about the previous iteration?
|
||||
- How does this iteration represent genuine progress?
|
||||
- What new capability am I adding?
|
||||
- How am I building upon accumulated knowledge?
|
||||
|
||||
**Technical Excellence:**
|
||||
- Am I using D3 best practices from the web source?
|
||||
- Is my code efficient and maintainable?
|
||||
- Have I applied the technique correctly?
|
||||
- What edge cases should I handle?
|
||||
|
||||
**Visual Communication:**
|
||||
- Does this visualization communicate data clearly?
|
||||
- Have I improved the visual design?
|
||||
- Are interactions intuitive and valuable?
|
||||
- What story does this data tell?
|
||||
|
||||
**Innovation Balance:**
|
||||
- Am I innovating while maintaining usability?
|
||||
- Have I combined multiple learnings effectively?
|
||||
- Is this iteration production-ready or experimental?
|
||||
- What makes this visualization memorable?
|
||||
|
||||
## Success Criteria
|
||||
|
||||
A successful D3 iteration demonstrates:
|
||||
1. **Web Learning Applied**: Specific technique from URL is implemented correctly
|
||||
2. **Measurable Improvement**: Clear advancement over previous iteration
|
||||
3. **Technical Quality**: Proper D3 patterns, performant code, accessible
|
||||
4. **Visual Excellence**: Professional design, clear communication, aesthetic appeal
|
||||
5. **Self-Contained**: Works perfectly as standalone HTML file with D3 CDN
|
||||
6. **Documented**: Clear explanation of improvements and web source attribution
|
||||
|
||||
Generate visualizations that progressively evolve from competent implementations to masterful, publication-quality interactive data visualizations through systematic web-enhanced learning.
|
||||
Loading…
Reference in New Issue