Skip to main content

ROC Curve

What is a ROC curve?​

A ROC curve (receiver operating characteristic curve) is a chart of how well a binary classifier separates two classes. It plots the true positive rate against the false positive rate at every decision threshold. The area under it, the AUC, sums the curve up as one number from 0 to 1, where 0.5 is chance and 1 is perfect.

Three charts of a simulated classifier in a dark navy theme: overlapping score histograms of negative and positive cases with a dashed threshold line, a ROC curve bowing towards the top-left corner above a dashed diagonal, with its area under the curve in the legend, a precision-recall curve that falls from the top-left towards a low dashed baseline, and the confusion matrix at the threshold

Score histograms, confusion matrix, ROC curve and precision-recall curve for a simulated classifier with 5% positives (sample data). Try the interactive version.

Key takeaways
  • Each point on a ROC curve is one threshold, turned into a confusion matrix and then into two rates: true positives caught and false alarms raised.
  • AUC is the probability that a randomly chosen positive gets a higher score than a randomly chosen negative.
  • The diagonal is a model with no skill. A curve below it has its scores the wrong way round.
  • With rare positives, the precision-recall curve and average precision show problems the ROC curve hides.
  • AUC judges the ranking. A deployed model also needs a threshold, chosen from the costs of each kind of error.

Classifiers, scores and the decision threshold​

A binary classifier sorts cases into two classes: spam or not spam, fraud or genuine, disease present or absent. By convention the class you are looking for is the positive class, whatever it means in real life.

Most classifiers don't output a yes or a no. They output a score, often a probability between 0 and 1, and a threshold turns it into a decision: a score at or above the threshold means "positive". Raise the threshold and the model flags fewer cases, missing more real positives but raising fewer false alarms. Lower it and the reverse happens.

A single accuracy figure describes the model at one threshold only. A ROC curve shows all of them at once, so you can judge the model's ranking separately from where you set the cut-off.

The confusion matrix​

At any threshold, every case falls into one of four boxes. The table that counts them is the confusion matrix:

Predicted positivePredicted negative
Actually positiveTrue positive (TP)False negative (FN), a miss
Actually negativeFalse positive (FP), a false alarmTrue negative (TN)

Take ten test cases, four positive and six negative, with these model scores (the same cases are used throughout this page):

Case12345678910
Score0.950.800.700.600.500.400.350.250.150.10
Actual class++−+−−+−−−

At a threshold of 0.5, cases 1 to 5 are predicted positive. Three of them are real positives and two are not, and one positive (case 7) is missed:

Predicted +Predicted −
Actual +TP = 3FN = 1
Actual −FP = 2TN = 4

Sensitivity, specificity, precision and recall​

The ROC and precision-recall curves are built from four ratios of those counts:

RateAlso calledFormulaAt threshold 0.5
True positive rate (TPR)Recall, sensitivity, hit rateTPTP+FN\dfrac{TP}{TP + FN}3 / 4 = 0.75
False positive rate (FPR)Fall-out, 1 − specificityFPFP+TN\dfrac{FP}{FP + TN}2 / 6 = 0.33
SpecificityTrue negative rateTNTN+FP\dfrac{TN}{TN + FP}4 / 6 = 0.67
PrecisionPositive predictive valueTPTP+FP\dfrac{TP}{TP + FP}3 / 5 = 0.60

The ROC curve plots TPR against FPR. The precision-recall curve plots precision against recall (which is TPR again). Accuracy, (TP + TN) / total, is 0.70 here.

Precision vs recall​

Recall answers "of all the real positives, how many did we catch?". Precision answers "of everything we flagged, how much was real?". Recall divides by the actual positives; precision divides by the predicted positives. A spam filter that lets some spam through has low recall; one that sends real mail to the spam folder has low precision.

Lowering the threshold usually raises recall and lowers precision. The F1 score combines the two into one number.

F1 score​

The F1 score is the harmonic mean of precision PP and recall RR:

F1=2PRP+R=2 TP2 TP+FP+FNF_1 = \frac{2PR}{P + R} = \frac{2\,TP}{2\,TP + FP + FN}

At a threshold of 0.5 the example has P=0.60P = 0.60 and R=0.75R = 0.75, so F1=2×0.60×0.75/1.35=0.67F_1 = 2 \times 0.60 \times 0.75 / 1.35 = 0.67. The harmonic mean punishes imbalance between the two: a model with precision 1.0 and recall 0.01 has an arithmetic mean of 0.505 but an F1 of only 0.02.

F1 depends on the threshold. For the ten cases:

ThresholdPredicted positiveTPFPFNPrecisionRecallF1
0.70cases 1–32120.670.500.57
0.60cases 1–43110.750.750.75
0.50cases 1–53210.600.750.67
0.35cases 1–74300.571.000.73

The best F1 here is at 0.60. Two things to know when you use it:

  • F1 ignores true negatives, so it says nothing about how well the model rejects negatives. That suits rare-positive problems, and it is why the precision-recall curve, not the ROC curve, is its natural companion.
  • When recall matters more than precision (or the other way round), use the FβF_\beta score, (1+β2)PR/(β2P+R)(1 + \beta^2) PR / (\beta^2 P + R): β=2\beta = 2 weights recall twice as heavily, β=0.5\beta = 0.5 favours precision.

How a ROC curve is built: a worked example​

To draw the curve, sweep the threshold down through every score and compute TPR and FPR at each step. Each case you pass moves the curve up by 1/P if it is positive (here 1/4) or right by 1/N if it is negative (1/6):

Two score distributions, negatives on the left and positives on the right, overlapping in the middle, with a vertical threshold line. Right of the line, positives are shaded as true positives and negatives as false positives; left of the line, positives are false negatives and negatives true negatives. An arrow shows that moving the threshold left raises both the true and false positive rates

Threshold (score ≥)TPFPTPRFPRPrecisionYouden's J
Above 0.950000–0
0.95100.2501.000.25
0.80200.5001.000.50
0.70210.500.170.670.33
0.60310.750.170.750.58
0.50320.750.330.600.42
0.40330.750.500.500.25
0.35431.000.500.570.50
0.25441.000.670.500.33
0.15451.000.830.440.17
0.10461.001.000.400

Plot the (FPR, TPR) pairs and join them: the curve starts at (0, 0), where nothing is flagged, and ends at (1, 1), where everything is. With few cases it is a staircase. With thousands it looks smooth, as in the demo. Two cases with the same score are passed together, which gives a diagonal step.

The area under this staircase is 0.833. You can get it two ways: by adding up the trapezoids under the points, or by counting pairs, as the next sections show.

How to read a ROC curve​

An annotated ROC curve: the false positive rate from 0 to 1 along the bottom and the true positive rate from 0 to 1 up the side. Callout 1 marks the dashed diagonal of a model with no skill, callout 2 the top-left corner of a perfect model, callout 3 a curve bowing towards that corner with the area under it shaded and labelled AUC 0.90, callout 4 one point on the curve marked as the operating point for a chosen threshold, with its vertical distance to the diagonal labelled Youden's J, and callout 5 a lower curve labelled as a weaker model

  1. The axes. The false positive rate runs left to right and the true positive rate bottom to top, both from 0 to 1. The threshold itself is not on an axis: it falls as you move along the curve from bottom left to top right.
  2. The diagonal. A model that guesses at random flags positives and negatives at the same rate, so TPR equals FPR at every threshold. It is the baseline to beat.
  3. The top-left corner. TPR 1 and FPR 0 is a perfect classifier: every positive caught, no false alarms. The closer the curve bows towards it, the better the model ranks.
  4. The steepness at the start. A curve that climbs straight up from the origin means the highest scores are almost all real positives. That matters when you can only act on a few cases, such as the top 1% of alerts.
  5. A point on the curve. Each point is one threshold, with one confusion matrix. Reading off a point gives you the trade-off you would get if you deployed the model there.
  6. Two curves. If one curve is above the other everywhere, that model is better at every threshold. If they cross, each is better in a different region.

What AUC means​

The area under the ROC curve (AUC, or ROC AUC) has a direct meaning: it is the probability that the model gives a randomly chosen positive a higher score than a randomly chosen negative, with ties counting half. Bamber showed in 1975 that this equals the Wilcoxon–Mann–Whitney statistic, and Hanley and McNeil made it the standard way to read AUC.

AUC=P(s+>s−)+12P(s+=s−)\text{AUC} = P(s_{+} > s_{-}) + \tfrac{1}{2}P(s_{+} = s_{-})

In the worked example there are 4 × 6 = 24 positive–negative pairs. The positive scored 0.95 beats all 6 negatives, 0.80 beats 6, 0.60 beats 5 (not 0.70) and 0.35 beats 3. That is 20 of 24 pairs, or 0.833, the same as the area under the staircase.

AUCWhat it means
1.0Every positive scores above every negative
0.9 or moreOutstanding discrimination (Hosmer and Lemeshow's rule of thumb)
0.8 to 0.9Excellent
0.7 to 0.8Acceptable
0.5No better than chance: the diagonal
Below 0.5Worse than chance: the scores are probably reversed

Because AUC only depends on the order of the scores, it doesn't change if you rescale them, and it says nothing about whether a score of 0.8 really means an 80% chance. In credit scoring, the same quantity is often reported as the Gini coefficient, 2 × AUC − 1.

The precision-recall curve​

A precision-recall curve (PR curve) plots precision against recall as the threshold sweeps from high to low. It starts at the top left, where the few cases flagged are mostly correct, and falls as the threshold drops and more negatives get through.

Its no-skill baseline is a flat line: a model that guesses has a precision equal to the share of positives in the data, the prevalence, at every recall. With 5% positives, the no-skill line is flat at 0.05, and that is the level the model must beat.

The usual summary is average precision (AP), the precision at each threshold weighted by how much recall rose since the previous one:

AP=∑n(Rn−Rn−1) Pn\text{AP} = \sum_n (R_n - R_{n-1})\, P_n

For the ten cases, recall rises by 0.25 at the four positives, where precision is 1, 1, 0.75 and 0.57, so AP = 0.25 × (1 + 1 + 0.75 + 0.571) = 0.830. AP is close to the area under the PR curve, but it avoids drawing straight lines between PR points, which overstates the area: Davis and Goadrich showed that interpolation in PR space is not linear.

Why imbalance changes the picture​

Suppose 1% of 100,000 transactions are fraud. A model that catches 900 of the 1,000 frauds (TPR 0.90) and flags 2% of the 99,000 genuine ones (FPR 0.02) looks excellent on a ROC curve. But 2% of 99,000 is 1,980 false alarms, so only 900 of 2,880 flagged cases are fraud: a precision of 0.31. The FPR divides by the huge number of negatives, which hides the false alarms; precision doesn't. Saito and Rehmsmeier found that PR plots describe performance on imbalanced data more informatively than ROC plots.

ROC curve vs precision-recall curve​

The two curves use the same confusion matrices and rank models the same way when one dominates the other (Davis and Goadrich proved a curve dominates in ROC space exactly when it dominates in PR space). They differ in what they make visible.

Chart or metricPlots or measuresBaseline (no skill)Best forWatch out for
ROC curve and AUCTPR against FPRDiagonal, AUC 0.5Balanced classes; comparing rankings; when both errors matterLooks good even when most alarms are false, if positives are rare
Precision-recall curve and APPrecision against recallFlat line at the prevalenceRare positives: fraud, screening, search, defect detectionAP isn't comparable between datasets with different prevalence
Accuracy(TP + TN) / total at one thresholdShare of the majority classQuick check on balanced dataWith 1% positives, "always negative" scores 99%
F1 scoreHarmonic mean of precision and recall at one thresholdDepends on prevalenceOne operating point when positives are rareIgnores true negatives; depends on the threshold
Detection error tradeoff (DET) curveMiss rate against FPR on normal-deviate scalesStraight lineComparing very good systems, such as speaker or biometric verificationLess familiar to most readers

Reporting both is often the clearest choice: ROC AUC for the ranking, and the PR curve or AP for what the people acting on the alerts will see.

Choosing a threshold​

The curve shows the options; a deployed model needs one point on it. Common ways to choose:

  • Youden's J, J=TPR−FPRJ = \text{TPR} - \text{FPR} (sensitivity + specificity − 1), is the vertical distance from the diagonal. Its maximum treats a miss and a false alarm as equally bad. In the worked example it peaks at 0.58 at a threshold of 0.60.
  • Cost-based. If a false positive costs CFPC_{FP} and a false negative costs CFNC_{FN}, and there are P positives and N negatives, the cheapest point is where the curve's slope equals NP⋅CFPCFN\frac{N}{P} \cdot \frac{C_{FP}}{C_{FN}}. When misses are expensive (a missed cancer), the slope is shallow and the point sits high and to the right; when false alarms are expensive, it sits low and to the left.
  • A fixed requirement. Many uses set one rate and maximise the other: at least 95% sensitivity for a screening test, or a false positive rate below 1 in 1,000 for an alarm.
  • Capacity. If a team can review 200 alerts a day, the threshold is the score of the 200th case.

The best threshold depends on the prevalence where the model is deployed, not only on the test set. A threshold tuned on balanced test data will flag too many cases in a population where positives are rare.

Comparing models with ROC curves​

Draw the curves on the same axes before comparing AUCs. When one curve is above the other everywhere, the choice is easy. When they cross, the AUCs can be equal while the models behave very differently at the thresholds you would use. In the live demo, model B has almost the same AUC as model A (0.885 against 0.890 at the default settings), but its positives are more spread out, so its highest scores are purer: at 5% positives its average precision is 0.72 against A's 0.42.

Tools for a fairer comparison:

  • Partial AUC: the area over only the FPR range you would use, for example 0 to 0.1.
  • A significance test. Two AUCs measured on the same test cases are correlated; DeLong's test accounts for that. A difference of 0.01 on a few hundred cases is often noise.
  • Confidence intervals by bootstrapping: resample the test cases, recompute the curve and AUC many times, and draw the band.

ROC curves and calibration​

A ROC curve measures discrimination, how well the model ranks cases. It says nothing about calibration, whether the scores mean what they say: among cases scored 0.8, are 80% positive? A model can have an AUC of 0.95 and still be badly calibrated, because squeezing or stretching the scores doesn't change their order. If you use the scores as probabilities, to estimate risk or expected cost, check a calibration (reliability) curve as well, and recalibrate if needed, for example with Platt scaling or isotonic regression.

Where ROC curves are used​

ROC curves are used wherever a yes/no decision trades missed cases against false alarms.

  • Radar and signal detection. ROC analysis grew out of radar signal detection in the 1940s and 1950s; Peterson, Birdsall and Fox set out its theory in 1954. Psychology adopted it as signal detection theory.
  • Medical diagnostic tests. ROC curves compare tests and set cut-offs, for example the level of a blood marker above which a test counts as positive, trading sensitivity against specificity. This page explains how the curves are drawn and read; it is not clinical guidance. See how SciChart is used for diagnostics and life sciences software.
  • Machine learning. ROC AUC and average precision are standard ways to evaluate classifiers, from spam filters to image classifiers.
  • Credit scoring and fraud detection. Lenders report AUC or the Gini coefficient for scorecards; fraud teams lean on precision-recall because fraud is rare.
  • Industrial inspection. Defect detectors and alarm systems trade missed faults against false alarms that waste engineers' time.

Common ROC curve mistakes​

Most ROC mistakes come from trusting AUC alone: on rare positives, at a deployed threshold, or on data that leaked into training.

  • Trusting AUC when positives are rare. In the live demo, with a class separation of 2.3 and 1% positives, the AUC is 0.95, yet the average precision is 0.42 and at the best Youden threshold only about 1 flagged case in 20 is a real positive. Moving the positive rate from 5% to 1% at the default separation barely changes the AUC (0.89 to 0.91) but halves the AP (0.42 to 0.23). Check the precision-recall curve, or the precision at the threshold you will deploy.
  • Quoting a threshold-free metric for a deployed model. AUC averages over every threshold, including ones you would never use. Report the sensitivity, specificity and precision at the chosen threshold as well.
  • Evaluating on leaked data. Scaling, feature selection or threshold tuning done on the whole dataset before splitting, duplicates of the same patient or customer in training and test sets, or features recorded after the outcome, all inflate the curve. Fit every step on training data only.
  • Choosing the threshold on the test set. Tune it on a validation set, then report the result on held-out data.
  • Comparing AUCs without the curves. Equal AUCs can hide curves that cross, and a small difference may not be significant.
  • Drawing a smooth curve from a handful of cases. With 20 positives, each positive moves the curve up by 0.05. Show the steps, and give a confidence interval.
  • Comparing AP across datasets. The PR baseline is the prevalence, so an AP of 0.4 is strong at 1% positives and weak at 30%.
  • Forgetting which class is positive. Swapping the labels, or using the score for the wrong class, mirrors the curve below the diagonal.

How to plot a ROC curve in JavaScript, React or Angular​

The demo simulates 5,000 test cases scored by two models, builds both curves in the browser, and recomputes the confusion matrix as you drag the threshold.

Drag the Threshold slider, or the dashed line on the histogram, to move the marker along both curves and update the confusion matrix and its rates. Class separation sets how far apart the two score distributions are, and Positive rate sets the share of positives, from 50% to 1%. Best Youden's J jumps to the threshold that maximises TPR − FPR, and Compare model B adds a second model with almost the same AUC but a different shape. Histogram switches between the share of each class and raw counts, which shows how small the positive class becomes at 1%. Hover for values, zoom with the mouse wheel, drag to pan and double-click to see everything again.

Here is the code for this chart. The ROC, AUC, precision-recall and confusion-matrix maths are plain JavaScript; SciChart.js draws the histograms as step mountain series, the curves as line series and the operating points as scatter markers.

// Score histograms, ROC curve and precision-recall curve for a binary classifier, charted with SciChart.js
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
EAxisAlignment,
FastLineRenderableSeries,
FastMountainRenderableSeries,
XyScatterRenderableSeries,
EllipsePointMarker,
XyDataSeries,
VerticalLineAnnotation,
ELabelPlacement,
LegendModifier,
ELegendPlacement,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- ROC and precision-recall maths (plain JavaScript, no library needed) ---

// Sweep the threshold from the highest score to the lowest. Each step admits one more case as "predicted
// positive"; tied scores are admitted together. Returns the ROC and PR points, the AUC (trapezoids, which
// equals the share of positive-negative pairs ranked correctly) and the average precision (AP).
function evaluate(scores, labels) {
const order = scores.map((_, i) => i).sort((a, b) => scores[b] - scores[a]);
const positives = labels.reduce((sum, y) => sum + y, 0);
const negatives = labels.length - positives;
const roc = { fpr: [0], tpr: [0], threshold: [Infinity] };
const pr = { recall: [0], precision: [1] };
let tp = 0;
let fp = 0;
let auc = 0;
let ap = 0;
for (let k = 0; k < order.length; k++) {
const i = order[k];
if (labels[i] === 1) tp++;
else fp++;
if (k + 1 < order.length && scores[order[k + 1]] === scores[i]) continue; // wait for the end of a tie
const fpr = fp / negatives;
const tpr = tp / positives;
const last = roc.fpr.length - 1;
auc += ((fpr - roc.fpr[last]) * (tpr + roc.tpr[last])) / 2;
const precision = tp / (tp + fp);
ap += (tpr - pr.recall[pr.recall.length - 1]) * precision;
roc.fpr.push(fpr);
roc.tpr.push(tpr);
roc.threshold.push(scores[i]);
pr.recall.push(tpr);
pr.precision.push(precision);
}
return { roc, pr, auc, ap, positives, negatives };
}

// The confusion matrix at one threshold: a case is predicted positive when its score is at or above it
function confusionMatrix(scores, labels, threshold) {
let tp = 0;
let fp = 0;
let tn = 0;
let fn = 0;
for (let i = 0; i < scores.length; i++) {
const predicted = scores[i] >= threshold;
if (labels[i] === 1) predicted ? tp++ : fn++;
else predicted ? fp++ : tn++;
}
const ratio = (a, b) => (b > 0 ? a / b : NaN);
const tpr = ratio(tp, tp + fn); // recall, sensitivity
const fpr = ratio(fp, fp + tn); // 1 - specificity
return {
tp,
fp,
tn,
fn,
tpr,
fpr,
specificity: ratio(tn, tn + fp),
precision: ratio(tp, tp + fp),
accuracy: (tp + tn) / scores.length,
f1: ratio(2 * tp, 2 * tp + fp + fn),
youdenJ: tpr - fpr
};
}

// Counts per score bin for one class, as a step outline from 0 to 1
function histogram(scores, labels, label, asShare) {
const counts = new Array(BINS).fill(0);
let total = 0;
for (let i = 0; i < scores.length; i++) {
if (labels[i] !== label) continue;
counts[Math.min(BINS - 1, Math.floor(scores[i] * BINS))]++;
total++;
}
const x = [];
const y = [];
for (let b = 0; b <= BINS; b++) {
x.push(b / BINS);
const value = counts[Math.min(b, BINS - 1)]; // repeat the last bin so the step closes at 1
y.push(asShare ? (100 * value) / Math.max(total, 1) : value);
}
return { x, y };
}

// --- The charts ---
const theme = new SciChartJsNavyTheme();
const COLOUR_NEG = "#50C7E0";
const COLOUR_POS = "#F48420";
const COLOUR_A = "#3BD16F";
const COLOUR_B = "#E36FD4";
const zoom = () => [new MouseWheelZoomModifier(), new ZoomPanModifier(), new ZoomExtentsModifier()];

// 1. Score histograms of the two classes, with a draggable threshold line
const hist = await SciChartSurface.create(ui.histogramDiv, { theme });
hist.sciChartSurface.xAxes.add(
new NumericAxis(hist.wasmContext, { axisTitle: "Model A score", visibleRange: new NumberRange(0, 1), labelPrecision: 1 })
);
const histYAxis = new NumericAxis(hist.wasmContext, {
axisTitle: "% of class",
axisAlignment: EAxisAlignment.Left,
autoRange: EAutoRange.Always,
growBy: new NumberRange(0, 0.3), // headroom for the legend
labelPrecision: 0
});
hist.sciChartSurface.yAxes.add(histYAxis);
const negativeHist = new XyDataSeries(hist.wasmContext, { dataSeriesName: "Negatives", dataIsSortedInX: true });
const positiveHist = new XyDataSeries(hist.wasmContext, { dataSeriesName: "Positives", dataIsSortedInX: true });
for (const { dataSeries, colour } of [{ dataSeries: negativeHist, colour: COLOUR_NEG }, { dataSeries: positiveHist, colour: COLOUR_POS }]) {
hist.sciChartSurface.renderableSeries.add(
new FastMountainRenderableSeries(hist.wasmContext, {
dataSeries,
isDigitalLine: true,
fill: colour + "55",
stroke: colour,
strokeThickness: 2
})
);
}
const thresholdLine = new VerticalLineAnnotation({
x1: 0.5,
stroke: "#FFFFFF",
strokeThickness: 2,
strokeDashArray: [6, 4],
isEditable: true, // drag the line to move the threshold
showLabel: true,
labelPlacement: ELabelPlacement.Axis,
axisLabelFill: "#FFFFFF",
axisLabelStroke: "#22365B"
});
hist.sciChartSurface.annotations.add(thresholdLine);
hist.sciChartSurface.chartModifiers.add(new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopRight }));

// 2 and 3. The ROC curve (TPR against FPR) and the precision-recall curve, each with a no-skill line,
// one curve per model and a marker for the current threshold
async function curveChart(div, xTitle, yTitle) {
const chart = await SciChartSurface.create(div, { theme });
const { sciChartSurface, wasmContext } = chart;
sciChartSurface.xAxes.add(
new NumericAxis(wasmContext, { axisTitle: xTitle, visibleRange: new NumberRange(0, 1), growBy: new NumberRange(0.02, 0.02), labelPrecision: 1 })
);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, { axisTitle: yTitle, axisAlignment: EAxisAlignment.Left, visibleRange: new NumberRange(0, 1), growBy: new NumberRange(0.02, 0.02), labelPrecision: 1 })
);
const line = (name, colour, extra = {}) => {
const dataSeries = new XyDataSeries(wasmContext, { dataSeriesName: name });
const series = new FastLineRenderableSeries(wasmContext, { dataSeries, stroke: colour, strokeThickness: 2.5, ...extra });
sciChartSurface.renderableSeries.add(series);
return series;
};
const noSkill = line("No skill", "#C8D3E8", { strokeThickness: 1.5, strokeDashArray: [6, 4] });
const curveA = line("Model A", COLOUR_A);
const curveB = line("Model B", COLOUR_B);
const marker = (colour) => {
const series = new XyScatterRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { dataSeriesName: "At threshold" }),
pointMarker: new EllipsePointMarker(wasmContext, { width: 14, height: 14, fill: colour, stroke: "#FFFFFF", strokeThickness: 2 })
});
sciChartSurface.renderableSeries.add(series);
return series;
};
const pointA = marker(COLOUR_A);
const pointB = marker(COLOUR_B);
// The legend and the tooltip skip the markers; the curves carry the names
const legend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.BottomRight });
const cursor = new CursorModifier({ showTooltip: true, showAxisLabels: false });
sciChartSurface.chartModifiers.add(legend, cursor, ...zoom());
for (const series of [pointA, pointB]) {
legend.includeSeries(series, false);
cursor.includeSeries(series, false);
}
return { noSkill, curveA, curveB, pointA, pointB, legend };
}
const roc = await curveChart(ui.rocDiv, "False positive rate (1 − specificity)", "True positive rate");
const pr = await curveChart(ui.prDiv, "Recall (true positive rate)", "Precision");

const setXy = (series, x, y) => {
series.dataSeries.clear();
series.dataSeries.appendRange(x, y);
};

// --- The controls ---
let data;
let resultA;
let resultB;
let threshold = 0.5;

// Simulate and evaluate both models: runs when the separation or positive rate changes
function onDataChanged() {
const separation = Number(ui.separationInput.value);
ui.separationOutput.textContent = `d = ${separation.toFixed(1)}`;
data = simulateTestSet(separation, Number(ui.rateSelect.value));
resultA = evaluate(data.scoresA, data.labels);
resultB = evaluate(data.scoresB, data.labels);
const asShare = ui.histogramSelect.value === "share";
histYAxis.axisTitle = asShare ? "% of class" : "Number of cases";
const negative = histogram(data.scoresA, data.labels, 0, asShare);
const positive = histogram(data.scoresA, data.labels, 1, asShare);
negativeHist.clear();
negativeHist.appendRange(negative.x, negative.y);
positiveHist.clear();
positiveHist.appendRange(positive.x, positive.y);

const compare = ui.compareCheckbox.checked;
const prevalence = resultA.positives / data.labels.length;
setXy(roc.noSkill, [0, 1], [0, 1]);
setXy(pr.noSkill, [0, 1], [prevalence, prevalence]);
pr.noSkill.dataSeries.dataSeriesName = `No skill (precision = ${(100 * prevalence).toFixed(1)}%)`;
setXy(roc.curveA, resultA.roc.fpr, resultA.roc.tpr);
setXy(roc.curveB, resultB.roc.fpr, resultB.roc.tpr);
setXy(pr.curveA, resultA.pr.recall, resultA.pr.precision);
setXy(pr.curveB, resultB.pr.recall, resultB.pr.precision);
roc.curveA.dataSeries.dataSeriesName = `Model A (AUC ${resultA.auc.toFixed(3)})`;
roc.curveB.dataSeries.dataSeriesName = `Model B (AUC ${resultB.auc.toFixed(3)})`;
pr.curveA.dataSeries.dataSeriesName = `Model A (AP ${resultA.ap.toFixed(3)})`;
pr.curveB.dataSeries.dataSeriesName = `Model B (AP ${resultB.ap.toFixed(3)})`;
for (const series of [roc.curveB, roc.pointB, pr.curveB, pr.pointB]) series.isVisible = compare;
// Rebuild the legends so they show the new AUC and AP, and model B only when it is drawn
for (const chart of [roc, pr]) {
chart.legend.sciChartLegend?.setRenderableSeriesArray(compare ? [chart.noSkill, chart.curveA, chart.curveB] : [chart.noSkill, chart.curveA]);
}
onThresholdChanged();
}

// Move the markers and update the confusion matrix: runs when the threshold changes
function onThresholdChanged() {
ui.thresholdInput.value = String(threshold);
ui.thresholdOutput.textContent = threshold.toFixed(3);
thresholdLine.x1 = threshold;
thresholdLine.labelValue = threshold.toFixed(3);
const a = confusionMatrix(data.scoresA, data.labels, threshold);
const b = confusionMatrix(data.scoresB, data.labels, threshold);
setXy(roc.pointA, [a.fpr], [a.tpr]);
setXy(roc.pointB, [b.fpr], [b.tpr]);
// With no predicted positives, precision is undefined: leave the PR marker off the chart
setXy(pr.pointA, Number.isFinite(a.precision) ? [a.tpr] : [], Number.isFinite(a.precision) ? [a.precision] : []);
setXy(pr.pointB, Number.isFinite(b.precision) ? [b.tpr] : [], Number.isFinite(b.precision) ? [b.precision] : []);

const pct = (v) => (Number.isFinite(v) ? `${(100 * v).toFixed(1)}%` : "–");
const cell = "padding:6px 8px; text-align:center; border:1px solid #3a5480;";
const good = "background:#3BD16F33;";
const bad = "background:#EF535033;";
ui.panel.innerHTML =
`<table style="border-collapse:collapse; margin-bottom:8px"><caption style="text-align:left; padding-bottom:4px">` +
`Model A confusion matrix at ${threshold.toFixed(3)}</caption>` +
`<tr><td></td><th scope="col" style="${cell}">Predicted +</th><th scope="col" style="${cell}">Predicted −</th></tr>` +
`<tr><th scope="row" style="${cell}">Actual +</th><td style="${cell}${good}">TP ${a.tp}</td><td style="${cell}${bad}">FN ${a.fn}</td></tr>` +
`<tr><th scope="row" style="${cell}">Actual −</th><td style="${cell}${bad}">FP ${a.fp}</td><td style="${cell}${good}">TN ${a.tn}</td></tr>` +
`</table>` +
`<div>Recall (TPR) ${pct(a.tpr)} · FPR ${pct(a.fpr)}</div>` +
`<div>Precision ${pct(a.precision)} · Specificity ${pct(a.specificity)}</div>` +
`<div>Accuracy ${pct(a.accuracy)} · F1 ${Number.isFinite(a.f1) ? a.f1.toFixed(3) : "–"} · J ${a.youdenJ.toFixed(3)}</div>` +
(ui.compareCheckbox.checked
? `<div style="margin-top:6px; color:${COLOUR_B}">Model B: recall ${pct(b.tpr)} · FPR ${pct(b.fpr)} · precision ${pct(b.precision)}</div>`
: "");
}

// The threshold that maximises Youden's J = TPR − FPR for model A
function bestYoudenThreshold() {
let best = 1;
let bestJ = -Infinity;
const { fpr, tpr, threshold: thresholds } = resultA.roc;
for (let k = 1; k < fpr.length; k++) {
if (tpr[k] - fpr[k] > bestJ) {
bestJ = tpr[k] - fpr[k];
best = thresholds[k];
}
}
return best;
}

ui.separationInput.addEventListener("input", onDataChanged);
ui.rateSelect.addEventListener("change", onDataChanged);
ui.compareCheckbox.addEventListener("change", onDataChanged);
ui.histogramSelect.addEventListener("change", onDataChanged);
ui.thresholdInput.addEventListener("input", () => {
threshold = Number(ui.thresholdInput.value);
onThresholdChanged();
});
ui.youdenButton.addEventListener("click", () => {
threshold = bestYoudenThreshold();
onThresholdChanged();
});
thresholdLine.dragDelta.subscribe(() => {
threshold = Math.max(0, Math.min(1, thresholdLine.x1));
onThresholdChanged();
});
onDataChanged();

Key points:

  • Each curve is a FastLineRenderableSeries over an XyDataSeries of (FPR, TPR) or (recall, precision) points. Both axes are fixed from 0 to 1, so curves from different models and settings stay comparable.
  • The diagonal and the precision-recall baseline are ordinary line series with strokeDashArray, so they appear in the legend; the model's AUC and AP go into each dataSeriesName.
  • The score histograms are FastMountainRenderableSeries with isDigitalLine: true, which draws each bin as a flat step. The threshold is a VerticalLineAnnotation with isEditable: true; its dragDelta event moves the slider and the markers.
  • The operating points are XyScatterRenderableSeries with an EllipsePointMarker, left out of the legend and tooltip with includeSeries(series, false).

See it in the demo app: JavaScript line chart · React line chart · Angular line chart, and for draggable threshold lines, JavaScript draggable threshold chart · React draggable threshold chart · Angular draggable threshold chart.

Go deeper: SciChart.js line series documentation, the mountain (area) series documentation for the histograms, and the histogram guide. For how diagnostic and laboratory software uses SciChart, see SciChart for diagnostics and life sciences.

Frequently asked questions​

What does a ROC curve show?​

A ROC curve shows how well a classifier separates two classes at every possible decision threshold. Each point is one threshold: its height is the share of real positives the model catches (the true positive rate) and its distance from the left is the share of negatives it wrongly flags (the false positive rate). A curve that rises steeply towards the top-left corner belongs to a model that ranks positives above negatives.

What is a good AUC score?​

An AUC of 0.5 means the model ranks cases no better than chance, and 1.0 means it ranks every positive above every negative. A widely quoted rule of thumb from Hosmer and Lemeshow calls 0.7 to 0.8 acceptable, 0.8 to 0.9 excellent and 0.9 or more outstanding. What counts as good depends on the task and on the baseline you are trying to beat, and a high AUC can still hide poor precision when positives are rare.

When should I use a precision-recall curve instead of a ROC curve?​

Use a precision-recall curve when the positive class is rare and you care mainly about the cases the model flags, as in fraud detection, screening or information retrieval. The false positive rate on a ROC curve divides by the large number of negatives, so thousands of false alarms barely move it, while precision drops sharply. When the classes are roughly balanced and both kinds of error matter, the ROC curve is the standard choice.

What is the difference between sensitivity and specificity?​

Sensitivity is the share of real positives that a test or model correctly flags as positive: TP / (TP + FN). It is the same as recall and the true positive rate. Specificity is the share of real negatives correctly cleared as negative: TN / (TN + FP). The false positive rate on a ROC curve is 1 minus the specificity. Lowering the threshold raises sensitivity and lowers specificity.

What is the F1 score?​

The F1 score is the harmonic mean of precision and recall, 2PR / (P + R). It is high only when both are high, ignores true negatives, and depends on the threshold you choose. Use it to compare models at one operating point when positives are rare; use the precision-recall curve to see every threshold at once.

Can AUC be below 0.5?​

Yes. An AUC below 0.5 means the model ranks negatives above positives more often than the reverse. On a test set it is usually a bug, such as swapped labels or a score that rises for the wrong class, or chance when the model has no skill and the test set is small. Reversing the scores of a model with an AUC of 0.3 gives an AUC of 0.7.

How do I plot a ROC curve in JavaScript?​

Sort the test cases by score from highest to lowest, then walk down the list counting true and false positives. After each distinct score, add a point at (false positive rate, true positive rate), and sum the trapezoids under the points for the AUC. Draw the points as a line series from (0, 0) to (1, 1) with a dashed diagonal for chance. SciChart.js draws it with a FastLineRenderableSeries over an XyDataSeries, and its React and Angular wrappers take the same code.

Sources​