
Venn Diagram Generator
- 6 installs
- 2 repo stars
- Updated August 1, 2026
- vishalsachdev/claude-skills
Helps with ai & agent building tasks.
About
venn-diagram-generator is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- venn-diagram-generator
- AI & Agent Building
- AI-coding skill
Venn Diagram Generator by the numbers
- 6 all-time installs (skills.sh)
- +1 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #12,739 of 16,556 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/vishalsachdev/claude-skills --skill venn-diagram-generatorAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 6 |
|---|---|
| repo stars | ★ 2 |
| Last updated | August 1, 2026 |
| Repository | vishalsachdev/claude-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Venn Diagram Generator
Overview
Generate interactive Venn diagram visualizations using venn.js and D3.js for intelligent textbooks. Creates complete MicroSim packages with standalone HTML files, MkDocs integration, and Dublin Core metadata. Each diagram features customizable colors, interactive tooltips, and follows the educational MicroSim pattern for seamless integration into educational content.
When to Use This Skill
Use the venn-diagram-generator skill when users request:
- Venn diagrams showing set relationships
- Comparison diagrams between 2-4 categories
- Visual representations of overlapping concepts
- Set theory illustrations
- Intersection and union visualizations
- Categorical relationship diagrams
- Euler diagrams
Example user requests:
- "Create a Venn diagram comparing Python, JavaScript, and Java"
- "Make a 2-circle Venn diagram showing cats and dogs"
- "Generate a diagram showing the overlap between AI, ML, and Data Science"
- "Visualize the relationship between sets A, B, and C"
Workflow
Step 1: Gather Diagram Requirements
If the user has NOT provided a title, ask them for one using clear, friendly language:
To create your Venn diagram, I need a title. What would you like to call this diagram?
Examples:
- "Programming Languages Comparison"
- "Pet Characteristics"
- "Technology Skill Overlap"Required information before proceeding:
1. Title: Clear, descriptive name for the diagram 2. Sets: 2-4 distinct categories/sets to compare 3. Relationships: Understanding of which sets overlap and how 4. Context: Educational purpose or subject area 5. Definitions: Educational definitions for each set and intersection (for tooltips)
Check for Existing Definitions (IMPORTANT):
Before asking the user for definitions, check if /docs/glossary.md exists and contains definitions for the set terms:
1. Read the glossary file if it exists: Read /docs/glossary.md 2. Extract relevant definitions for each set/term in the diagram 3. Use glossary definitions if available - they are ISO 11179-compliant and ensure consistency 4. Only ask the user if definitions are missing or unclear
Example glossary lookup:
If creating diagram for "AI, Machine Learning, Deep Learning":
- Search glossary.md for "Artificial Intelligence", "Machine Learning", "Deep Learning"
- Extract the definitions
- Use them directly in the definitions objectIf the description is incomplete or unclear, prompt the user for additional information:
To create an accurate Venn diagram, I need more information:
1. What sets/categories do you want to compare?
2. What items or characteristics are shared between sets?
3. Are there any items unique to each set?
4. What's the educational purpose of this diagram?
5. (Only if not in glossary) How would you define each set and their overlaps?Priority for Definitions:
1. First: Check /docs/glossary.md for existing definitions 2. Second: Use definitions provided by the user 3. Third: Create concise, educational definitions based on context
Note on Definitions: Using glossary definitions ensures consistency across the textbook and leverages existing ISO 11179-compliant content. Every hover interaction becomes a teaching moment that reinforces concepts from the glossary.
Step 2: Design the Venn Diagram Data
Consult references/venn-js-reference.md for detailed syntax guidance and examples.
Design decisions:
1. Determine set count (2, 3, or 4 circles):
- 2 circles: Simple comparisons
- 3 circles: Complex relationships with multiple overlaps
- 4+ circles: Maximum complexity (use sparingly)
2. Define set sizes: Use proportional values that reflect relationships:
- For symbolic diagrams: Use consistent sizes (e.g., all 10)
- For data-driven diagrams: Use actual proportional values
- Ensure intersections don't exceed smallest containing set
3. Choose color palette: Select from educational-friendly schemes:
- Primary Colors: Red (#FF6B6B), Cyan (#4ECDC4), Yellow (#FFE66D)
- Cool Tones: Blue-Purple (#667eea), Purple (#764ba2), Sky Blue (#4facfe)
- Pastels: Powder Blue (#a8dadc), Mint (#f1faee), Coral (#e63946)
- Custom: Match textbook theme colors
4. Structure the data in venn.js format:
// 2-Circle Example
var sets = [
{sets: ['Python'], size: 100},
{sets: ['JavaScript'], size: 100},
{sets: ['Python', 'JavaScript'], size: 40}
];
// 3-Circle Example
var sets = [
{sets: ['AI'], size: 100},
{sets: ['ML'], size: 80},
{sets: ['Data Science'], size: 90},
{sets: ['AI', 'ML'], size: 60},
{sets: ['AI', 'Data Science'], size: 50},
{sets: ['ML', 'Data Science'], size: 55},
{sets: ['AI', 'ML', 'Data Science'], size: 40}
];Step 3: Create the MicroSim Directory Structure
Create the diagram directory following the MicroSim pattern:
mkdir -p /docs/sims/[diagram-name]Naming convention:
- Use kebab-case (lowercase with hyphens)
- Descriptive and concise (2-4 words max)
- Avoid special characters
- Examples:
programming-languages,pet-comparison,ml-ai-overlap
Step 4: Generate Files from Templates
Use the template files in assets/template/ as a starting point. Replace all placeholders with actual content.
4.1 Create script.js
Copy assets/template/script.js and replace placeholders:
{{VENN_DATA}}: Replace with the actual sets array (from Step 2){{COLOR_SCHEME}}: Replace with color configuration array- `{{DEFINITIONS}}`: Create educational definitions object (see Educational Tooltips below)
Example color scheme format:
var colorScheme = [
{set: 'Python', color: '#667eea'},
{set: 'JavaScript', color: '#764ba2'},
{set: 'Java', color: '#4facfe'}
];Educational Tooltips (CRITICAL):
Always create a definitions object that maps sets to educational content. Replace meaningless size values with definitions that explain what each region represents.
// Example definitions object
var definitions = {
'Python': 'High-level language known for readability and data science',
'JavaScript': 'Language that runs in browsers for web interactivity',
'Java': 'Platform-independent language used in enterprise applications',
'JavaScript,Python': 'Both are dynamically typed and interpreted languages',
'Java,Python': 'Both support object-oriented programming with classes',
'Java,JavaScript': 'Both use C-like syntax and are widely adopted',
'Java,JavaScript,Python': 'All three support variables, loops, and functions'
};
// Helper function to retrieve definitions
function getDefinition(sets) {
var key = sets.sort().join(',');
return definitions[key] || sets.join(" ∩ ");
}
// Use in tooltip (NOT d.size)
.on("mouseover", function(event, d) {
tooltip.html(getDefinition(d.sets)); // Educational content
})Definition Guidelines:
1. Concise: Keep under 100 characters (1 sentence ideal) 2. Meaningful: Focus on concepts, not numbers or technical details 3. Educational: Explain relationships for intersections 4. Accessible: Use language appropriate for target audience 5. Consistent: Maintain similar tone and structure across all definitions
Good vs Bad Examples:
✅ Good: "Systems that simulate human intelligence and decision-making" ✅ Good: "Overlap: Methods combining statistical analysis with AI"
❌ Bad: "Size: 150" (not educational) ❌ Bad: "This is the intersection of sets A and B containing 40 elements" (too technical) ❌ Bad: "Machine learning algorithms are techniques that..." (too long)
Why This Matters:
- Makes diagrams self-documenting for students
- Provides immediate context without reading external docs
- Reinforces learning objectives through interaction
- Transforms every hover into a teaching moment
Important: Ensure proper JavaScript syntax - the data will be embedded directly into the script.
4.2 Create main.html
Copy assets/template/main.html and replace these placeholders:
{{TITLE}}: Diagram title (e.g., "Programming Languages Comparison"){{SUBTITLE}}: Brief subtitle (e.g., "Interactive Venn Diagram"){{DESCRIPTION}}: 2-3 sentence explanation of what the diagram shows
The main.html template already includes:
- D3.js v7.9.0 from CDN
- venn.js v0.2.20 from CDN
- Link to style.css and script.js
- Proper HTML5 structure
4.3 Create style.css
Copy assets/template/style.css directly - no modifications needed unless custom styling is requested.
The default stylesheet ensures:
- 16px minimum font size for accessibility
- Responsive design for mobile devices
- Interactive tooltip styling
- Clean, professional appearance
- Print-friendly styling
4.4 Create index.md
Copy assets/template/index.md and replace placeholders:
{{TITLE}}: Same as main.html title{{META_DESCRIPTION}}: SEO-friendly description (1 sentence){{OVERVIEW}}: 1-paragraph overview of what the diagram illustrates{{DESCRIPTION}}: Detailed description of the visualization{{SET_RELATIONSHIPS}}: Bulleted list explaining relationships:
- **Set A**: Contains items X, Y, Z (unique to A)
- **Set B**: Contains items M, N, O (unique to B)
- **A ∩ B**: Shared items include P, Q{{KEY_CONCEPTS}}: Bulleted list of educational concepts illustrated{{EDUCATIONAL_APPLICATIONS}}: How teachers/students can use this diagram{{DIAGRAM_NAME}}: Directory name (for iframe embedding example){{RELATED_CONCEPTS}}: Links to related textbook sections
4.5 Create metadata.json
Copy assets/template/metadata.json and replace placeholders:
{{TITLE}}: Diagram title{{DESCRIPTION}}: Brief description (2-3 sentences){{SUBJECT}}: Educational subject area (e.g., "Mathematics", "Computer Science", "Biology"){{DATE}}: Current date in ISO format (YYYY-MM-DD){{COVERAGE}}: Scope of content (e.g., "Introductory", "Intermediate", "Advanced"){{AUDIENCE}}: Target audience (e.g., "High School", "Undergraduate", "General"){{SET_COUNT}}: Number of main circles (2, 3, or 4){{INTERSECTION_COUNT}}: Number of intersection areas{{CONCEPTS_LIST}}: JSON array of set labels with proper quoting:
"Set A", "Set B", "Set C"{{BLOOM_LEVEL}}: Highest Bloom's Taxonomy level (e.g., "Understand", "Apply", "Analyze")
Example metadata.json:
{
"title": "Programming Languages Comparison",
"description": "Interactive Venn diagram showing the overlap and unique features of Python, JavaScript, and Java programming languages",
"subject": "Computer Science",
"creator": "Claude AI with Venn Diagram Generator Skill",
"date": "2025-11-07",
"type": "Interactive Venn Diagram",
"format": "text/html",
"language": "en-US",
"coverage": "Introductory",
"rights": "Educational Use",
"audience": "Undergraduate",
"diagram_type": "venn",
"set_count": "3",
"intersection_count": "7",
"concepts": [
"Python",
"JavaScript",
"Java",
"Programming Paradigms",
"Language Features"
],
"bloom_taxonomy": "Understand",
"version": "1.0",
"library": "venn.js 0.2.20",
"dependencies": ["d3.js 7.9.0"]
}Step 5: Validate and Test
Perform quality checks:
1. Data validation:
- Verify intersection sizes don't exceed smallest containing set
- Check that all set names are consistent across files
- Ensure color array matches number of sets
2. File structure: Verify all 5 files are present:
- ✓ index.md
- ✓ main.html
- ✓ style.css
- ✓ script.js
- ✓ metadata.json
3. Placeholder replacement: Check that no {{PLACEHOLDERS}} remain in any file
4. JavaScript syntax: Ensure script.js has valid JSON for sets array
5. Responsive design: Verify diagram adapts to different screen sizes
Test the diagram:
Open main.html directly in a browser to verify:
- Circles render correctly
- Colors display as intended
- Tooltips appear on hover
- Labels are readable
- No JavaScript errors in console
Step 6: Update MkDocs Navigation (Optional)
If working within a textbook project with mkdocs.yml, suggest adding the diagram to navigation:
nav:
- Visualizations:
- Programming Languages: sims/programming-languages/index.mdOr integrate into relevant chapter:
nav:
- Chapter 2 - Set Theory:
- Introduction: chapters/02/index.md
- Venn Diagrams: sims/set-relationships/index.mdStep 7: Inform the User
Provide a clear summary of what was created:
✓ Created interactive Venn diagram: [Diagram Title]
Location: /docs/sims/[diagram-name]/
Files generated:
✓ main.html - Standalone interactive diagram with venn.js
✓ index.md - MkDocs integration page with iframe embed
✓ style.css - Responsive styling with tooltips
✓ script.js - Venn diagram data and interactive features
✓ metadata.json - Dublin Core metadata for searchability
Features:
• [X]-circle Venn diagram
• Interactive tooltips showing set intersections
• Customized color scheme
• Responsive design for mobile and desktop
• Educational-friendly 16px fonts
The diagram illustrates: [brief description of what it shows]
To view:
1. Standalone: Open /docs/sims/[diagram-name]/main.html in a browser
2. In textbook: Run `mkdocs serve` and navigate to the diagram page
Next steps:
- Test the diagram by opening main.html
- Add navigation link in mkdocs.yml (if applicable)
- Reference from relevant chapter content
- Consider creating related diagrams for connected conceptsBest Practices
Educational Tooltips - Primary Best Practice
ALWAYS use educational definitions in tooltips instead of size values. This is the most important improvement for educational Venn diagrams.
The Problem: Default venn.js examples display size values like "150 users" which provide no educational value. Students see numbers instead of learning content.
The Solution: Create a definitions object that maps each set and intersection to a clear, concise educational definition:
var definitions = {
'AI': 'Systems that simulate human intelligence, reasoning, and decision-making',
'ML': 'Algorithms that learn patterns from data without explicit programming',
'Deep Learning': 'Neural networks with multiple layers that learn complex representations',
'AI,ML': 'Machine Learning is a subset of AI that focuses on learning from data',
'ML,Deep Learning': 'Deep Learning is a specialized form of ML using neural networks',
'AI,ML,Deep Learning': 'Deep Learning represents the intersection of AI and ML approaches'
};
function getDefinition(sets) {
var key = sets.sort().join(',');
return definitions[key] || sets.join(" ∩ ");
}Implementation Pattern:
1. Create definitions object with all possible set combinations 2. Keep each definition under 100 characters (1 sentence) 3. Focus on meaning and relationships, not technical details 4. Use accessible language for your target audience 5. Use getDefinition(d.sets) in tooltip, NOT d.size
Impact: Every hover interaction becomes a teaching moment that reinforces learning objectives and provides immediate context.
Design Principles
1. Clarity over Complexity:
- Prefer 2-3 circles for optimal readability
- Use 4+ circles only when absolutely necessary
- Consider multiple simple diagrams instead of one complex diagram
2. Proportional Sizing:
- For data-driven diagrams, use actual proportions
- For conceptual diagrams, use symbolic consistent sizes
- Ensure mathematical validity (intersections ≤ smallest set)
3. Color Selection:
- Use high-contrast colors for accessibility
- Apply colorblind-safe palettes when possible
- Maintain consistent opacity (0.70-0.85) for overlap visibility
- Use color consistently across related diagrams
4. Meaningful Labels:
- Keep set names concise (1-3 words)
- Use Title Case for professional appearance
- Ensure labels are educational and clear
- Avoid jargon unless appropriate for audience
5. Educational Context:
- Always explain what the diagram teaches
- Provide real-world examples in documentation
- Align with learning objectives
- Include suggested classroom activities
Accessibility
1. Font Size: Minimum 16px for readability from the back of a classroom 2. Color Contrast: WCAG AA compliance (4.5:1 minimum contrast ratio) 3. Alternative Text: Provide descriptive text in index.md 4. Keyboard Navigation: Diagrams work without mouse (D3.js handles this) 5. Screen Readers: Semantic HTML structure in main.html
Educational Integration
1. Align with Learning Goals: Map diagram to specific learning objectives 2. Bloom's Taxonomy: Tag with appropriate cognitive level 3. Prerequisites: Document what students should know first 4. Assessment: Suggest comprehension questions in index.md 5. Extensions: Propose how students could modify the diagram
Common Venn Diagram Patterns
Pattern 1: Simple Comparison (2 Circles)
Use case: Comparing two categories with clear overlap
Example: "Fruits vs Vegetables"
var sets = [
{sets: ['Fruits'], size: 100},
{sets: ['Vegetables'], size: 100},
{sets: ['Fruits', 'Vegetables'], size: 20} // e.g., Tomatoes
];Pattern 2: Triple Intersection (3 Circles)
Use case: Showing complex relationships between three domains
Example: "Math, Physics, Computer Science"
var sets = [
{sets: ['Math'], size: 100},
{sets: ['Physics'], size: 100},
{sets: ['CS'], size: 100},
{sets: ['Math', 'Physics'], size: 40}, // e.g., Calculus
{sets: ['Math', 'CS'], size: 35}, // e.g., Algorithms
{sets: ['Physics', 'CS'], size: 30}, // e.g., Simulations
{sets: ['Math', 'Physics', 'CS'], size: 15} // e.g., Computational Physics
];Pattern 3: Subset Representation (Nested)
Use case: Showing hierarchical relationships (one set inside another)
Example: "Animals > Mammals > Dogs"
var sets = [
{sets: ['Animals'], size: 150},
{sets: ['Mammals'], size: 50},
{sets: ['Animals', 'Mammals'], size: 50} // Mammals ⊆ Animals
];Pattern 4: Disjoint Sets (No Overlap)
Use case: Showing mutually exclusive categories
Example: "Odd Numbers vs Even Numbers"
var sets = [
{sets: ['Odd'], size: 100},
{sets: ['Even'], size: 100}
// No intersection - sets are disjoint
];Troubleshooting
Common Issues
Issue: Sets data is invalid
- Symptom: Diagram doesn't render or JavaScript errors
- Solution: Check that intersection sizes don't exceed individual set sizes
- Example Fix:
// BAD
{sets: ['A'], size: 10},
{sets: ['A','B'], size: 15} // Can't be larger than A!
// GOOD
{sets: ['A'], size: 20},
{sets: ['A','B'], size: 15}Issue: Colors not showing correctly
- Symptom: All circles are same color
- Solution: Verify set names in color scheme exactly match set names in data
- Example Fix:
// Data uses 'Python' but colors use 'python' (case mismatch)
var sets = [{sets: ['Python'], size: 10}];
var colorScheme = [{set: 'python', color: '#667eea'}]; // Wrong!
// Correct
var colorScheme = [{set: 'Python', color: '#667eea'}]; // Fixed!Issue: Diagram too small/large
- Symptom: Diagram doesn't fit container or is too small
- Solution: Adjust width/height in script.js
venn.VennDiagram()call - Typical values: Width 600px, Height 450px
Issue: Labels cut off
- Symptom: Set names or intersection values are truncated
- Solution:
1. Increase diagram padding 2. Shorten label text 3. Increase container size 4. Reduce font size (as last resort)
Issue: Tooltips not appearing
- Symptom: No tooltip on hover
- Solution: Check that tooltip CSS class exists in style.css and JavaScript event handlers are attached
Issue: Diagram not responsive on mobile
- Symptom: Diagram doesn't resize on small screens
- Solution: Verify
makeResponsive()function is called and SVG has viewBox attribute
Resources
Bundled References
- `references/venn-js-reference.md`: Comprehensive venn.js guide with examples, data formats, styling options, color palettes, and troubleshooting
- `ai-ml-dl-examplejs.js`: Complete working example demonstrating educational tooltips with definitions for AI, ML, and Deep Learning relationships. Shows proper implementation of the definitions pattern.
Bundled Templates
- `assets/template/main.html`: Standalone HTML diagram template with CDN links
- `assets/template/style.css`: Responsive stylesheet with tooltip and print styles
- `assets/template/script.js`: Interactive venn.js initialization with tooltips
- `assets/template/index.md`: MkDocs integration template
- `assets/template/metadata.json`: Dublin Core metadata template
External Resources
- venn.js GitHub: https://github.com/benfred/venn.js
- venn.js Examples: https://benfred.github.io/venn.js/
- D3.js Documentation: https://d3js.org/
- MkDocs Material Theme: https://squidfunk.github.io/mkdocs-material/
- Set Theory Introduction: https://en.wikipedia.org/wiki/Venn_diagram
Examples
Example 1: Two-Circle Comparison
User Request: "Create a Venn diagram comparing dogs and cats"
Generated Data:
var sets = [
{sets: ['Dogs'], size: 100},
{sets: ['Cats'], size: 100},
{sets: ['Dogs', 'Cats'], size: 40}
];
var colorScheme = [
{set: 'Dogs', color: '#667eea'},
{set: 'Cats', color: '#764ba2'}
];Set Relationships:
- Dogs Only: Bark, very loyal, need walks, pack animals
- Cats Only: Meow, independent, use litter box, solitary hunters
- Both: Four legs, fur, domesticated, popular pets, carnivores
Example 2: Three-Circle Knowledge Domains
User Request: "Show the overlap between AI, Machine Learning, and Data Science"
Generated Data:
var sets = [
{sets: ['AI'], size: 120},
{sets: ['Machine Learning'], size: 100},
{sets: ['Data Science'], size: 110},
{sets: ['AI', 'Machine Learning'], size: 70},
{sets: ['AI', 'Data Science'], size: 60},
{sets: ['Machine Learning', 'Data Science'], size: 65},
{sets: ['AI', 'Machine Learning', 'Data Science'], size: 50}
];
var colorScheme = [
{set: 'AI', color: '#667eea'},
{set: 'Machine Learning', color: '#764ba2'},
{set: 'Data Science', color: '#f093fb'}
];
// Educational tooltips
var definitions = {
'AI': 'Systems that simulate human intelligence and decision-making',
'Machine Learning': 'Algorithms that learn patterns from data without explicit programming',
'Data Science': 'Field combining statistics, analysis, and domain expertise to extract insights',
'AI,Machine Learning': 'ML is a core approach within AI for building intelligent systems',
'AI,Data Science': 'AI techniques applied to data analysis and predictive modeling',
'Data Science,Machine Learning': 'ML provides the algorithms that data scientists use for analysis',
'AI,Data Science,Machine Learning': 'The intersection where intelligent systems learn from data'
};
function getDefinition(sets) {
var key = sets.sort().join(',');
return definitions[key] || sets.join(" ∩ ");
}Set Relationships:
- AI Only: Expert systems, robotics, natural language processing
- ML Only: Supervised learning, unsupervised learning, model training
- Data Science Only: Data visualization, statistics, data cleaning
- AI ∩ ML: Neural networks, deep learning
- AI ∩ Data Science: Predictive analytics, decision trees
- ML ∩ Data Science: Feature engineering, cross-validation
- All Three: Classification algorithms, regression, model evaluation
Example 3: Programming Language Features
User Request: "Compare Python, JavaScript, and Java programming languages"
Generated Data:
var sets = [
{sets: ['Python'], size: 100},
{sets: ['JavaScript'], size: 100},
{sets: ['Java'], size: 100},
{sets: ['Python', 'JavaScript'], size: 45},
{sets: ['Python', 'Java'], size: 40},
{sets: ['JavaScript', 'Java'], size: 35},
{sets: ['Python', 'JavaScript', 'Java'], size: 25}
];
var colorScheme = [
{set: 'Python', color: '#4ECDC4'},
{set: 'JavaScript', color: '#FFE66D'},
{set: 'Java', color: '#FF6B6B'}
];Set Relationships:
- Python Only: Indentation-based syntax, data science libraries, simple syntax
- JavaScript Only: Runs in browsers, async/await, DOM manipulation
- Java Only: JVM-based, strongly typed, enterprise focus
- Python ∩ JavaScript: Dynamic typing, interpreted, first-class functions
- Python ∩ Java: Object-oriented, classes, large standard library
- JavaScript ∩ Java: C-like syntax, used in web development
- All Three: Variables, loops, functions, arrays/lists, popular languages
Integration with Other Skills
This skill works well with other intelligent textbook skills:
- glossary-generator: PRIMARY INTEGRATION - Always check
/docs/glossary.mdfirst for ISO 11179-compliant definitions to use in tooltips. This ensures consistency across the textbook and reinforces glossary terms through interactive hover experiences. - learning-graph-generator: Visualize concept dependencies as Venn diagrams showing prerequisite relationships
- chapter-content-generator: Embed diagrams in chapter content with iframe integration
- quiz-generator: Create questions about set relationships shown in the diagram
- microsim-p5: Use Venn diagrams for static set visualizations, p5.js for dynamic simulations
Best Practice: When creating Venn diagrams for an existing textbook project, always check the glossary first. This creates a cohesive learning experience where glossary terms are reinforced through multiple touchpoints (definitions, diagrams, quizzes).
Version History
v1.0 - Initial release
- 2-4 circle Venn diagram generation
- Interactive tooltips with hover effects
- Customizable color schemes
- Responsive design for mobile and desktop
- MicroSim package creation with full documentation
- Dublin Core metadata support
- Educational-friendly 16px fonts
// Venn Diagram Example for AI, ML, and Deep Learning
/*
Here's the generalized rule for educational tooltips in Venn diagrams:
Educational Tooltips Rule
Use Definitions Instead of Size Values
Problem: The default venn.js examples show size values (e.g., "150 users") which are not
educational for learning-focused diagrams.
Solution: Replace size numbers with educational definitions that explain what each region
represents.
Implementation Pattern:
// 1. Create a definitions object mapping sets to educational content
var definitions = {
'SetA': 'Clear, concise definition of Set A',
'SetB': 'Clear, concise definition of Set B',
'SetA,SetB': 'Explanation of the relationship/overlap between A and B',
'SetA,SetB,SetC': 'Explanation of triple intersection'
};
// 2. Create helper function to lookup definitions
function getDefinition(sets) {
var key = sets.sort().join(',');
return definitions[key] || sets.join(" ∩ ");
}
// 3. Use in tooltip
.on("mouseover", function(event, d) {
tooltip.html(getDefinition(d.sets)); // NOT d.size
})
Definition Guidelines:
1. Keep definitions concise (1 sentence, under 100 characters ideal)
2. Focus on meaning not technical details
3. Explain relationships for intersections (what the overlap means)
4. Use accessible language appropriate for target audience
5. Be consistent in tone and structure across all definitions
Examples:
Good definitions:
- "Systems that simulate human intelligence and decision-making"
- "Overlap: Methods that combine statistical analysis with AI"
Poor definitions:
- "Size: 150" ❌ (not educational)
- "This is the intersection of sets A and B containing 40 elements" ❌ (too technical)
- "Machine learning algorithms are..." (too long) ❌
Why This Matters:
- Makes diagrams self-documenting for students
- Provides immediate context without reading external docs
- Reinforces learning objectives through interaction
- Replaces meaningless numbers with meaningful content
Complete Educational Example:
var definitions = {
'Mammals': 'Warm-blooded vertebrates that nurse their young',
'Carnivores': 'Animals that primarily eat meat',
'Mammals,Carnivores': 'Meat-eating mammals like lions, wolves, and seals'
};
This pattern ensures every hover interaction is a teaching moment rather than just visual
feedback.
*/
// Venn diagram data - Nested sets showing AI ⊃ ML ⊃ DL hierarchy
var sets = [
{sets: ['AI'], size: 150},
{sets: ['ML'], size: 90},
{sets: ['Deep Learning'], size: 40},
{sets: ['AI', 'ML'], size: 90},
{sets: ['ML', 'Deep Learning'], size: 40},
{sets: ['AI', 'Deep Learning'], size: 40},
{sets: ['AI', 'ML', 'Deep Learning'], size: 40}
];
// Color configuration - Blue gradient from light (AI) to dark (DL)
var colorScheme = [
{set: 'AI', color: '#87CEEB'}, // Light blue (outer)
{set: 'ML', color: '#4169E1'}, // Medium blue (middle)
{set: 'Deep Learning', color: '#1E3A8A'} // Dark blue (inner)
];
// Initialize the Venn diagram
function initVennDiagram() {
// Create the Venn diagram chart
var chart = venn.VennDiagram()
.width(600)
.height(450);
// Select the container and bind data
var div = d3.select("#venn")
.datum(sets)
.call(chart);
// Apply color scheme to all areas (including intersections)
// For nested sets, use the most specific (innermost) set's color
div.selectAll("g")
.select("path")
.style("fill", function(d) {
// Determine color based on which sets are involved
// Priority: Deep Learning > Machine Learning > AI
if (d.sets.includes('DL')) {
return '#1E3A8A'; // Dark blue for DL
} else if (d.sets.includes('Machine Learning')) {
return '#4169E1'; // Medium blue for ML
} else if (d.sets.includes('AI')) {
return '#87CEEB'; // Light blue for AI
}
return '#999'; // Fallback gray
});
// Ensure all text labels are dark gray and visible
div.selectAll("text")
.style("fill", "#333")
.style("font-weight", "bold")
.style("font-size", "16px");
// Educational definitions for each set
var definitions = {
'AI': 'Systems that simulate human intelligence, reasoning, and decision-making',
'ML': 'Algorithms that learn patterns from data without explicit programming',
'Deep Learning': 'Neural networks with multiple layers that learn complex representations',
'AI,ML': 'Machine Learning is a subset of AI that focuses on learning from data',
'ML,Deep Learning': 'Deep Learning is a specialized form of ML using neural networks',
'AI,Deep Learning': 'Deep Learning combines AI principles with neural network architectures',
'AI,ML,Deep Learning': 'Deep Learning represents the intersection of AI and ML approaches'
};
// Helper function to get definition based on sets
function getDefinition(sets) {
var key = sets.sort().join(',');
return definitions[key] || sets.join(" ∩ ");
}
// Add interactive tooltips
var tooltip = d3.select("body").append("div")
.attr("class", "venntooltip");
// Hover effects - following official venn.js pattern
div.selectAll("g")
.on("mouseover", function(event, d) {
// Sort all areas relative to current to ensure proper z-ordering
venn.sortAreas(div, d);
// Display tooltip with educational definition
tooltip.transition().duration(400).style("opacity", 0.9);
tooltip.html(getDefinition(d.sets))
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 28) + "px");
// Highlight the current path - only change opacity, not fill color
var selection = d3.select(this).transition("tooltip").duration(400);
selection.select("path")
.style("fill-opacity", d.sets.length == 1 ? 0.4 : 0.1)
.style("stroke-opacity", 1);
})
.on("mouseout", function(event, d) {
tooltip.transition().duration(400).style("opacity", 0);
// Reset opacity only - use lower values so text remains readable
var selection = d3.select(this).transition("tooltip").duration(400);
selection.select("path")
.style("fill-opacity", d.sets.length == 1 ? 0.25 : 0.0)
.style("stroke-opacity", 0);
});
// Make diagram responsive
makeResponsive();
}
// Responsive behavior
function makeResponsive() {
var container = d3.select("#venn");
var svg = container.select("svg");
if (!svg.empty()) {
var width = parseInt(svg.attr("width"));
var height = parseInt(svg.attr("height"));
var aspect = width / height;
svg.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMidYMid meet")
.attr("width", "100%")
.attr("height", "100%");
// Redraw on window resize
d3.select(window).on("resize", function() {
var targetWidth = container.node().getBoundingClientRect().width;
svg.attr("width", targetWidth)
.attr("height", targetWidth / aspect);
});
}
}
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
initVennDiagram();
});
{{TITLE}}
Overview
{{OVERVIEW}}
Interactive Diagram
<iframe src="main.html" width="100%" height="600px"></iframe>
View the Diagram Fullscreen{ .md-button .md-button--primary }
Description
{{DESCRIPTION}}
Set Relationships
{{SET_RELATIONSHIPS}}
Key Concepts
{{KEY_CONCEPTS}}
Educational Applications
{{EDUCATIONAL_APPLICATIONS}}
Embedding This Diagram
You can include this Venn diagram on your website using the following iframe:
<iframe src="https://your-site.github.io/sims/{{DIAGRAM_NAME}}/main.html"
width="100%"
height="600px"
style="border: 1px solid #ccc; border-radius: 4px;">
</iframe>Related Concepts
{{RELATED_CONCEPTS}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{TITLE}}</title>
<link rel="stylesheet" href="style.css">
<!-- D3.js v7 - Required dependency for venn.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js"></script>
<!-- venn.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/venn.js/0.2.20/venn.min.js"></script>
</head>
<body>
<div class="container">
<header>
<h1>{{TITLE}}</h1>
<p class="subtitle">{{SUBTITLE}}</p>
</header>
<main>
<div class="diagram-container">
<div id="venn"></div>
</div>
<div class="description">
<h2>About This Diagram</h2>
<p>{{DESCRIPTION}}</p>
</div>
</main>
<footer>
<p>Generated with <a href="https://github.com/benfred/venn.js" target="_blank">venn.js</a> and <a href="https://d3js.org/" target="_blank">D3.js</a></p>
<p><a href=".">Back to Lesson Plan</a></p>
</footer>
</div>
<script src="script.js"></script>
</body>
</html>
{
"title": "{{TITLE}}",
"description": "{{DESCRIPTION}}",
"subject": "{{SUBJECT}}",
"creator": "Claude AI with Venn Diagram Generator Skill",
"date": "{{DATE}}",
"type": "Interactive Venn Diagram",
"format": "text/html",
"language": "en-US",
"coverage": "{{COVERAGE}}",
"rights": "Educational Use",
"audience": "{{AUDIENCE}}",
"diagram_type": "venn",
"set_count": "{{SET_COUNT}}",
"intersection_count": "{{INTERSECTION_COUNT}}",
"concepts": [
{{CONCEPTS_LIST}}
],
"bloom_taxonomy": "{{BLOOM_LEVEL}}",
"version": "1.0",
"library": "venn.js 0.2.20",
"dependencies": ["d3.js 7.9.0"]
}
// Venn Diagram Configuration and Rendering
// This script is populated with data specific to each diagram
// Venn diagram data - Replace {{VENN_DATA}} with actual sets data
var sets = {{VENN_DATA}};
// Color configuration - Replace {{COLOR_SCHEME}} with actual colors
var colorScheme = {{COLOR_SCHEME}};
// Initialize the Venn diagram
function initVennDiagram() {
// Create the Venn diagram chart
var chart = venn.VennDiagram()
.width(600)
.height(450);
// Select the container and bind data
var div = d3.select("#venn")
.datum(sets)
.call(chart);
// Apply color scheme to circles
if (colorScheme && colorScheme.length > 0) {
colorScheme.forEach(function(colorConfig) {
d3.selectAll("#venn .venn-circle")
.filter(function(d) {
return d.sets.length === 1 && d.sets[0] === colorConfig.set;
})
.select("path")
.style("fill", colorConfig.color);
});
}
// Add interactive tooltips
var tooltip = d3.select("body").append("div")
.attr("class", "venntooltip");
// Hover effects
div.selectAll("g")
.on("mouseover", function(event, d) {
// Sort all areas relative to current to ensure proper z-ordering
venn.sortAreas(div, d);
// Display tooltip
tooltip.transition().duration(200).style("opacity", 0.9);
// Generate tooltip text
var tooltipText = d.sets.join(" ∩ ") + ": " + d.size;
tooltip.html(tooltipText)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 28) + "px");
// Highlight current area
d3.select(this).select("path")
.style("fill-opacity", 0.95)
.style("stroke-width", "3px");
})
.on("mouseout", function(event, d) {
tooltip.transition().duration(200).style("opacity", 0);
// Reset styling
d3.select(this).select("path")
.style("fill-opacity", function(d) {
return d.sets.length === 1 ? 0.75 : 0.85;
})
.style("stroke-width", "2px");
});
// Make diagram responsive
makeResponsive();
}
// Responsive behavior
function makeResponsive() {
var container = d3.select("#venn");
var svg = container.select("svg");
if (!svg.empty()) {
var width = parseInt(svg.attr("width"));
var height = parseInt(svg.attr("height"));
var aspect = width / height;
svg.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMidYMid meet")
.attr("width", "100%")
.attr("height", "100%");
// Redraw on window resize
d3.select(window).on("resize", function() {
var targetWidth = container.node().getBoundingClientRect().width;
svg.attr("width", targetWidth)
.attr("height", targetWidth / aspect);
});
}
}
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
initVennDiagram();
});
/* Venn Diagram MicroSim Stylesheet */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
line-height: 1.6;
color: #333;
background-color: #f5f5f5;
padding: 20px;
}
.container {
max-width: 900px;
margin: 0 auto;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px 20px;
text-align: center;
}
header h1 {
font-size: 32px;
margin-bottom: 10px;
font-weight: 600;
}
header .subtitle {
font-size: 18px;
opacity: 0.95;
}
main {
padding: 20px;
}
.diagram-container {
background-color: #fafafa;
border: 1px solid #e0e0e0;
border-radius: 6px;
padding: 30px;
margin-bottom: 30px;
min-height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
#venn {
width: 100%;
max-width: 600px;
margin: 0 auto;
}
/* Venn diagram circle styling */
#venn .venn-circle path {
fill-opacity: 0.75;
stroke: #333;
stroke-width: 2px;
}
#venn .venn-circle text {
fill: #333;
font-size: 16px;
font-weight: bold;
pointer-events: none;
}
#venn .venn-intersection path {
fill-opacity: 0.85;
}
#venn .venn-intersection text {
fill: #333;
font-size: 14px;
font-weight: normal;
}
/* Tooltip styling */
.venntooltip {
position: absolute;
text-align: center;
width: auto;
min-width: 80px;
padding: 10px;
font-size: 14px;
background: rgba(0, 0, 0, 0.85);
color: white;
border-radius: 4px;
pointer-events: none;
opacity: 0;
transition: opacity 0.2s;
}
.description {
margin-top: 30px;
}
.description h2 {
font-size: 24px;
margin-bottom: 15px;
color: #667eea;
}
.description p {
font-size: 16px;
line-height: 1.8;
margin-bottom: 10px;
}
footer {
background-color: #f0f0f0;
padding: 20px;
text-align: center;
font-size: 14px;
color: #666;
border-top: 1px solid #e0e0e0;
}
footer a {
color: #667eea;
text-decoration: none;
font-weight: 500;
}
footer a:hover {
text-decoration: underline;
}
footer p {
margin: 5px 0;
}
/* Responsive Design */
@media screen and (max-width: 768px) {
body {
padding: 10px;
}
header h1 {
font-size: 24px;
}
header .subtitle {
font-size: 16px;
}
.diagram-container {
padding: 20px;
min-height: 300px;
}
#venn {
max-width: 100%;
}
}
/* Print Styles */
@media print {
body {
background-color: white;
padding: 0;
}
.container {
box-shadow: none;
}
header {
background: #667eea;
print-color-adjust: exact;
-webkit-print-color-adjust: exact;
}
footer {
page-break-before: avoid;
}
}
venn.js Reference Guide
Overview
venn.js is a JavaScript library for laying out area-proportional Venn and Euler diagrams. It uses D3.js for rendering SVG visualizations.
Dependencies
- D3.js v7+ - Required for DOM manipulation and SVG rendering
- CDN:
https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js
CDN Links
- venn.js:
https://cdnjs.cloudflare.com/ajax/libs/venn.js/0.2.20/venn.min.js - Latest version: 0.2.20 (as of 2024)
Basic Data Format
Venn diagrams require an array of objects where each object represents either: 1. A single set 2. An intersection of multiple sets
Data Structure
var sets = [
{sets: ['A'], size: 12}, // Set A with 12 items
{sets: ['B'], size: 12}, // Set B with 12 items
{sets: ['A','B'], size: 2} // Intersection of A and B with 2 items
];Key properties:
sets: Array of set names (strings)size: Numerical value representing area/countlabel: Optional custom label (defaults to set names)
Creating Diagrams
2-Circle Venn Diagram
var sets = [
{sets: ['Set A'], size: 10},
{sets: ['Set B'], size: 10},
{sets: ['Set A', 'Set B'], size: 3}
];
var chart = venn.VennDiagram();
d3.select("#venn").datum(sets).call(chart);3-Circle Venn Diagram
var sets = [
// Individual sets
{sets: ['A'], size: 12},
{sets: ['B'], size: 12},
{sets: ['C'], size: 12},
// Pairwise intersections
{sets: ['A','B'], size: 2},
{sets: ['A','C'], size: 2},
{sets: ['B','C'], size: 2},
// Triple intersection
{sets: ['A','B','C'], size: 1}
];
var chart = venn.VennDiagram();
d3.select("#venn").datum(sets).call(chart);4+ Circle Venn Diagrams
venn.js supports 4 or more sets, though visual clarity may decrease:
var sets = [
{sets: ['A'], size: 10},
{sets: ['B'], size: 10},
{sets: ['C'], size: 10},
{sets: ['D'], size: 10},
{sets: ['A','B'], size: 2},
{sets: ['A','C'], size: 2},
{sets: ['A','D'], size: 2},
{sets: ['B','C'], size: 2},
{sets: ['B','D'], size: 2},
{sets: ['C','D'], size: 2},
// Add triple and quadruple intersections as needed
];Configuration Options
Basic Configuration
var chart = venn.VennDiagram()
.width(600)
.height(450)
.padding(10); // Padding around diagramAdvanced Options
var chart = venn.VennDiagram()
.width(600)
.height(450)
.fontSize("14px")
.duration(1000) // Animation duration in ms
.styled(true) // Apply default styling
.orientationOrder(function(a, b) {
// Custom ordering function
return a.size - b.size;
});Styling with D3
Apply custom styles after rendering using D3 selectors:
Circle Fill Colors
// Apply colors to individual sets
var colors = {
'A': '#667eea',
'B': '#764ba2',
'C': '#f093fb'
};
d3.selectAll("#venn .venn-circle")
.filter(function(d) { return d.sets.length === 1; })
.select("path")
.style("fill", function(d) { return colors[d.sets[0]]; });Opacity and Strokes
// Adjust fill opacity
d3.selectAll("#venn .venn-circle path")
.style("fill-opacity", 0.75)
.style("stroke", "#333")
.style("stroke-width", "2px");
// Style intersection areas differently
d3.selectAll("#venn .venn-intersection path")
.style("fill-opacity", 0.85);Text Styling
// Style set labels
d3.selectAll("#venn .venn-circle text")
.style("fill", "#333")
.style("font-size", "16px")
.style("font-weight", "bold");
// Style intersection labels
d3.selectAll("#venn .venn-intersection text")
.style("fill", "#333")
.style("font-size", "14px");Interactivity
Tooltips
// Create tooltip element
var tooltip = d3.select("body").append("div")
.attr("class", "venntooltip")
.style("position", "absolute")
.style("opacity", 0);
// Add hover events
var div = d3.select("#venn");
div.selectAll("g")
.on("mouseover", function(event, d) {
// Ensure proper z-ordering
venn.sortAreas(div, d);
// Show tooltip
tooltip.transition().duration(200).style("opacity", 0.9);
tooltip.html(d.sets.join(" ∩ ") + ": " + d.size)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 28) + "px");
// Highlight area
d3.select(this).select("path")
.style("fill-opacity", 0.95);
})
.on("mouseout", function(event, d) {
tooltip.transition().duration(200).style("opacity", 0);
d3.select(this).select("path")
.style("fill-opacity", 0.75);
});Click Events
div.selectAll("g")
.on("click", function(event, d) {
console.log("Clicked:", d.sets.join(", "));
// Add custom click behavior
});Educational Color Schemes
Scheme 1: Primary Colors (Best for 3 sets)
var colors = {
'Set 1': '#FF6B6B', // Red
'Set 2': '#4ECDC4', // Cyan
'Set 3': '#FFE66D' // Yellow
};Scheme 2: Cool Tones (Professional)
var colors = {
'Set 1': '#667eea', // Blue-Purple
'Set 2': '#764ba2', // Purple
'Set 3': '#4facfe' // Sky Blue
};Scheme 3: Pastel (Gentle, Accessible)
var colors = {
'Set 1': '#a8dadc', // Powder Blue
'Set 2': '#f1faee', // Mint Cream
'Set 3': '#e63946' // Imperial Red
};Scheme 4: Earth Tones
var colors = {
'Set 1': '#8ecae6', // Sky
'Set 2': '#219ebc', // Ocean
'Set 3': '#ffb703' // Orange
};Common Patterns
Two-Circle Comparison
Use for comparing two categories (e.g., "Cats vs Dogs", "Python vs JavaScript"):
var sets = [
{sets: ['Category A'], size: 100, label: 'Unique to A'},
{sets: ['Category B'], size: 100, label: 'Unique to B'},
{sets: ['Category A', 'Category B'], size: 50, label: 'Shared'}
];Three-Circle Knowledge Domains
Use for showing overlap between three fields (e.g., "Math, Computer Science, Engineering"):
var sets = [
{sets: ['Math'], size: 100},
{sets: ['CS'], size: 100},
{sets: ['Engineering'], size: 100},
{sets: ['Math', 'CS'], size: 30},
{sets: ['Math', 'Engineering'], size: 25},
{sets: ['CS', 'Engineering'], size: 35},
{sets: ['Math', 'CS', 'Engineering'], size: 15}
];Subset Representation
Show one set as a subset of another by making the intersection size equal to the smaller set:
var sets = [
{sets: ['All Animals'], size: 100},
{sets: ['Mammals'], size: 30},
{sets: ['All Animals', 'Mammals'], size: 30} // Mammals ⊆ Animals
];Best Practices
1. Size Values
- Use proportional sizes that reflect actual relationships
- Ensure intersection sizes don't exceed the smallest containing set
- For purely symbolic diagrams, use consistent sizes (e.g., all 10)
2. Set Names
- Use clear, concise labels (2-4 words max)
- Avoid special characters in set names
- Use Title Case for professional appearance
3. Color Selection
- Choose high-contrast colors for accessibility
- Use colorblind-safe palettes when possible
- Apply consistent opacity (0.70-0.85) for visibility of overlaps
4. Layout
- Keep to 2-3 circles for optimal clarity
- Use 4+ circles only when necessary
- Consider multiple diagrams instead of one complex diagram
5. Responsive Design
Make diagrams responsive:
var svg = d3.select("#venn svg");
var width = parseInt(svg.attr("width"));
var height = parseInt(svg.attr("height"));
svg.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMidYMid meet")
.attr("width", "100%")
.attr("height", "100%");Troubleshooting
Issue: Circles not appearing
Solution: Ensure D3.js is loaded before venn.js:
<script src="d3.js"></script>
<script src="venn.js"></script>Issue: Layout looks wrong
Solution: Check that intersection sizes don't exceed individual set sizes:
// BAD: Intersection larger than sets
{sets: ['A'], size: 5},
{sets: ['B'], size: 5},
{sets: ['A','B'], size: 10} // Error!
// GOOD: Proportional sizes
{sets: ['A'], size: 10},
{sets: ['B'], size: 10},
{sets: ['A','B'], size: 3}Issue: Text labels cut off
Solution: Increase padding or adjust container size:
var chart = venn.VennDiagram()
.width(700)
.height(500)
.padding(20); // Increase paddingIssue: Colors not applying
Solution: Ensure you're selecting the correct elements:
// Select path within circle, not the circle itself
d3.selectAll("#venn .venn-circle path")
.style("fill", "red");Critical Rules for venn.js Hover Interactions
1. Never Modify Fill Colors During Interactions
- Set fill colors once during initialization
- Never change fill property in mouseover/mouseout handlers
- The venn.sortAreas() function can interfere with dynamic color changes
2. Only Modify Opacity Values
Use fill-opacity and stroke-opacity for hover effects: // CORRECT - Change opacity only .on("mouseover", function(event, d) { selection.select("path") .style("fill-opacity", d.sets.length == 1 ? 0.4 : 0.1) .style("stroke-opacity", 1); })
// WRONG - Don't change fill color .on("mouseover", function(event, d) { selection.select("path") .style("fill", "#FF0000") // ❌ Don't do this! })
3. Use Low Opacity Values for Text Readability
Follow the official venn.js example pattern:
- Resting state: Single sets = 0.25, Intersections = 0.0
- Hover state: Single sets = 0.4, Intersections = 0.1
High opacity (0.75-0.85) makes text labels unreadable, especially on dark colors.
4. Use Named Transitions
Use .transition("tooltip") instead of .transition() to avoid conflicts: var selection = d3.select(this).transition("tooltip").duration(400);
5. Don't Reapply Styles After sortAreas()
- Calling venn.sortAreas(div, d) reorders DOM elements
- Do not reapply fill colors or text styling after this call
- The library handles this internally
6. Reference Official Examples
When in doubt, always check the official examples at: https://github.com/benfred/venn.js/tree/master/examples
Especially intersection_tooltip.html for the canonical hover pattern.
Complete Working Pattern:
// Set colors once during initialization div.selectAll("g").select("path") .style("fill", function(d) { return getColor(d); });
// Hover: change opacity only div.selectAll("g") .on("mouseover", function(event, d) { venn.sortAreas(div, d); var selection = d3.select(this).transition("tooltip").duration(400); selection.select("path") .style("fill-opacity", d.sets.length == 1 ? 0.4 : 0.1) .style("stroke-opacity", 1); }) .on("mouseout", function(event, d) { var selection = d3.select(this).transition("tooltip").duration(400); selection.select("path") .style("fill-opacity", d.sets.length == 1 ? 0.25 : 0.0) .style("stroke-opacity", 0); });
Resources
- GitHub Repository: https://github.com/benfred/venn.js
- D3.js Documentation: https://d3js.org/
- Examples and Demos: https://benfred.github.io/venn.js/
- NPM Package: https://www.npmjs.com/package/venn.js
Version Notes
- Current version: 0.2.20
- Breaking changes: None reported between 0.2.x versions
- Browser support: All modern browsers (Chrome, Firefox, Safari, Edge)
- Mobile support: Responsive with proper viewport settings