
Math Function Plotter Plotly
- 10 installs
- 2 repo stars
- Updated August 1, 2026
- vishalsachdev/claude-skills
Helps with ai & agent building tasks.
About
math-function-plotter-plotly is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- math-function-plotter-plotly
- AI & Agent Building
- AI-coding skill
Math Function Plotter Plotly by the numbers
- 10 all-time installs (skills.sh)
- +1 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #11,882 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 math-function-plotter-plotlyAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 10 |
|---|---|
| repo stars | ★ 2 |
| Last updated | August 1, 2026 |
| Repository | vishalsachdev/claude-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Math Function Plotter - Plotly.js MicroSim Generator
Overview
This skill generates interactive mathematical function plots using the Plotly.js JavaScript library. Each MicroSim is optimized for iframe embedding in narrow textbook layouts with minimal margins, responsive design, hover tooltips showing precise coordinates, and interactive sliders allowing users to explore points along the curve.
The skill creates complete MicroSim packages following the repository's standardized structure, including standalone HTML files, responsive CSS, interactive JavaScript, comprehensive markdown documentation, and Dublin Core metadata.
When to Use This Skill
Invoke this skill when users request:
- "Plot a mathematical function"
- "Graph the equation y = ..."
- "Visualize f(x) = ..."
- "Create an interactive function plotter"
- "Show me a graph of [trigonometric/polynomial/exponential] function"
- "Make a plot I can embed in my textbook"
- "Generate a calculus visualization"
- "Create an interactive sine/cosine/tangent graph"
Workflow
Follow these steps to create a mathematical function plot MicroSim:
Step 1: Gather Requirements
Ask the user for the following information:
Required:
- Function expression: The mathematical function to plot (e.g., "sin(x)", "x^2", "e^(-x^2)")
- Title: Name for the MicroSim (e.g., "Sine Function", "Quadratic Function")
- Domain: Range of x-values to plot [xMin, xMax]
Optional (with smart defaults):
- Range: Y-axis limits [yMin, yMax] (auto-calculated if not provided)
- Interactive point: Initial x-position for the slider (default: midpoint of domain)
- Slider step: Increment for slider movement (default: (xMax - xMin) / 100)
- Axis labels: Custom labels for x and y axes (default: "x" and "y")
- Subtitle: Brief description (default: function expression)
- Context: Course/chapter where this will be used (for educational content)
Example conversation:
User: "Create a plot for the sine function"
Assistant: "I'll create an interactive sine function plot. Let me gather some details:
- Title: 'Sine Function Visualization'
- Function: sin(x)
- Domain: Would you like -2π to 2π (approximately -6.28 to 6.28)?
- Is this for a specific course or chapter?"Use clear, friendly language when prompting users. Provide sensible defaults based on common mathematical conventions.
Step 2: Create Directory Structure
Create the MicroSim directory following the standardized pattern:
docs/sims/[microsim-name]/
├── main.html
├── style.css
├── script.js
├── index.md
└── metadata.jsonNaming conventions:
- Use kebab-case (lowercase with hyphens)
- Be descriptive but concise
- Examples:
sine-function,quadratic-parabola,exponential-decay,gaussian-bell-curve
Step 3: Generate main.html
Use the template from assets/template-iframe-main.html and replace placeholders:
Placeholder replacements:
{{TITLE}}→ Full title (e.g., "Sine Function Visualization"){{SUBTITLE}}→ Function expression or description (e.g., "y = sin(x)"){{X_MIN}}→ Minimum x value (e.g., -6.28){{X_MAX}}→ Maximum x value (e.g., 6.28){{X_STEP}}→ Slider step size (e.g., 0.01){{INITIAL_X}}→ Initial slider position (e.g., 0)
Key features to preserve:
- Minimal body margins (
margin: 0; padding: 0;) - Plotly.js CDN link (v2.27.0 or latest stable)
- Link to external
style.cssandscript.js - Semantic HTML5 structure
Step 4: Generate style.css
Use the template from assets/template-iframe-style.css.
Critical requirements:
- Body margins: MUST be
margin: 0; padding: 0;for iframe embedding - Container padding: Maximum 5px (reduces to 2px on mobile)
- Header margins: Maximum 5px top, 2px bottom
- Background: Use
aliceblue(repository standard) - Responsive breakpoints: 768px (tablet), 480px (mobile)
- Plot height: 400px desktop, 300px tablet, 250px mobile
Testing: Ensure the visualization looks good at widths from 320px to 1200px.
Step 5: Generate script.js
Use the template from assets/template-script.js and replace placeholders:
Placeholder replacements:
{{FUNCTION_JS}}→ JavaScript function definition
function f(x) {
return Math.sin(x); // Example
}{{X_MIN}},{{X_MAX}}→ Domain limits{{Y_MIN}},{{Y_MAX}}→ Range limits (or calculate automatically){{FUNCTION_LABEL}}→ Legend label (e.g., "y = sin(x)"){{X_LABEL}}→ X-axis label (default: "x"){{Y_LABEL}}→ Y-axis label (default: "y"){{FILENAME}}→ Export filename (e.g., "sine-function")
Function conversion guide:
Common mathematical expressions to JavaScript:
| Math Notation | JavaScript Code |
|---|---|
| sin(x) | Math.sin(x) |
| cos(x) | Math.cos(x) |
| tan(x) | Math.tan(x) |
| e^x | Math.exp(x) |
| x^2 | Math.pow(x, 2) or x**2 |
| √x | Math.sqrt(x) |
| ln(x) | Math.log(x) |
| log₁₀(x) | Math.log10(x) |
| \ | x\ |
Auto-calculate range if not provided:
// Sample the function to find y range
const samplePoints = 100;
const yValues = [];
for (let i = 0; i <= samplePoints; i++) {
const x = xMin + (xMax - xMin) * i / samplePoints;
yValues.push(f(x));
}
const yMin = Math.min(...yValues) * 1.1; // Add 10% padding
const yMax = Math.max(...yValues) * 1.1;Step 6: Create index.md Documentation
Use the template from assets/template-index.md and customize:
Required sections:
1. YAML frontmatter with title, description, quality_score 2. Level 1 header matching the title 3. Interactive visualization (iframe embed) 4. Fullscreen link button 5. Copy-paste embed code in HTML code block 6. Overview - Purpose and features 7. How to Use - Step-by-step instructions 8. Educational Applications - Subject-specific use cases 9. Customization Guide - How to modify the MicroSim 10. Technical Details - Library version, implementation notes 11. Lesson Plan Suggestions - Learning objectives, activities, assessments 12. References - Links to documentation and resources
Customization for specific functions:
- Trigonometric: Mention periodicity, amplitude, phase shift
- Polynomial: Discuss degree, roots, turning points
- Exponential: Highlight growth/decay, asymptotes
- Logarithmic: Note domain restrictions, inverse relationships
Lesson plan quality: Provide specific, actionable activities with questions that use the slider interactivity. Example:
**Activity 1: Finding Specific Values (10 minutes)**
1. Use the slider to find f(π/2). What value do you observe?
2. At what x-value does f(x) = 0.5? (Approximate using the slider)
3. Challenge: Find all x-values where f(x) = 0 in the visible range.Step 7: Create metadata.json
Use the template from assets/template-metadata.json:
Required Dublin Core fields:
title- Same as MicroSim titledescription- 1-2 sentence summarycreator- Author name or organizationdate- Creation date (YYYY-MM-DD format)subject- Array of keywords (include "mathematics" plus specific topics)type- Always "Interactive Simulation"format- Always "text/html"language- Always "en-US"rights- License (typically "CC BY 4.0")
Optional educational fields:
audience- Target learners (e.g., "High school students", "College undergraduates")educationalLevel- Grade/level (e.g., "Grade 11-12", "Undergraduate")learningResourceType- Always "Interactive Plot"interactivityType- Always "active"typicalLearningTime- ISO 8601 duration (e.g., "PT10M" for 10 minutes)
Subject keyword selection:
Choose 3-5 specific keywords from:
- Mathematics: algebra, geometry, trigonometry, calculus, statistics
- Physics: kinematics, waves, thermodynamics, electromagnetism
- Engineering: signals, control-systems, circuits
- Computer Science: algorithms, numerical-methods, machine-learning
Step 8: Test and Validate
Perform the following checks:
Visual Testing:
1. Open main.html in a browser 2. Verify the plot renders correctly 3. Check that axes are labeled and readable 4. Confirm tooltips appear on hover 5. Test slider interaction - point should move smoothly along curve 6. Resize browser window - verify responsive behavior
Functional Testing:
1. Slider range: Ensure slider covers the full x domain 2. Point accuracy: Verify point position matches slider value 3. Tooltips: Check coordinate precision (3 decimal places) 4. Export: Test PNG export functionality 5. Mobile: Test on small screen sizes (320px width minimum)
Documentation Review:
1. Verify iframe embed works in index.md 2. Check all placeholders are replaced 3. Ensure lesson plan is specific to the function 4. Validate all markdown links work
Metadata Validation:
1. Confirm metadata.json is valid JSON 2. Check all required Dublin Core fields are present 3. Verify subject keywords are relevant
Integration (if part of a textbook project):
1. Update mkdocs.yml navigation if needed 2. Add references to the MicroSim in relevant chapters 3. Link from glossary terms if applicable
Best Practices
Educational Design
1. Tooltip content: Use educational definitions, not just raw coordinates
- Good: "At x=π/2 (1.571), sin(x) reaches its maximum value of 1"
- Avoid: "1.571, 1.000"
2. Slider purpose: Design slider activities that promote exploration
- "Find where f(x) = 0"
- "What happens as x approaches infinity?"
- "Locate the maximum value"
3. Lesson integration: Reference specific textbook concepts
- Link to chapter sections
- Use consistent notation with textbook
- Address common misconceptions
Technical Design
1. Function sampling: Use 500 points minimum for smooth curves 2. Domain selection: Choose domains that show key features
- Trigonometric: Show 1-3 complete periods
- Polynomial: Include all real roots if possible
- Exponential: Show meaningful change (3-5 orders of magnitude)
3. Range calculation: Add 10% padding above/below extrema for visual clarity
4. Responsive design: Test at widths: 320px, 480px, 768px, 1024px, 1200px
5. Performance: Keep total points under 2000 for smooth rendering
Accessibility
1. Color choices: Ensure sufficient contrast (WCAG AA minimum) 2. Font sizes: Minimum 12px, scale up to 16px on desktop 3. Alt text: Provide text descriptions of function behavior 4. Keyboard navigation: Slider should be keyboard-accessible (built-in with HTML range input)
Documentation Quality
1. Mathematical notation: Use proper LaTeX or Unicode symbols
- π not pi, ≈ not ~, ² not ^2 (in markdown text)
2. Code examples: Provide copy-paste ready snippets 3. References: Link to authoritative sources (MDN, Plotly docs, math references)
Common Function Configurations
Trigonometric Functions
// Sine function
function f(x) { return Math.sin(x); }
// Domain: -2π to 2π (-6.28 to 6.28)
// Range: -1.5 to 1.5
// Cosine function
function f(x) { return Math.cos(x); }
// Domain: -2π to 2π
// Range: -1.5 to 1.5
// Tangent function (with discontinuities)
function f(x) { return Math.tan(x); }
// Domain: -π to π (-3.14 to 3.14)
// Range: -10 to 10 (limited for visibility)
// Damped sine wave
function f(x) { return Math.exp(-x/5) * Math.sin(x); }
// Domain: 0 to 20
// Range: Auto-calculatePolynomial Functions
// Quadratic
function f(x) { return x**2; }
// Domain: -5 to 5
// Range: 0 to 25
// Cubic
function f(x) { return x**3 - 3*x; }
// Domain: -3 to 3
// Range: Auto-calculate
// Quartic with multiple turning points
function f(x) { return x**4 - 4*x**2 + 1; }
// Domain: -3 to 3
// Range: Auto-calculateExponential and Logarithmic
// Exponential growth
function f(x) { return Math.exp(x); }
// Domain: -2 to 2
// Range: 0 to 10
// Exponential decay
function f(x) { return Math.exp(-x); }
// Domain: 0 to 5
// Range: 0 to 1.2
// Natural logarithm
function f(x) { return Math.log(x); }
// Domain: 0.1 to 10 (must be positive)
// Range: Auto-calculate
// Gaussian/Normal distribution
function f(x) {
const mu = 0, sigma = 1;
return Math.exp(-0.5 * ((x-mu)/sigma)**2) / (sigma * Math.sqrt(2*Math.PI));
}
// Domain: -4 to 4
// Range: 0 to 0.5Physics and Engineering
// Projectile motion (trajectory)
function f(x) {
const v0 = 20, angle = 45 * Math.PI/180, g = 9.8;
return x * Math.tan(angle) - (g * x**2) / (2 * v0**2 * Math.cos(angle)**2);
}
// Domain: 0 to 40
// Range: Auto-calculate
// Simple harmonic motion
function f(x) {
const A = 1, omega = 2, phi = 0;
return A * Math.cos(omega * x + phi);
}
// Domain: 0 to 10
// Range: -1.5 to 1.5Troubleshooting
Issue: Plot appears blank
Causes:
- Function returns NaN for some x-values
- Domain/range mismatch
- JavaScript function syntax error
Solutions:
- Check browser console for errors
- Verify function definition in
script.js - Test function with sample values:
console.log(f(0), f(1), f(-1)) - Add domain validation:
function f(x) {
if (x <= 0) return NaN; // For log functions
return Math.log(x);
}Issue: Slider doesn't update the point
Causes:
- Incorrect trace index in
Plotly.restyle - Event listener not attached
- Slider ID mismatch
Solutions:
- Verify point trace is index 1 (curve is index 0)
- Check slider ID matches:
document.getElementById('x-slider') - Confirm event listener is after DOM load
- Test with:
console.log('Slider value:', e.target.value)
Issue: Tooltips show incorrect values
Causes:
- Hover template formatting error
- Point coordinates not calculated correctly
Solutions:
- Check
hovertemplatesyntax in trace definition - Verify decimal precision:
%{x:.3f}for 3 decimal places - Test point calculation:
console.log(pointX, pointY)
Issue: Layout too cramped in iframe
Causes:
- Margins/padding too large
- Plot height too tall for container
Solutions:
- Reduce container padding to 2-5px maximum
- Check responsive breakpoints are working
- Test iframe height: Try 500px, 600px, 700px
- Verify
marginin Plotly layout:
margin: { l: 50, r: 20, t: 10, b: 50 }Issue: Function looks jagged/pixelated
Causes:
- Not enough sample points
- Domain too large for point count
Solutions:
- Increase
numPointsin config (try 500-1000) - For discontinuous functions, handle special points
- Add more points near areas of rapid change
References
Plotly.js Documentation
- Plotly.js Official Documentation
- Line Charts Guide
- Scatter Plots
- Hover Text and Formatting
- Layout Configuration
- Responsive Plots
JavaScript Math Functions
Educational Resources
- Desmos Graphing Calculator - Reference for function visualization
- GeoGebra - Interactive mathematics software
- Khan Academy - Functions
MicroSim Standards
- MicroSim Standardization Skill - Quality rubric and requirements
- Dublin Core Metadata - Metadata standards
- Plotly.js CDN - Latest library versions
<!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">
<!-- Plotly.js CDN -->
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
</head>
<body>
<div class="container">
<h1>{{TITLE}}</h1>
<p class="subtitle">{{SUBTITLE}}</p>
<!-- Plot container -->
<div id="plot"></div>
<!-- Interactive controls -->
<div class="controls">
<label for="x-slider">Point Position (x): <span id="x-value">{{INITIAL_X}}</span></label>
<input type="range" id="x-slider" min="{{X_MIN}}" max="{{X_MAX}}" step="{{X_STEP}}" value="{{INITIAL_X}}">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
/*
* Math Function Plotter - Responsive Styling
* Designed for iframe embedding with minimal padding and margins
* Target: <iframe src="main.html" height="500pt" width="100%" scrolling="no"></iframe>
* Optimized for narrow MkDocs pages with navbar (left) and TOC (right)
*/
/* Critical: Remove all body margins for iframe embedding */
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica', 'Arial', sans-serif;
background: aliceblue;
}
/* Container with minimal margins */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 5px;
background: aliceblue;
}
/* Title with minimal spacing */
h1 {
margin-top: 5px;
margin-bottom: 2px;
font-size: 1.5em;
text-align: center;
color: #333;
}
.subtitle {
margin-top: 0;
margin-bottom: 5px;
font-size: 0.9em;
text-align: center;
color: #666;
}
/* Plot container */
#plot {
width: 100%;
height: 400px;
margin-bottom: 10px;
background: white;
border-radius: 4px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
/* Interactive controls */
.controls {
margin: 10px 5px 5px 5px;
padding: 10px;
background: white;
border-radius: 4px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.controls label {
display: block;
margin-bottom: 5px;
font-size: 0.9em;
color: #333;
font-weight: 500;
}
#x-slider {
width: 100%;
margin-top: 5px;
}
#x-value {
font-weight: bold;
color: #007bff;
}
/* Responsive breakpoints */
/* Tablet and small desktop */
@media (max-width: 768px) {
.container {
padding: 3px;
}
h1 {
font-size: 1.2em;
margin-top: 3px;
margin-bottom: 2px;
}
.subtitle {
font-size: 0.8em;
margin-bottom: 3px;
}
#plot {
height: 300px;
margin-bottom: 8px;
}
.controls {
margin: 8px 3px 3px 3px;
padding: 8px;
}
}
/* Mobile devices */
@media (max-width: 480px) {
.container {
padding: 2px;
}
h1 {
font-size: 1em;
margin-top: 2px;
margin-bottom: 1px;
}
.subtitle {
font-size: 0.75em;
margin-bottom: 2px;
}
#plot {
height: 250px;
margin-bottom: 5px;
}
.controls {
margin: 5px 2px 2px 2px;
padding: 5px;
}
.controls label {
font-size: 0.8em;
}
}
/* Print styles */
@media print {
.controls {
display: none;
}
#plot {
height: 500px;
}
}
{{TITLE}}
Interactive Visualization
<iframe src="main.html" width="100%" height="500px"></iframe>
View the {{TITLE}} MicroSim Fullscreen{:target="_blank" .md-button}
Copy-Paste Embed Code
To embed this visualization in your own page, use the following HTML code:
<iframe src="https://{{GITHUB_USERNAME}}.github.io/{{REPO_NAME}}/sims/{{MICROSIM_NAME}}/main.html" width="100%" height="500px"></iframe>Overview
{{OVERVIEW}}
This interactive MicroSim demonstrates the mathematical function {{FUNCTION_LABEL}} using Plotly.js. The visualization includes:
- Smooth function curve - Plotted with {{NUM_POINTS}} points for visual clarity
- Interactive point marker - Red point that moves along the curve
- Hover tooltips - Show precise (x, y) coordinates at any point
- Responsive design - Adapts to different screen sizes
- Slider control - Adjust the x-coordinate to see the corresponding y-value
How to Use
1. View the plot - The blue curve shows the function over the domain [{{X_MIN}}, {{X_MAX}}] 2. Move the slider - Drag the slider below the plot to change the x-coordinate 3. Observe the point - Watch the red point move along the curve 4. Hover for details - Hover over any part of the curve to see exact coordinates 5. Export image - Use the camera icon in the toolbar to save as PNG
Educational Applications
This visualization is ideal for:
- Calculus courses - Understanding function behavior, continuity, limits
- Precalculus - Exploring trigonometric, polynomial, and exponential functions
- Physics - Visualizing wave functions, trajectories, and periodic motion
- Engineering - Analyzing signal processing, control systems
- Self-study - Interactive exploration of mathematical concepts
Customization Guide
To create your own function plot, modify the following parameters in script.js:
Function Definition
function f(x) {
return {{FUNCTION_EXPRESSION}}; // Replace with your function
}Domain and Range
const config = {
xMin: {{X_MIN}}, // Minimum x value
xMax: {{X_MAX}}, // Maximum x value
yMin: {{Y_MIN}}, // Minimum y value (for display)
yMax: {{Y_MAX}}, // Maximum y value (for display)
numPoints: 500, // Number of points (higher = smoother)
initialX: {{INITIAL_X}} // Initial slider position
};Styling Options
Edit style.css to customize:
- Colors - Change background, curve, point colors
- Font sizes - Adjust title, labels, axis text
- Plot height - Modify
#plot { height: 400px; } - Margins - Adjust spacing for different layouts
Technical Details
- Library: Plotly.js v2.27.0
- Function sampling: {{NUM_POINTS}} evenly-spaced points
- Responsive: Uses Plotly's built-in responsive mode
- Interactivity: Range slider with real-time updates
- Tooltips: Automatic hover labels with 3 decimal precision
- Export: Built-in PNG export functionality
Lesson Plan Suggestions
Learning Objectives
Students will be able to:
1. Visualize the relationship between x and y in {{FUNCTION_TYPE}} functions 2. Understand how changing input values affects output values 3. Identify key features ({{KEY_FEATURES}}) 4. Make predictions about function behavior in different domains
Classroom Activities
Activity 1: Function Exploration (15 minutes)
- Have students use the slider to find specific points
- Ask: "What is f({{SAMPLE_X1}})? Use the slider to find out."
- Discuss: "What happens as x approaches {{CRITICAL_POINT}}?"
Activity 2: Pattern Recognition (20 minutes)
- Students observe the function over the entire domain
- Identify: {{PATTERN_QUESTIONS}}
- Compare with other functions in the same family
Activity 3: Prediction Challenge (15 minutes)
- Given x-values outside the visible range, predict y-values
- Verify predictions by adjusting the domain
- Discuss extrapolation vs. interpolation
Assessment Questions
1. What is the approximate value of f({{SAMPLE_X2}})? 2. {{ASSESSMENT_Q1}} 3. {{ASSESSMENT_Q2}} 4. How would the graph change if we {{MODIFICATION}}?
References
- Plotly.js Documentation
- Plotly.js Line Charts
- Plotly.js Hover Text
- Mathematical Functions Reference
- {{ADDITIONAL_REFERENCES}}
{
"title": "{{TITLE}}",
"description": "{{DESCRIPTION}}",
"creator": "{{CREATOR}}",
"date": "{{DATE}}",
"subject": [
"mathematics",
"{{SUBJECT1}}",
"{{SUBJECT2}}",
"visualization",
"interactive learning"
],
"type": "Interactive Simulation",
"format": "text/html",
"language": "en-US",
"rights": "CC BY 4.0",
"audience": "{{AUDIENCE}}",
"educationalLevel": "{{EDUCATIONAL_LEVEL}}",
"learningResourceType": "Interactive Plot",
"interactivityType": "active",
"typicalLearningTime": "PT10M"
}
/**
* Math Function Plotter - Interactive Plotly.js Visualization
* Template placeholders: {{FUNCTION_JS}}, {{X_MIN}}, {{X_MAX}}, {{Y_MIN}}, {{Y_MAX}}, etc.
*/
// Configuration
const config = {
xMin: {{X_MIN}},
xMax: {{X_MAX}},
yMin: {{Y_MIN}},
yMax: {{Y_MAX}},
numPoints: 500, // Number of points for smooth curve
initialX: {{INITIAL_X}}
};
// Mathematical function (replace with actual function)
// Example: function f(x) { return Math.sin(x); }
{{FUNCTION_JS}}
// Generate data points for the function
function generateFunctionData() {
const xValues = [];
const yValues = [];
const step = (config.xMax - config.xMin) / config.numPoints;
for (let i = 0; i <= config.numPoints; i++) {
const x = config.xMin + i * step;
const y = f(x);
xValues.push(x);
yValues.push(y);
}
return { x: xValues, y: yValues };
}
// Create the plot
function createPlot(pointX) {
const functionData = generateFunctionData();
const pointY = f(pointX);
// Function curve trace
const curveTrace = {
x: functionData.x,
y: functionData.y,
type: 'scatter',
mode: 'lines',
name: '{{FUNCTION_LABEL}}',
line: {
color: '#007bff',
width: 2
},
hovertemplate: '<b>x:</b> %{x:.3f}<br><b>y:</b> %{y:.3f}<extra></extra>'
};
// Interactive point trace
const pointTrace = {
x: [pointX],
y: [pointY],
type: 'scatter',
mode: 'markers',
name: 'Point',
marker: {
color: '#dc3545',
size: 10,
symbol: 'circle'
},
hovertemplate: '<b>Point</b><br>x: %{x:.3f}<br>y: %{y:.3f}<extra></extra>'
};
const data = [curveTrace, pointTrace];
// Layout configuration
const layout = {
title: false, // Title is in HTML for better control
xaxis: {
title: {
text: '{{X_LABEL}}',
font: { size: 14 }
},
range: [config.xMin, config.xMax],
showgrid: true,
gridcolor: '#e0e0e0',
zeroline: true,
zerolinecolor: '#333',
zerolinewidth: 1
},
yaxis: {
title: {
text: '{{Y_LABEL}}',
font: { size: 14 }
},
range: [config.yMin, config.yMax],
showgrid: true,
gridcolor: '#e0e0e0',
zeroline: true,
zerolinecolor: '#333',
zerolinewidth: 1
},
margin: {
l: 50,
r: 20,
t: 10,
b: 50
},
paper_bgcolor: 'white',
plot_bgcolor: 'white',
hovermode: 'closest',
showlegend: true,
legend: {
x: 0.02,
y: 0.98,
bgcolor: 'rgba(255,255,255,0.8)',
bordercolor: '#ccc',
borderwidth: 1
}
};
// Plotly configuration
const plotConfig = {
responsive: true,
displayModeBar: true,
displaylogo: false,
modeBarButtonsToRemove: ['lasso2d', 'select2d'],
toImageButtonOptions: {
format: 'png',
filename: '{{FILENAME}}',
height: 600,
width: 800
}
};
Plotly.newPlot('plot', data, layout, plotConfig);
}
// Update point position
function updatePoint(x) {
const y = f(x);
Plotly.restyle('plot', {
x: [[x]],
y: [[y]]
}, [1]); // Update trace index 1 (point trace)
// Update slider display
document.getElementById('x-value').textContent = x.toFixed(3);
}
// Initialize plot
createPlot(config.initialX);
// Slider event listener
document.getElementById('x-slider').addEventListener('input', function(e) {
const x = parseFloat(e.target.value);
updatePoint(x);
});
// Window resize handler for responsiveness
window.addEventListener('resize', function() {
Plotly.Plots.resize('plot');
});