Plotly Chart Guidelines: Difference between revisions
m Frank@tygron.nl moved page Plotly Chart Quality Guidelines to Plotly Chart Guidelines |
No edit summary |
||
| Line 3: | Line 3: | ||
==Top 5 Failure Modes== | ==Top 5 Failure Modes== | ||
These are the most frequently observed defects across production panels. Address them first during self-review | These are the most frequently observed defects across production panels. Address them first during self-review. | ||
{|class=wikitable | {|class=wikitable | ||
| Line 12: | Line 12: | ||
|- | |- | ||
| 1 | | 1 | ||
| Runtime `fetch()` or dynamic TQL construction | |||
| Raw JavaScript error; blank chart; FATAL | |||
| Use static `$SELECT_…$` TQL tags only ([[#TQL_Clause_Compatibility_X_vs_Y|see TQL section]]) | |||
|- | |||
| 2 | |||
| Vertical overflow | | Vertical overflow | ||
| x-axis labels or footnote clipped at panel bottom | | x-axis labels or footnote clipped at panel bottom | ||
| Set chart div height to panel height minus all other elements ([[#Safe_DOM_Order_and_Panel_Height_Budget|see height budget]]) | | Set chart div height to panel height minus all other elements ([[#Safe_DOM_Order_and_Panel_Height_Budget|see height budget]]) | ||
|- | |- | ||
| | | 3 | ||
| Coolest bar renders gray/white | | Coolest bar renders gray/white | ||
| Minimum-value bar looks like missing data on a Reds scale | | Minimum-value bar looks like missing data on a Reds scale | ||
| Pad `cmin` below the data minimum ([[#Choosing_Color_Domain_Bounds|see color domain]]) | | Pad `cmin` below the data minimum ([[#Choosing_Color_Domain_Bounds|see color domain]]) | ||
|- | |- | ||
| | | 4 | ||
| Colorscale has no effect | | Colorscale has no effect | ||
| All bars render in default blue despite declaring `colorscale: "Reds"` | | All bars render in default blue despite declaring `colorscale: "Reds"` | ||
| Add `marker.color: values` to the trace ([[#Coloring_Bar_Charts_by_Value|see coloring]]) | | Add `marker.color: values` to the trace ([[#Coloring_Bar_Charts_by_Value|see coloring]]) | ||
|- | |- | ||
| | | 5 | ||
| Literal `°C` in labels/tooltips | | Literal `°C` in labels/tooltips | ||
| Degree sign shows as raw entity text | | Degree sign shows as raw entity text | ||
| Use `\u00B0` or literal `°` inside JavaScript strings ([[#Encoding_Special_Characters_in_JavaScript_Strings|see encoding]]) | | Use `\u00B0` or literal `°` inside JavaScript strings ([[#Encoding_Special_Characters_in_JavaScript_Strings|see encoding]]) | ||
|} | |} | ||
| Line 47: | Line 47: | ||
* '''traces''' – an array of trace objects. Each trace describes one dataset (a set of bars, a line, etc.). Properties such as `type`, `x`, `y`, `marker`, `text`, `textposition`, and `showlegend` belong here. | * '''traces''' – an array of trace objects. Each trace describes one dataset (a set of bars, a line, etc.). Properties such as `type`, `x`, `y`, `marker`, `text`, `textposition`, and `showlegend` belong here. | ||
* '''layout''' – a single object controlling axes, margins, titles, annotations, and global appearance. Properties such as `xaxis`, `yaxis`, `margin`, `title`, `barmode`, `paper_bgcolor`, and `plot_bgcolor` belong here. | * '''layout''' – a single object controlling axes, margins, titles, annotations, and global appearance. Properties such as `xaxis`, `yaxis`, `margin`, `title`, `barmode`, `paper_bgcolor`, and `plot_bgcolor` belong here. | ||
* '''config''' – controls interactivity. The | * '''config''' – controls interactivity. See the next section. | ||
* '''orientation''' – vertical (column) bars are the default and preferred layout for per-category comparisons. Horizontal bars are a fallback only when category names are too long even after rotation. | |||
Examples on this page focus on trace and layout properties. The config argument is omitted unless a non-default override is demonstrated. | |||
See [[How to insert a Plotly Graph]] for the full setup including CSS sizing and the staticPlot flag. | |||
===Recommended Plotly configuration=== | |||
The default Plotly configuration (`{ staticPlot: false, displayModeBar: true }`) is **acceptable** for Tygron Text Panels. Standard examples therefore omit the config argument entirely: | |||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', [trace], layout); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Pass a config object **only** when overriding a default: | |||
<syntaxhighlight> | |||
// Non-interactive chart (no mode bar, no pan/zoom) | |||
Plotly.newPlot('chart', [trace], layout, { staticPlot: true }); | |||
</syntaxhighlight> | |||
Do not clutter examples with default configuration values. | |||
===Loading Plotly correctly=== | ===Loading Plotly correctly=== | ||
| Line 74: | Line 90: | ||
Use `margin`, not `margins`, in the Plotly layout object. Incorrect property names fail silently and produce unexpected spacing. | Use `margin`, not `margins`, in the Plotly layout object. Incorrect property names fail silently and produce unexpected spacing. | ||
=== | ===JavaScript conventions=== | ||
Wrap chart code in an IIFE | * Use `const` for values that are not reassigned; use `let` for values that are reassigned. **Never use `var`.** | ||
* Wrap chart code in an IIFE `(function () { … })();` to prevent leaking variables into the global panel scope. | |||
* Define shared named constants (unit string, padding factors, chart height) once at the top of the script and reference them throughout. | |||
* Keep source formatted with indentation and newlines. Do not store minified single-line scripts. | |||
* Separate data extraction, cleaning, scale calculation, trace construction, layout construction, and rendering into distinct blocks. | |||
* Do not hardcode project-specific names or values in reusable documentation examples. | |||
===Avoid duplicate titles=== | ===Avoid duplicate titles=== | ||
| Line 89: | Line 110: | ||
Two layout defects dominate failed panels: the chart container appearing before the title in the DOM, and the total content height exceeding the fixed panel height. | Two layout defects dominate failed panels: the chart container appearing before the title in the DOM, and the total content height exceeding the fixed panel height. | ||
===DOM order=== | ===Mandatory DOM order=== | ||
The | The required DOM order for a chart panel is: | ||
# `<h2>` title | # `<h2>` title | ||
# `<p>` subtitle | # `<p>` subtitle | ||
# chart container `<div>` | # chart container `<div>` | ||
# footnote `<p>` ( | # footnote `<p>` (optional) | ||
# `<script>` initialisation | # `<script>` initialisation | ||
Placing the chart container before the title can push the title below the visible area in fixed-height panels. Even if a screenshot appears correct, the stored DOM order should still be reviewed. | Placing the chart container before the title can push the title below the visible area in fixed-height panels. Even if a screenshot appears correct, the stored DOM order should still be reviewed. | ||
=== | ===Height budget=== | ||
A panel has a fixed pixel height (e.g. 1000 px). The sum of all elements must fit within that height | A panel has a fixed pixel height (e.g. 1000 px). The sum of all elements must fit within that height. | ||
{|class=wikitable | |||
! Element | |||
! Estimated height (1000 px panel) | |||
|- | |||
| Title (`<h2>`) | |||
| 40 px | |||
padding | |- | ||
| Subtitle (`<p>`) | |||
| 30 px | |||
| Chart `<div>` | |||
| 850 px | |||
|- | |||
| Footnote (optional) | |||
| 30 px | |||
|- | |||
| Safety padding | |||
| 50 px | |||
|- | |||
| '''Total''' | |||
| '''1000 px''' | |||
|} | |||
If the footnote is omitted, the chart height can be increased to approximately 910 px. | |||
* Set the chart `<div>` height to `panel_height − (title + subtitle + footnote + padding)`, typically 80–90 % of the panel height. | *s Set the chart `<div>` height to `panel_height − (title + subtitle + footnote + padding)`, typically 80–90 % of the panel height. | ||
* Set `layout.height` to the same value as the `<div>` height. | * Set `layout.height` to the **same value** as the `<div>` height. | ||
* Do not set `layout.height` to the full panel height when the panel contains additional HTML above or below the chart. | * Do not set `layout.height` to the full panel height when the panel contains additional HTML above or below the chart. | ||
* After any change to panel size, recalculate and re-verify the rendered image. | * After any change to panel size, recalculate and re-verify the rendered image. | ||
| Line 144: | Line 178: | ||
A common defect is using a zero baseline or an overly wide axis when the data occupies a narrow band. This is especially relevant when comparing Grid Overlay values across Neighborhoods or Areas, where values often fall within a tight range. | A common defect is using a zero baseline or an overly wide axis when the data occupies a narrow band. This is especially relevant when comparing Grid Overlay values across Neighborhoods or Areas, where values often fall within a tight range. | ||
''' | '''Labels must be readable.''' Every axis tick, category label, value annotation, and colorbar title must be legible at the rendered panel size. If a label is clipped, rotated beyond recognition, or too small to read, the chart fails regardless of data accuracy. This is a **mandatory** acceptance criterion. | ||
===When to avoid a zero baseline=== | ===When to avoid a zero baseline=== | ||
| Line 160: | Line 194: | ||
In that case, use a data-driven range. | In that case, use a data-driven range. | ||
===When an over-wide range is misleading=== | |||
An axis range much wider than the data spread wastes vertical space and reduces comparability. If the data spread is small (e.g. 3.3 °C), do not use a range many times larger than the spread (e.g. `[30, 50]`) unless there is a strong analytical reason. An over-wide range makes all bars appear the same height and defeats the purpose of the chart. | |||
===Concrete example: narrow-band data=== | ===Concrete example: narrow-band data=== | ||
| Line 171: | Line 209: | ||
===Data-driven range=== | ===Data-driven range=== | ||
First compute the bounds from your data: | First compute the bounds from your data using named constants: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
(function () { | |||
const AXIS_PADDING_FACTOR = 0.15; | |||
const | const MIN_AXIS_PADDING = 0.5; | ||
const | |||
const yMin = minValue - | const minValue = Math.min(...values); | ||
const yMax = maxValue + | const maxValue = Math.max(...values); | ||
const span = maxValue - minValue || 1; | |||
const axisPadding = Math.max(span * AXIS_PADDING_FACTOR, MIN_AXIS_PADDING); | |||
const yMin = minValue - axisPadding; | |||
const yMax = maxValue + axisPadding; | |||
})(); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 187: | Line 229: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', | Plotly.newPlot('chart', [trace], { | ||
yaxis: { | yaxis: { | ||
range: [yMin, yMax] | range: [yMin, yMax] | ||
} | } | ||
}); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
(The `config` argument is omitted because the platform default is acceptable.) | |||
===Choose dtick sensibly=== | ===Choose dtick sensibly=== | ||
| Line 200: | Line 243: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', | Plotly.newPlot('chart', [trace], { | ||
yaxis: { | yaxis: { | ||
range: [yMin, yMax], | range: [yMin, yMax], | ||
dtick: 1 | dtick: 1 | ||
} | } | ||
}); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Pick a `dtick` that yields roughly 4–10 ticks over the visible range. Too many ticks clutter the chart; too few hide structure. | |||
=== | ===Truncation footnote (optional)=== | ||
'''A footnote is not a mandatory requirement.'''' However, if the axis does not start at zero and the truncation could be misunderstood, a brief note improves clarity: | |||
<syntaxhighlight> | <syntaxhighlight> | ||
| Line 221: | Line 263: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
State the concrete start value (rather than a generic "zoomed" sentence) to prevent readers from misinterpreting bar lengths. If a footnote is included, reserve height for it in the budget and verify it remains visible. | |||
===Hardcoded ranges=== | ===Hardcoded ranges=== | ||
| Line 240: | Line 278: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
{ | { | ||
type: "bar", | type: "bar", | ||
| Line 246: | Line 283: | ||
y: values, | y: values, | ||
text: values.map((v) => v.toFixed(1) + "\u00B0C"), | text: values.map((v) => v.toFixed(1) + "\u00B0C"), | ||
textposition: "outside" | textposition: "outside" | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 253: | Line 290: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', | Plotly.newPlot('chart', [trace], { | ||
margin: { t: 60 } | |||
margin: { t: 60 } | }); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 270: | Line 306: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', | Plotly.newPlot('chart', [trace], { | ||
margin: { b: 140 } | |||
margin: { b: 140 } | }); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 283: | Line 318: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', | Plotly.newPlot('chart', [trace], { | ||
xaxis: { | xaxis: { | ||
automargin: true | automargin: true | ||
} | } | ||
}); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 298: | Line 332: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', | Plotly.newPlot('chart', [trace], { | ||
xaxis: { | xaxis: { | ||
tickangle: -45 | tickangle: -45 | ||
} | } | ||
}); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 313: | Line 346: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', | Plotly.newPlot('chart', [trace], { | ||
xaxis: { | xaxis: { | ||
tickfont: { size: 11 } | tickfont: { size: 11 } | ||
} | } | ||
}); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 330: | Line 362: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
{ | { | ||
type: "bar", | type: "bar", | ||
x: values, | x: values, | ||
y: names, | y: names, | ||
orientation: "h" | orientation: "h" | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
When switching to horizontal bars, | When switching to horizontal bars, swap the axis roles and reserve left margin for category labels: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
// layout | // layout | ||
margin: { t: 40, r: | margin: { t: 40, r: 70, b: 40, l: 180 } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 357: | Line 388: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
(function () { | |||
const trace = { | const COLOR_PADDING_FACTOR = 0.15; | ||
const MIN_COLOR_PADDING = 0.5; | |||
const minValue = Math.min(...values); | |||
const maxValue = Math.max(...values); | |||
const span = maxValue - minValue || 1; | |||
const colorPadding = Math.max(span * COLOR_PADDING_FACTOR, MIN_COLOR_PADDING); | |||
const trace = { | |||
type: "bar", | |||
x: names, | |||
y: values, | |||
marker: { | |||
color: values, // ← REQUIRED: without this the colorscale is inert | |||
colorscale: "Reds", | |||
cmin: minValue - colorPadding, | |||
cmax: maxValue + colorPadding, | |||
showscale: true, | |||
line: { | |||
color: "#333333", | |||
width: 1 | |||
}, | |||
colorbar: { | |||
title: { text: "PET (\u00B0C)" }, | |||
thickness: 14, | |||
len: 0.8 | |||
} | |||
} | } | ||
}; | |||
}; | |||
Plotly.newPlot('chart', [trace], { | Plotly.newPlot('chart', [trace], { | ||
margin: { r: 70 } | |||
}); | |||
} | })(); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
'''The critical property is `marker.color`.''' Without it, `colorscale`, `cmin`, and `cmax` have no visible effect and the bars render in the default Plotly blue. Declaring `colorscale: "Reds"` alone is a no-op | '''The critical property is `marker.color`.''' Without it, `colorscale`, `cmin`, and `cmax` have no visible effect and the bars render in the default Plotly blue. Declaring `colorscale: "Reds"` alone is a **silent no-op**—there is no error message, no console warning. The chart simply renders in uniform blue. Misspelling `color` as `colors` has the same effect. | ||
===Array length must match=== | ===Array length must match=== | ||
| Line 445: | Line 484: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', [trace], { | Plotly.newPlot('chart', [trace], { | ||
margin: { r: 70 } | margin: { r: 70 } | ||
}); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 455: | Line 493: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
{ | { | ||
type: "bar", | type: "bar", | ||
x: names, | x: names, | ||
y: values, | y: values, | ||
showlegend: true | showlegend: true | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 469: | Line 506: | ||
Color should support the data, not replace it. Also provide value labels, tooltips, or a table when precise values matter. | Color should support the data, not replace it. Also provide value labels, tooltips, or a table when precise values matter. | ||
==Choosing Color Domain Bounds== | ==Choosing Color Domain Bounds== | ||
| Line 487: | Line 520: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
(function () { | |||
const COLOR_PADDING_FACTOR = 0.15; | |||
const | const MIN_COLOR_PADDING = 0.5; | ||
const | |||
const | const minValue = Math.min(...values); | ||
const | const maxValue = Math.max(...values); | ||
const span = maxValue - minValue || 1; | |||
const colorPadding = Math.max(span * COLOR_PADDING_FACTOR, MIN_COLOR_PADDING); | |||
const colorMin = minValue - colorPadding; | |||
const trace = { | const colorMax = maxValue + colorPadding; | ||
const trace = { | |||
type: "bar", | |||
x: names, | |||
y: values, | |||
marker: { | |||
color: values, | |||
colorscale: "Reds", | |||
} | cmin: colorMin, | ||
}; | cmax: colorMax | ||
} | |||
}; | |||
})(); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 548: | Line 584: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
Plotly.newPlot('chart', | Plotly.newPlot('chart', [trace], { | ||
paper_bgcolor: "rgba(255,255,255,0.95)", | paper_bgcolor: "rgba(255,255,255,0.95)", | ||
plot_bgcolor: "rgba(255,255,255,0.95)" | plot_bgcolor: "rgba(255,255,255,0.95)" | ||
}); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 624: | Line 659: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
{ | { | ||
type: "bar", | type: "bar", | ||
| Line 677: | Line 711: | ||
===Static binding only=== | ===Static binding only=== | ||
Do **not** construct TQL queries dynamically in JavaScript (e.g. string concatenation + `fetch('/api/session/query/')`). Use static `$SELECT_…$` tags that the platform evaluates at render time. Runtime fetching is a FATAL violation and the root cause of blank-panel failures. | Do **not** construct TQL queries dynamically in JavaScript (e.g. string concatenation + `fetch('/api/session/query/')`). Use static `$SELECT_…$` tags that the platform evaluates at render time. Runtime fetching is a **FATAL** violation and the root cause of blank-panel failures. | ||
Full details: [[Text Panel Content Guidelines#Static_TQL_data_binding_for_charts|Static TQL data binding]], [[TQL]], [[X (TQL)]], [[Y (TQL)]]. | Full details: [[Text Panel Content Guidelines#Static_TQL_data_binding_for_charts|Static TQL data binding]], [[TQL]], [[X (TQL)]], [[Y (TQL)]]. | ||
| Line 683: | Line 717: | ||
==Overlay Coupling and Timeframe Disclosure== | ==Overlay Coupling and Timeframe Disclosure== | ||
When the chart values come from a grid overlay, the panel should be coupled to that overlay so it activates when the panel opens. The TQL query, the coupled overlay, and the subtitle should all refer to the same source. Pin the timeframe explicitly in the TQL tag or state it concretely in the subtitle (e.g. "02 Aug 2013, last iteration"). | When the chart values come from a grid overlay, the panel should be coupled to that overlay so it activates when the panel opens. The TQL query, the coupled overlay, and the subtitle should all refer to the same source. Pin the timeframe explicitly in the TQL tag or state it concretely in the subtitle (e.g. "02 Aug 2013, last iteration"). A generic phrase such as "most recent timeframe" is insufficient; use the concrete date. | ||
Full details: [[Text Panel Content Guidelines#Overlay,_timeframe,_and_scenario_coupling|Overlay, timeframe, and scenario coupling]], [[Timeframe (TQL Param)]]. | Full details: [[Text Panel Content Guidelines#Overlay,_timeframe,_and_scenario_coupling|Overlay, timeframe, and scenario coupling]], [[Timeframe (TQL Param)]]. | ||
| Line 692: | Line 726: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
const container = document.getElementById("chart"); | (function () { | ||
const container = document.getElementById("chart"); | |||
if (!container) { | |||
if (! | return; | ||
} | } | ||
Plotly.newPlot(container, [trace], layout | try { | ||
} catch (error) { | if (!rows.length) { | ||
throw new Error("No data available"); | |||
} | |||
} | |||
Plotly.newPlot(container, [trace], layout); | |||
} catch (error) { | |||
container.innerHTML = | |||
"<p style='color:#c00;padding:20px;'>Unable to render chart. Please check the data source.</p>"; | |||
} | |||
})(); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
| Line 730: | Line 770: | ||
* footnote. | * footnote. | ||
Define the unit | Define the unit once and reuse it: | ||
<syntaxhighlight> | <syntaxhighlight> | ||
| Line 738: | Line 778: | ||
This prevents subtle inconsistencies (e.g. `°C` in the axis but `deg C` in the tooltip). Avoid mixing formats such as `C`, `°C`, and `degC` within the same panel. | This prevents subtle inconsistencies (e.g. `°C` in the axis but `deg C` in the tooltip). Avoid mixing formats such as `C`, `°C`, and `degC` within the same panel. | ||
==Verify the Rendered Image (MANDATORY)=== | |||
Source code can look correct while the rendered chart still exhibits a defect. This is the single most reliable way to catch silent failures (inert colorscale, clipped labels, near-white minimum bar, literal entity text). **Rendered-image inspection is mandatory, not optional.** Before marking a panel complete: | |||
* Open the panel in the viewer (`web/panel.html?id=…`) and inspect the rendered image. | |||
* Confirm all x-axis category labels are fully visible (especially the last one). | |||
* Confirm the minimum-value bar is visibly coloured (not gray/white). | |||
* Confirm no literal `°` or `°` text appears anywhere. | |||
* Confirm the chart is not blank and no JS error is displayed. | |||
* Confirm the footnote (if present) and no-data message are not clipped. | |||
* Confirm the colorbar gradient matches the actual bar colours. | |||
* Confirm the title and subtitle are visible and legible. | |||
A panel whose code passes review but whose rendered image shows a defect is '''not''' ready for delivery. | |||
See [[Text Panel Content Guidelines#Quality-assurance_checklist|QA checklist]] for the full rendered-image checklist. | |||
==Quick-Reference Checklist== | ==Quick-Reference Checklist== | ||
| Line 748: | Line 805: | ||
|- | |- | ||
| DOM order | | DOM order | ||
| title → subtitle → chart div → footnote → script | | title → subtitle → chart div → footnote (optional) → script | ||
|- | |- | ||
| Height budget | | Height budget | ||
| Line 760: | Line 817: | ||
|- | |- | ||
| Axis range | | Axis range | ||
| fitted to data (no zero baseline for narrow bands); truncation disclosed ( | | fitted to data (no zero baseline for narrow bands, no over-wide range); truncation disclosed (optional) | ||
|- | |- | ||
| X-axis labels | | X-axis labels | ||
| Line 793: | Line 850: | ||
|- | |- | ||
| Config | | Config | ||
| | | platform default applied (explicit or implicit); non-default overrides documented | ||
|- | |- | ||
| No CDN script | | No CDN script | ||
| Line 800: | Line 857: | ||
| Orientation | | Orientation | ||
| vertical (column) bars preferred; horizontal only when labels require it | | vertical (column) bars preferred; horizontal only when labels require it | ||
|- | |||
| JS conventions | |||
| `const`/`let` (not `var`); IIFE-scoped; named constants; no global leaks | |||
|- | |||
| Source formatting | |||
| indented, multi-line, readable; not minified | |||
|- | |- | ||
| Rendered image | | Rendered image | ||
| inspected: all labels visible, colours correct, no JS error, min bar not gray | | **inspected (mandatory):** all labels visible, colours correct, no JS error, min bar not gray | ||
|} | |} | ||
| Line 810: | Line 873: | ||
A per-category bar-chart panel is ready for delivery only when '''all''' of the following chart-specific conditions hold: | A per-category bar-chart panel is ready for delivery only when '''all''' of the following chart-specific conditions hold: | ||
===FATAL (release blockers)=== | |||
* Static bracketed TQL tags (no runtime fetch, no CDN, no `window.load` gate). | * Static bracketed TQL tags (no runtime fetch, no CDN, no `window.load` gate). | ||
* Names pulled dynamically; X-clause used for both categories and values. | * Names pulled dynamically; X-clause used for both categories and values. | ||
* Stored panel text is not empty (rendered image confirms chart presence). | |||
===MAJOR (must fix before delivery)=== | |||
* `marker.color` bound to values **and** `colorscale`/`cmin`/`cmax` present; `cmin` padded below the minimum. | * `marker.color` bound to values **and** `colorscale`/`cmin`/`cmax` present; `cmin` padded below the minimum. | ||
* y-axis fitted to the data extent (no zero baseline, no over-wide range). | * y-axis fitted to the data extent (no zero baseline, no over-wide range). | ||
| Line 818: | Line 887: | ||
* Opaque background + explicit dark fonts; single title; unit consistent; degree sign via `\u00B0`. | * Opaque background + explicit dark fonts; single title; unit consistent; degree sign via `\u00B0`. | ||
* `try/catch` + empty-data guard. | * `try/catch` + empty-data guard. | ||
* Vertical orientation used (horizontal only with justification). | * Vertical orientation used (horizontal only with justification). | ||
* | * `let`/`const` used throughout; code IIFE-scoped; source formatted and readable. | ||
===MINOR (should fix; documented if deferred)=== | |||
* Platform default config applied (explicit or implicit). | |||
* Concrete date in subtitle when timeframe is pinned. | |||
* Colorbar present for continuous scales. | |||
* Truncation footnote present (optional but recommended). | |||
* Worst-case label length tested. | |||
Panel-level sign-off (text persistence, name uniqueness, overlay coupling, timeframe disclosure): [[Text Panel Content Guidelines#Sign-off_criteria|Sign-off criteria]]. | Panel-level sign-off (text persistence, name uniqueness, overlay coupling, timeframe disclosure): [[Text Panel Content Guidelines#Sign-off_criteria|Sign-off criteria]]. | ||
Revision as of 15:25, 1 December 2026
This page contains tips on adding a Plotly Chart to a Text Panel content successfully. It focuses on correct Plotly figure construction, visual tuning, and rendering-quality checks. For panel lifecycle topics (severity grading, timeout-safe authoring workflow, unique names and collision handling, QA sign-off criteria, and common failure signatures), see Text Panel Content Guidelines.
Top 5 Failure Modes
These are the most frequently observed defects across production panels. Address them first during self-review.
| Rank | Defect | Symptom | Fix |
|---|---|---|---|
| 1 | Runtime `fetch()` or dynamic TQL construction | Raw JavaScript error; blank chart; FATAL | Use static `$SELECT_…$` TQL tags only (see TQL section) |
| 2 | Vertical overflow | x-axis labels or footnote clipped at panel bottom | Set chart div height to panel height minus all other elements (see height budget) |
| 3 | Coolest bar renders gray/white | Minimum-value bar looks like missing data on a Reds scale | Pad `cmin` below the data minimum (see color domain) |
| 4 | Colorscale has no effect | All bars render in default blue despite declaring `colorscale: "Reds"` | Add `marker.color: values` to the trace (see coloring) |
| 5 | Literal `°C` in labels/tooltips | Degree sign shows as raw entity text | Use `\u00B0` or literal `°` inside JavaScript strings (see encoding) |
Figure Anatomy
Every Plotly figure is built from up to four arguments passed to `Plotly.newPlot`:
Plotly.newPlot(divId, traces, layout, config);- traces – an array of trace objects. Each trace describes one dataset (a set of bars, a line, etc.). Properties such as `type`, `x`, `y`, `marker`, `text`, `textposition`, and `showlegend` belong here.
- layout – a single object controlling axes, margins, titles, annotations, and global appearance. Properties such as `xaxis`, `yaxis`, `margin`, `title`, `barmode`, `paper_bgcolor`, and `plot_bgcolor` belong here.
- config – controls interactivity. See the next section.
- orientation – vertical (column) bars are the default and preferred layout for per-category comparisons. Horizontal bars are a fallback only when category names are too long even after rotation.
Examples on this page focus on trace and layout properties. The config argument is omitted unless a non-default override is demonstrated.
See How to insert a Plotly Graph for the full setup including CSS sizing and the staticPlot flag.
Recommended Plotly configuration
The default Plotly configuration (`{ staticPlot: false, displayModeBar: true }`) is **acceptable** for Tygron Text Panels. Standard examples therefore omit the config argument entirely:
Plotly.newPlot('chart', [trace], layout);Pass a config object **only** when overriding a default:
// Non-interactive chart (no mode bar, no pan/zoom)
Plotly.newPlot('chart', [trace], layout, { staticPlot: true });Do not clutter examples with default configuration values.
Loading Plotly correctly
Plotly is available inside Text Panels without manually loading an external CDN script. When the panel content contains the capitalized word `Plotly`, the platform injects the required script reference. The `$LIB_PLOTLY` tag can also be used where an explicit script entry is preferred.
Do not add CDN script tags. Avoid adding external Plotly CDN script tags (e.g. `https://cdn.plot.ly/plotly-*.min.js`). Manual CDN loading can cause:
- duplicate library loading,
- version mismatches,
- offline rendering failures,
- content-security-policy problems.
Execution timing
Because TQL tags are replaced before the HTML is rendered, chart code can normally run immediately after the static values are available. Avoid gating the entire chart behind `window.load` unless there is a specific reason to do so—a `window.load` handler can leave the chart blank if the expected load sequence does not occur.
Property name accuracy
Use `margin`, not `margins`, in the Plotly layout object. Incorrect property names fail silently and produce unexpected spacing.
JavaScript conventions
- Use `const` for values that are not reassigned; use `let` for values that are reassigned. **Never use `var`.**
- Wrap chart code in an IIFE `(function () { … })();` to prevent leaking variables into the global panel scope.
- Define shared named constants (unit string, padding factors, chart height) once at the top of the script and reference them throughout.
- Keep source formatted with indentation and newlines. Do not store minified single-line scripts.
- Separate data extraction, cleaning, scale calculation, trace construction, layout construction, and rendering into distinct blocks.
- Do not hardcode project-specific names or values in reusable documentation examples.
Avoid duplicate titles
Do not declare both an HTML `<h2>` title and a `layout.title` in the Plotly configuration. Doing so produces a ghost/duplicate title that overlaps or stacks awkwardly. Choose one:
- Preferred: use the HTML `<h2>` for the panel title and omit `layout.title`.
- Alternative: use `layout.title` and omit the HTML heading.
Safe DOM Order and Panel Height Budget
Two layout defects dominate failed panels: the chart container appearing before the title in the DOM, and the total content height exceeding the fixed panel height.
Mandatory DOM order
The required DOM order for a chart panel is:
- `<h2>` title
- `<p>` subtitle
- chart container `<div>`
- footnote `<p>` (optional)
- `<script>` initialisation
Placing the chart container before the title can push the title below the visible area in fixed-height panels. Even if a screenshot appears correct, the stored DOM order should still be reviewed.
Height budget
A panel has a fixed pixel height (e.g. 1000 px). The sum of all elements must fit within that height.
| Element | Estimated height (1000 px panel) | ||
|---|---|---|---|
| Title (`<h2>`) | 40 px | ||
| Subtitle (`<p>`) | 30 px | Chart `<div>` | 850 px |
| Footnote (optional) | 30 px | ||
| Safety padding | 50 px | ||
| Total | 1000 px |
If the footnote is omitted, the chart height can be increased to approximately 910 px.
- s Set the chart `<div>` height to `panel_height − (title + subtitle + footnote + padding)`, typically 80–90 % of the panel height.
- Set `layout.height` to the **same value** as the `<div>` height.
- Do not set `layout.height` to the full panel height when the panel contains additional HTML above or below the chart.
- After any change to panel size, recalculate and re-verify the rendered image.
Anti-pattern: Setting the chart `<div>` to 1000 px inside a 1000 px panel that also contains a title, subtitle, and footnote guarantees vertical overflow. The chart will consume the full panel height, pushing the x-axis labels and any footnote below the visible fold.
A panel that requires scrolling to reveal axis labels or values should be resized or simplified.
Width budget
Account for horizontal space as well:
- A colorbar consumes approximately 60–80 px on the right side.
- Long category labels with rotation consume additional left/right margin.
- Set `layout.margin.r` to accommodate the colorbar (typically 70 px).
- If the panel width is constrained, prefer shorter labels or a horizontal bar orientation.
Avoid overflow:hidden
Do not use `overflow: hidden` on the panel or chart container. It silently clips axis labels, footnotes, and no-data messages. Verify that the last x-axis label is fully visible and that footnotes and no-data messages remain visible.
Full details: Layout, height budget, and clipping prevention.
Axis Scaling and Label Readability
A common defect is using a zero baseline or an overly wide axis when the data occupies a narrow band. This is especially relevant when comparing Grid Overlay values across Neighborhoods or Areas, where values often fall within a tight range.
Labels must be readable. Every axis tick, category label, value annotation, and colorbar title must be legible at the rendered panel size. If a label is clipped, rotated beyond recognition, or too small to read, the chart fails regardless of data accuracy. This is a **mandatory** acceptance criterion.
When to avoid a zero baseline
Avoid forcing the axis to zero when:
- the data range is narrow,
- zero is not a meaningful reference,
- the purpose is to compare small differences between categories.
Example situation:
- all values are within a few units of each other,
- a zero baseline makes all bars look almost identical.
In that case, use a data-driven range.
When an over-wide range is misleading
An axis range much wider than the data spread wastes vertical space and reduces comparability. If the data spread is small (e.g. 3.3 °C), do not use a range many times larger than the spread (e.g. `[30, 50]`) unless there is a strong analytical reason. An over-wide range makes all bars appear the same height and defeats the purpose of the chart.
Concrete example: narrow-band data
Consider PET values spanning 39.3–42.6 °C (a 3.3 °C spread):
- A zero-baseline axis (`range: [0, 45]`) makes all nine bars reach nearly the same height—differences are invisible.
- An over-wide axis (`range: [30, 50]`) wastes ~60 % of vertical space and still obscures inter-neighborhood differences.
- A fitted axis (`range: [38.5, 43.5]`) makes the 3.3 °C spread clearly visible.
Data-driven range
First compute the bounds from your data using named constants:
(function () {
const AXIS_PADDING_FACTOR = 0.15;
const MIN_AXIS_PADDING = 0.5;
const minValue = Math.min(...values);
const maxValue = Math.max(...values);
const span = maxValue - minValue || 1;
const axisPadding = Math.max(span * AXIS_PADDING_FACTOR, MIN_AXIS_PADDING);
const yMin = minValue - axisPadding;
const yMax = maxValue + axisPadding;
})();Then set the range on the layout object:
Plotly.newPlot('chart', [trace], {
yaxis: {
range: [yMin, yMax]
}
});(The `config` argument is omitted because the platform default is acceptable.)
Choose dtick sensibly
`dtick` controls the step between axis ticks. Set it alongside range on the layout object:
Plotly.newPlot('chart', [trace], {
yaxis: {
range: [yMin, yMax],
dtick: 1
}
});Pick a `dtick` that yields roughly 4–10 ticks over the visible range. Too many ticks clutter the chart; too few hide structure.
Truncation footnote (optional)
A footnote is not a mandatory requirement.' However, if the axis does not start at zero and the truncation could be misunderstood, a brief note improves clarity:
<p class="footnote">
The y-axis starts at {{yMin}} °C to emphasise differences between categories.
</p>State the concrete start value (rather than a generic "zoomed" sentence) to prevent readers from misinterpreting bar lengths. If a footnote is included, reserve height for it in the budget and verify it remains visible.
Hardcoded ranges
Avoid hardcoded axis ranges that may clip future data. If a fixed range is used, require justification and a footnote explaining the chosen bounds. Hardcoded ranges become stale when scenarios, iterations, or timeframes change.
Ensure extremes are visible
Ensure the minimum and maximum values remain visible inside the plot area. Check axis behaviour after data changes, not only for the initial dataset. Avoid duplicate or overlapping axis labels.
Value labels
When precise comparison matters, display values above the bars. These properties belong to the trace object:
{
type: "bar",
x: names,
y: values,
text: values.map((v) => v.toFixed(1) + "\u00B0C"),
textposition: "outside"
}Include units in the label string. Ensure the layout top margin is large enough to show outside labels:
Plotly.newPlot('chart', [trace], {
margin: { t: 60 }
});Reserve top margin when displaying a y-axis title.
Preventing Clipped Category Labels
Clipped x-axis labels are a common rendering defect, especially when category names are long.
Increase bottom margin
Rotated labels need vertical space. Set the bottom margin on the layout object:
Plotly.newPlot('chart', [trace], {
margin: { b: 140 }
});If labels are still clipped, increase the bottom margin further—within the total height budget described above.
Use automargin
Enable automatic margin adjustment on the layout object, where supported:
Plotly.newPlot('chart', [trace], {
xaxis: {
automargin: true
}
});This helps but is not a substitute for verifying the rendered image.
Control tick angle
Set a moderate rotation angle on the layout object:
Plotly.newPlot('chart', [trace], {
xaxis: {
tickangle: -45
}
});Very steep angles (e.g. −90) can require excessive bottom margin.
Reduce font size cautiously
Reducing font size can help, but only if labels remain readable. Set the tick font on the layout object:
Plotly.newPlot('chart', [trace], {
xaxis: {
tickfont: { size: 11 }
}
});Abbreviate long names
If full names are impractical, use controlled abbreviations and explain them in a footnote or tooltip.
Use horizontal bars as a fallback
Vertical (column) orientation is the default and preferred layout for per-category comparisons. Use horizontal bars only when category names are too long for a vertical x-axis even after rotation. Change the orientation on the trace object:
{
type: "bar",
x: values,
y: names,
orientation: "h"
}When switching to horizontal bars, swap the axis roles and reserve left margin for category labels:
// layout
margin: { t: 40, r: 70, b: 40, l: 180 }Test with the longest label and tallest content
During development, test the layout using the longest expected category name and the tallest expected content stack (title + subtitle + chart + footnote), not only the current sample data. Verify that the last x-axis label is fully visible and that footnotes and no-data messages remain visible.
Coloring Bar Charts by Value
A colorscale only affects a Plotly bar trace when the trace carries its own colour array. All of the properties below (`color`, `colorscale`, `cmin`, `cmax`, `showscale`, `colorbar`) live inside `marker` on the trace object.
Required pattern
(function () {
const COLOR_PADDING_FACTOR = 0.15;
const MIN_COLOR_PADDING = 0.5;
const minValue = Math.min(...values);
const maxValue = Math.max(...values);
const span = maxValue - minValue || 1;
const colorPadding = Math.max(span * COLOR_PADDING_FACTOR, MIN_COLOR_PADDING);
const trace = {
type: "bar",
x: names,
y: values,
marker: {
color: values, // ← REQUIRED: without this the colorscale is inert
colorscale: "Reds",
cmin: minValue - colorPadding,
cmax: maxValue + colorPadding,
showscale: true,
line: {
color: "#333333",
width: 1
},
colorbar: {
title: { text: "PET (\u00B0C)" },
thickness: 14,
len: 0.8
}
}
};
Plotly.newPlot('chart', [trace], {
margin: { r: 70 }
});
})();The critical property is `marker.color`. Without it, `colorscale`, `cmin`, and `cmax` have no visible effect and the bars render in the default Plotly blue. Declaring `colorscale: "Reds"` alone is a **silent no-op**—there is no error message, no console warning. The chart simply renders in uniform blue. Misspelling `color` as `colors` has the same effect.
Array length must match
The color array length must match the data array length. A color array that is too short can produce black or unexpected final bars.
Index alignment
Ensure that `names[i]` corresponds to `values[i]` for every index `i`. A silent off-by-one shift (e.g. caused by filtering one array but not the other) produces a chart where every bar displays the wrong category's value. Verify alignment by checking that the highest value belongs to the expected category.
// Filter by index pair to preserve alignment
const cleanNames = [];
const cleanValues = [];
for (let i = 0; i < names.length; i++) {
if (values[i] != null && isFinite(values[i])) {
cleanNames.push(names[i]);
cleanValues.push(values[i]);
}
}
// Verify: cleanNames.length === cleanValues.lengthNote: `isNaN(null)` returns `false` in JavaScript, so always use `!= null && isFinite(...)` rather than just `isNaN(...)`.
Sort paired objects, not separate arrays
Do not sort the names array and the values array independently. Build paired objects first, sort those, then destructure:
const rows = [];
for (let i = 0; i < names.length; i++) {
if (values[i] != null && isFinite(values[i])) {
rows.push({ name: names[i], value: values[i] });
}
}
rows.sort((a, b) => b.value - a.value);
const sortedNames = rows.map((r) => r.name);
const sortedValues = rows.map((r) => r.value);Do not assume identical row ordering
Two independent dynamic TQL tags (one for names, one for values) are not guaranteed to return rows in the same order. Always join by index pair or by item ID, and verify alignment before plotting.
Continuous data needs continuous encoding
For continuous quantitative data, use a continuous colorscale. Do not assign a fixed positional palette (first bar always red, second always blue, …) unless position itself is meaningful. Positional coloring becomes misleading when bars are sorted by value.
Align the color metaphor with the metric
For heat stress, use warmer colors for higher values and cooler colors for lower values. The color encoding should reinforce, not contradict, the data story.
Add a colorbar
The colorbar is declared inside `trace.marker` (see the block above). Include the measurement unit in the colorbar title. Reserve right margin on the layout object so it does not overlap the bars:
Plotly.newPlot('chart', [trace], {
margin: { r: 70 }
});Categorical coloring
If you are using discrete categories rather than a continuous scale, enable a legend on the trace object:
{
type: "bar",
x: names,
y: values,
showlegend: true
}Make sure the legend entries explain what each colour means.
Do not rely on color alone
Color should support the data, not replace it. Also provide value labels, tooltips, or a table when precise values matter.
Choosing Color Domain Bounds
Even when `marker.color` is present, the colour domain can still be misleading.
The minimum-value problem
Sequential scales such as "Reds" start with a very light, near-white colour. If `cmin` equals the data minimum exactly, the lowest value maps to that near-white end and can look like missing data. This is the single most common color-related defect in production panels.
Pad the lower bound
Compute padded bounds, then pass them to the trace's marker:
(function () {
const COLOR_PADDING_FACTOR = 0.15;
const MIN_COLOR_PADDING = 0.5;
const minValue = Math.min(...values);
const maxValue = Math.max(...values);
const span = maxValue - minValue || 1;
const colorPadding = Math.max(span * COLOR_PADDING_FACTOR, MIN_COLOR_PADDING);
const colorMin = minValue - colorPadding;
const colorMax = maxValue + colorPadding;
const trace = {
type: "bar",
x: names,
y: values,
marker: {
color: values,
colorscale: "Reds",
cmin: colorMin,
cmax: colorMax
}
};
})();Padding keeps the minimum value visibly coloured rather than blending into the background. If the lowest color is still too light against the background, add a thin bar outline (`line: { color: '#333333', width: 1 }`).
Dynamic vs fixed bounds
Prefer dynamic bounds with padding:
// trace.marker
cmin: minValue - padding,
cmax: maxValue + paddingUse fixed (hard-coded) bounds only when:
- the data domain is stable across all Scenarios, Iterations, and timeframes,
- the fixed bounds are documented,
- the fixed bounds are verified to keep every value visible.
Hard-coded bounds become stale when scenarios, iterations, or timeframes change.
Verify extremes
Always check the rendered output to confirm that:
- the minimum value is not near-white,
- the maximum value is not saturated into an unreadable block,
- intermediate values are visually distinguishable,
- the colorbar gradient matches the actual bar colours.
Background Opacity and Contrast
Panels render over a 3D map. A transparent or semi-transparent background makes axis labels, titles, and bar values illegible.
Opaque background
Set both `paper_bgcolor` and `plot_bgcolor` to a solid, high-contrast fill on the layout object:
Plotly.newPlot('chart', [trace], {
paper_bgcolor: "rgba(255,255,255,0.95)",
plot_bgcolor: "rgba(255,255,255,0.95)"
});Font colour
Default Plotly fonts are dark grey/black, which works well on a light background. If you use a dark background, switch to light fonts:
// layout
font: { color: "#ffffff" },
xaxis: { tickfont: { color: "#ffffff" } },
yaxis: { tickfont: { color: "#ffffff" } }Subtitle and footnote contrast
Apply the same principle to the HTML `<h2>`, `<p>`, and `.footnote` elements via inline styles or a scoped `<style>` block. Low-contrast text over the 3D map is a common readability defect.
Check contrast for both light and dark map backgrounds. Test the panel in the actual viewer, not only in isolation.
Full details: Background and contrast.
Encoding Special Characters in JavaScript Strings
JavaScript strings are not HTML. HTML entities such as `°` or `°` are **not** decoded inside JavaScript string literals and will render literally.
Incorrect
// WRONG – entity inside a JS string
const unit = "°C";
const yAxisTitle = "Average PET (°C)";
const hoverTemplate = "%{x}: %{y:.1f} °C";This renders as: `41.8 °C`
Correct
Use a Unicode escape or the literal UTF-8 character:
// Option 1: Unicode escape
const degree = "\u00B0";
const unit = degree + "C";
const yAxisTitle = "Average PET (" + unit + ")";
const hoverTemplate = "%{x}: %{y:.1f} " + unit + "C";
// Option 2: Literal UTF-8
const unit = "°C";HTML entities are appropriate only in HTML text nodes (e.g. the subtitle `<p>`), never inside `<script>` strings passed to Plotly.
Where to check
After rendering, verify that none of the following contain a literal `°`, `°`, or similar entity text:
- bar value labels (`text`),
- tooltip / hover template,
- y-axis title,
- colorbar title,
- subtitle,
- footnote.
Full details: Character encoding.
Hover Templates and Tooltips
Configure the hover template on the trace to show the category, value, and unit:
{
type: "bar",
x: names,
y: values,
hovertemplate: "%{x}<br>Avg PET: %{y:.1f}\u00B0C<extra></extra>"
}- Use `\u00B0` (or the literal `°`) for the degree sign—never `°`.
- Keep the unit consistent with the axis title, bar labels, and colorbar title.
- The `<extra></extra>` tag suppresses the default trace-name box.
TQL Clause Compatibility (X vs Y)
The choice between `X` and `Y` clauses affects the shape of the JavaScript array received by the panel.
| Clause family | Result shape | Typical use |
|---|---|---|
| `X`, `XA`, `XK`, `XC` | flat array | simple bar charts, category lists, one value per item |
| `Y`, `YA`, `YK`, `YC` | array of arrays | matrices, per-item time series, heatmaps |
Critical rule: For a simple bar chart with one value per category, use the **same clause family** for both the category names and the values:
// CORRECT – both X-clause → flat arrays
const names = [$SELECT_NAME_WHERE_NEIGHBORHOOD_IS_X];
const values = [$SELECT_GRIDAVG_WHERE_NEIGHBORHOOD_IS_X_AND_GRIDTYPE_IS_HEAT_STRESS_AND_RESULTTYPE_IS_PET_AND_TIMEFRAME_IS_0];// WRONG – X-clause names + Y-clause values → flat + nested mismatch
const names = [$SELECT_NAME_WHERE_NEIGHBORHOOD_IS_X];
const values = [$SELECT_GRIDAVG_WHERE_NEIGHBORHOOD_IS_Y_AND_GRIDTYPE_IS_HEAT_STRESS_AND_RESULTTYPE_IS_PET];Mixing an X-clause name array with a Y-clause value array feeds Plotly a nested y-series and the chart renders blank.
Caution: Query Tool masks the Y-clause bug
The Query Tool and the `execute` API endpoint *display* Y-clause results flattened, which can mask this bug during development. Judge tag shape by the substitution semantics above (X → flat, Y → array-of-arrays), not by the tool's pretty-printed output.
Static binding only
Do **not** construct TQL queries dynamically in JavaScript (e.g. string concatenation + `fetch('/api/session/query/')`). Use static `$SELECT_…$` tags that the platform evaluates at render time. Runtime fetching is a **FATAL** violation and the root cause of blank-panel failures.
Full details: Static TQL data binding, TQL, X (TQL), Y (TQL).
Overlay Coupling and Timeframe Disclosure
When the chart values come from a grid overlay, the panel should be coupled to that overlay so it activates when the panel opens. The TQL query, the coupled overlay, and the subtitle should all refer to the same source. Pin the timeframe explicitly in the TQL tag or state it concretely in the subtitle (e.g. "02 Aug 2013, last iteration"). A generic phrase such as "most recent timeframe" is insufficient; use the concrete date.
Full details: Overlay, timeframe, and scenario coupling, Timeframe (TQL Param).
Error Handling and No-Data Messages
Panel JavaScript should fail visibly, not silently. Wrap chart initialisation in a `try/catch` block:
(function () {
const container = document.getElementById("chart");
if (!container) {
return;
}
try {
if (!rows.length) {
throw new Error("No data available");
}
Plotly.newPlot(container, [trace], layout);
} catch (error) {
container.innerHTML =
"<p style='color:#c00;padding:20px;'>Unable to render chart. Please check the data source.</p>";
}
})();Before plotting, validate:
- the container exists,
- the category array is not empty,
- the value array is not empty,
- category and value arrays have the same length,
- values are finite numbers,
- axis minima and maxima are finite.
Guard against `Math.min` and `Math.max` being called on empty arrays. A no-data state should be a designed part of the panel, not an accidental blank box.
Full details: Robustness, error handling, and code quality.
Unit Consistency
The measurement unit (e.g. `°C`, `dB(A)`, `ppm`) should appear consistently in:
- the y-axis title,
- bar value labels,
- hover / tooltip template,
- colorbar title,
- subtitle,
- footnote.
Define the unit once and reuse it:
const UNIT = "\u00B0C";
// then reference UNIT everywhereThis prevents subtle inconsistencies (e.g. `°C` in the axis but `deg C` in the tooltip). Avoid mixing formats such as `C`, `°C`, and `degC` within the same panel.
Verify the Rendered Image (MANDATORY)=
Source code can look correct while the rendered chart still exhibits a defect. This is the single most reliable way to catch silent failures (inert colorscale, clipped labels, near-white minimum bar, literal entity text). **Rendered-image inspection is mandatory, not optional.** Before marking a panel complete:
- Open the panel in the viewer (`web/panel.html?id=…`) and inspect the rendered image.
- Confirm all x-axis category labels are fully visible (especially the last one).
- Confirm the minimum-value bar is visibly coloured (not gray/white).
- Confirm no literal `°` or `°` text appears anywhere.
- Confirm the chart is not blank and no JS error is displayed.
- Confirm the footnote (if present) and no-data message are not clipped.
- Confirm the colorbar gradient matches the actual bar colours.
- Confirm the title and subtitle are visible and legible.
A panel whose code passes review but whose rendered image shows a defect is not ready for delivery.
See QA checklist for the full rendered-image checklist.
Quick-Reference Checklist
Before shipping a Plotly chart panel, verify:
| Check | Pass criteria |
|---|---|
| DOM order | title → subtitle → chart div → footnote (optional) → script |
| Height budget | chart div + title + subtitle + footnote + padding ≤ panel height |
| Width budget | colorbar margin + label margins accounted for |
| Single title | only one of HTML `<h2>` or `layout.title`, not both |
| Axis range | fitted to data (no zero baseline for narrow bands, no over-wide range); truncation disclosed (optional) |
| X-axis labels | all visible; tested with longest expected name and tallest content stack |
| Index alignment | names[i] corresponds to values[i] for all i; arrays filtered by index pair |
| marker.color | present and bound to the numeric value array; length matches data |
| Color domain | cmin padded below data minimum; cmax padded above data maximum |
| Colorbar | present, titled with unit, right margin reserved |
| Background | opaque (≥ 90 % alpha); font contrast verified over 3D map |
| Degree sign | `\u00B0` or literal `°` in JS strings; no `°` |
| TQL clauses | same clause family (X/X or Y/Y) for names and values; static tags only (no runtime fetch) |
| Error handling | try/catch present; empty-data guard; no-data message styled |
| Units | consistent across axis, labels, tooltip, colorbar, subtitle |
| Config | platform default applied (explicit or implicit); non-default overrides documented |
| No CDN script | no external Plotly `<script>` tag; no `window.load` gate |
| Orientation | vertical (column) bars preferred; horizontal only when labels require it |
| JS conventions | `const`/`let` (not `var`); IIFE-scoped; named constants; no global leaks |
| Source formatting | indented, multi-line, readable; not minified |
| Rendered image | **inspected (mandatory):** all labels visible, colours correct, no JS error, min bar not gray |
Panel-level checks (overlay coupling, timeframe disclosure, panel name uniqueness, text persistence): QA checklist.
Delivery Gate
A per-category bar-chart panel is ready for delivery only when all of the following chart-specific conditions hold:
FATAL (release blockers)
- Static bracketed TQL tags (no runtime fetch, no CDN, no `window.load` gate).
- Names pulled dynamically; X-clause used for both categories and values.
- Stored panel text is not empty (rendered image confirms chart presence).
MAJOR (must fix before delivery)
- `marker.color` bound to values **and** `colorscale`/`cmin`/`cmax` present; `cmin` padded below the minimum.
- y-axis fitted to the data extent (no zero baseline, no over-wide range).
- Chart height = panel height − header; div height = `layout.height`; x-axis labels fully visible.
- Opaque background + explicit dark fonts; single title; unit consistent; degree sign via `\u00B0`.
- `try/catch` + empty-data guard.
- Vertical orientation used (horizontal only with justification).
- `let`/`const` used throughout; code IIFE-scoped; source formatted and readable.
MINOR (should fix; documented if deferred)
- Platform default config applied (explicit or implicit).
- Concrete date in subtitle when timeframe is pinned.
- Colorbar present for continuous scales.
- Truncation footnote present (optional but recommended).
- Worst-case label length tested.
Panel-level sign-off (text persistence, name uniqueness, overlay coupling, timeframe disclosure): Sign-off criteria.