confidence-intervals / web /src /components /TabMultiple.vue
keefereuther's picture
Cursor
Use local tutor URLs in development, deployed URLs in production
d8d79a7
Raw History Blame Contribute Delete
10.1 kB
<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import * as d3 from 'd3'
import { rnorm, mean, sampleSd, qnorm } from '../lib/stats.js'
const tutorUrl = import.meta.env.DEV
? 'http://127.0.0.1:7862'
: 'https://keefereuther-ci-tab2.hf.space'
const normalSD = ref(1)
const sampleSize = ref(50)
const numSamples = ref(100)
const confidenceLevel = ref(95)
const manyRows = ref(null)
const plotEl = ref(null)
let plotResizeObserver = null
/** Right margin reserves space for color legend beside panel. */
const margin = { top: 52, right: 180, bottom: 52, left: 78 }
function measurePlotSize() {
const el = plotEl.value
if (!el) return { W: 920, H: 480 }
const w = el.getBoundingClientRect().width || el.clientWidth
const W = Math.max(280, Math.floor(w))
const H = Math.max(360, Math.round((W * 480) / 920))
return { W, H }
}
const statsBlock = computed(() => {
const rows = manyRows.value
if (!rows || !rows.length) return ''
const m = rows.map((r) => r.sampleMean)
const grand = mean(m)
const n = m.length
let s = 0
for (const v of m) s += (v - grand) ** 2
const sdMeans = n > 1 ? Math.sqrt(s / (n - 1)) : 0
return `Number of Samples: ${n}\nMean of Sample Means: ${grand.toFixed(3)}\nSD of Sample Means: ${sdMeans.toFixed(3)}`
})
function generateSamples() {
const rows = []
for (let k = 0; k < numSamples.value; k++) {
const x = rnorm(sampleSize.value, 0, normalSD.value)
rows.push({
sampleMean: mean(x),
sampleSD: sampleSd(x),
jitter: (Math.random() * 2 - 1) * 0.2,
})
}
manyRows.value = rows
}
function renderPlot() {
const root = plotEl.value
if (!root) return
d3.select(root).selectAll('*').remove()
const { W, H } = measurePlotSize()
const innerW = W - margin.left - margin.right
const innerH = H - margin.top - margin.bottom
const svg = d3
.select(root)
.append('svg')
.attr('viewBox', `0 0 ${W} ${H}`)
.attr('width', '100%')
.attr('preserveAspectRatio', 'xMinYMid meet')
.style('display', 'block')
.style('max-width', '100%')
.style('height', 'auto')
.style('vertical-align', 'top')
.style('font-family', 'system-ui, sans-serif')
const rows = manyRows.value
if (!rows || !rows.length) {
svg
.append('text')
.attr('x', W / 2)
.attr('y', H / 2)
.attr('text-anchor', 'middle')
.attr('fill', '#64748b')
.attr('font-size', 16)
.text('Click “Generate Samples” to simulate.')
return
}
const means = rows.map((r) => r.sampleMean)
const yLo = Math.min(...means) - 0.05
const yHi = Math.max(...means) + 0.05
const jitterWidth = 0.2
const xCenter = 1
const xLo = xCenter - jitterWidth
const xHi = xCenter + jitterWidth
const x = d3.scaleLinear().domain([xLo, xHi]).range([0, innerW])
const y = d3.scaleLinear().domain([yLo, yHi]).range([innerH, 0])
const nEach = sampleSize.value
const alpha = 1 - confidenceLevel.value / 100
const zCrit = qnorm(1 - alpha / 2)
const decorated = rows.map((r) => {
const se = r.sampleSD / Math.sqrt(nEach)
const ciLower = r.sampleMean - zCrit * se
const ciUpper = r.sampleMean + zCrit * se
const excludesZero = ciLower > 0 || ciUpper < 0
return { ...r, xData: xCenter + r.jitter, excludesZero }
})
const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`)
/** `theme_minimal`: subtle horizontal grid from y-axis ticks */
const yAxis = d3.axisLeft(y).ticks(8).tickSize(-innerW)
const yG = g.append('g').call(yAxis)
yG.selectAll('.tick line').attr('stroke', '#e5e7eb')
yG.selectAll('.tick text').attr('fill', '#374151').attr('font-size', 14)
yG.select('.domain').remove()
/** Bottom spine only (x labels suppressed like ggplot axis.text.x blank) */
g.append('line')
.attr('x1', 0)
.attr('x2', innerW)
.attr('y1', innerH)
.attr('y2', innerH)
.attr('stroke', '#374151')
.attr('stroke-width', 1)
/** `geom_hline(yintercept=0, ...)` */
g.append('line')
.attr('x1', 0)
.attr('x2', innerW)
.attr('y1', y(0))
.attr('y2', y(0))
.attr('stroke', '#ff0000')
.attr('stroke-width', 1.2)
.attr('stroke-dasharray', '6 4')
/** `geom_jitter(width=0.2, size=4, alpha=0.7)` — size≈4 pt → ~4.5px radius */
g.selectAll('circle.pt')
.data(decorated)
.join('circle')
.attr('class', 'pt')
.attr('cx', (d) => x(d.xData))
.attr('cy', (d) => y(d.sampleMean))
.attr('r', 4.5)
.attr('fill', (d) => (d.excludesZero ? '#ff0000' : '#0000ff'))
.attr('fill-opacity', 0.7)
svg
.append('text')
.attr('x', margin.left)
.attr('y', 32)
.attr('font-size', 18)
.attr('font-weight', 600)
.attr('fill', '#0f172a')
.text('Beeswarm Dot Plot of Sample Means')
svg
.append('text')
.attr('transform', 'rotate(-90)')
.attr('x', -(margin.top + innerH / 2))
.attr('y', 22)
.attr('text-anchor', 'middle')
.attr('font-size', 14)
.attr('fill', '#0f172a')
.text('Sample Means')
/** Legend: title + swatches — placed in margin to avoid crowding points */
const legX = margin.left + innerW + 16
let legY = margin.top + 24
svg
.append('text')
.attr('x', legX)
.attr('y', legY)
.attr('font-size', 12)
.attr('font-weight', 600)
.attr('fill', '#0f172a')
.text(`${confidenceLevel.value}% CI excludes 0?`)
legY += 22
const legItems = [
{ label: 'Includes 0', fill: '#0000ff' },
{ label: 'Excludes 0', fill: '#ff0000' },
]
for (const item of legItems) {
svg.append('rect').attr('x', legX).attr('y', legY - 10).attr('width', 14).attr('height', 14).attr('fill', item.fill).attr('opacity', 0.85)
svg
.append('text')
.attr('x', legX + 20)
.attr('y', legY + 1)
.attr('font-size', 13)
.attr('fill', '#0f172a')
.text(item.label)
legY += 22
}
}
watch([manyRows, confidenceLevel, sampleSize, normalSD, numSamples], () => nextTick().then(renderPlot), {
deep: true,
})
onMounted(() => {
nextTick(() => {
plotResizeObserver = new ResizeObserver(() => nextTick(renderPlot))
if (plotEl.value) plotResizeObserver.observe(plotEl.value)
renderPlot()
})
})
onUnmounted(() => {
plotResizeObserver?.disconnect()
plotResizeObserver = null
})
</script>
<template>
<div class="flex flex-col gap-6 lg:flex-row">
<aside class="w-full shrink-0 space-y-4 rounded-lg border border-slate-200 bg-white p-4 shadow-sm lg:w-72">
<h3 class="text-lg font-semibold text-slate-800">The Population</h3>
<div>
<label class="mb-1 block text-sm font-medium text-slate-600">Population SD:</label>
<input
v-model.number="normalSD"
type="number"
min="0.1"
step="0.1"
class="w-full rounded border border-slate-300 px-3 py-2 shadow-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
/>
</div>
<hr class="border-slate-200" />
<h3 class="text-lg font-semibold text-slate-800">Your Multiple Samples</h3>
<div>
<label class="mb-1 block text-sm font-medium text-slate-600">Sample Size (each):</label>
<input
v-model.number="sampleSize"
type="number"
min="1"
class="w-full rounded border border-slate-300 px-3 py-2 shadow-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
/>
</div>
<div>
<label class="mb-1 block text-sm font-medium text-slate-600">Number of Random Samples:</label>
<input
v-model.number="numSamples"
type="number"
min="1"
class="w-full rounded border border-slate-300 px-3 py-2 shadow-sm focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
/>
</div>
<div>
<label class="mb-1 block text-sm font-medium text-slate-600">Confidence Level (%)</label>
<input
v-model.number="confidenceLevel"
type="range"
min="50"
max="99"
step="1"
class="w-full accent-sky-600"
/>
<div class="text-sm text-slate-600">{{ confidenceLevel }}%</div>
</div>
<button
type="button"
class="w-full rounded-md bg-sky-700 px-4 py-2 text-white shadow hover:bg-sky-800 focus:outline-none focus:ring-2 focus:ring-sky-500 focus:ring-offset-2"
@click="generateSamples"
>
Generate Samples
</button>
<hr class="border-slate-200" />
<h4 class="font-semibold text-slate-800">Guiding Questions:</h4>
<p class="text-sm text-slate-700">
1. If you run 100 simulated experiments, how many experiments (red dots) failed to contain the true population
mean within their 95% CI?
</p>
<p class="text-sm text-slate-700">
2. Why is it sometimes not exactly 5 red dots (samples means with 95% CIs that don't include the population mean?)
</p>
<p class="text-sm text-slate-700">3. How does changing standard deviation and sample size affect the output?</p>
<p class="text-sm text-slate-700">4. What is the relationship between a confidence interval and standard error?</p>
</aside>
<div class="min-w-0 flex-1 space-y-4">
<div class="overflow-x-auto rounded-lg border border-slate-200 bg-white p-2 shadow-sm">
<div ref="plotEl" class="ci-plot-host min-h-[320px] w-full min-w-0" />
</div>
<pre
v-if="manyRows && manyRows.length"
class="overflow-x-auto whitespace-pre-wrap rounded-lg border border-slate-200 bg-slate-50 p-4 font-mono text-sm text-slate-800"
>{{ statsBlock }}</pre>
<hr class="border-slate-200" />
<h4 class="text-lg font-semibold text-slate-800">AI Tutor</h4>
<p class="text-sm text-slate-600">Have a conversation with the chatbot about this simulation!</p>
<iframe
:src="tutorUrl"
class="h-[700px] w-full rounded-lg border border-slate-200"
title="AI Tutor tab 2"
style="border: none"
/>
</div>
</div>
</template>