Plotly Chart Guidelines: Difference between revisions

From Tygron Support wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(2 intermediate revisions by the same user not shown)
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]])
|-
|-
| 2
| 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]])
|-
|-
| 3
| 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]])
|-
|-
| 4
| 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]])
|-
| 5
| Zero-baseline or over-wide axis
| All bars look the same height over a narrow data band
| Use a data-driven `yaxis.range` with padding ([[#Axis_Scaling_and_Label_Readability|see axis scaling]])
|}
|}


Line 41: Line 41:
Every Plotly figure is built from up to four arguments passed to `Plotly.newPlot`:
Every Plotly figure is built from up to four arguments passed to `Plotly.newPlot`:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot(divId, traces, layout, config);
Plotly.newPlot(divId, traces, layout, config);
</syntaxhighlight>
</syntaxhighlight>
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 standard setting for Tygron Text Panels is:
* '''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.


<syntaxhighlight>
Examples on this page focus on trace and layout properties. The config argument is omitted unless a non-default override is demonstrated.
const config = { staticPlot: false, displayModeBar: true };
 
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 lang="javascript">
Plotly.newPlot('chart', [trace], layout);
</syntaxhighlight>
</syntaxhighlight>


All code snippets below indicate in a comment whether they target a trace or the layout. See [[How to insert a Plotly Graph]] for the full setup including CSS sizing and the staticPlot flag.
Pass a config object **only** when overriding a default:
 
<syntaxhighlight lang="javascript">
// 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.


===Scoping===
===JavaScript conventions===


Wrap chart code in an IIFE or clearly scoped script block to avoid leaking variables into the global panel scope.
* 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 recommended DOM order for a chart panel is:
The required DOM order for a chart panel is:


# `&lt;h2&gt;` title
# `&lt;h2&gt;` title
# `&lt;p&gt;` subtitle
# `&lt;p&gt;` subtitle
# chart container `&lt;div&gt;`
# chart container `&lt;div&gt;`
# footnote `&lt;p&gt;` (if present)
# footnote `&lt;p&gt;` (optional)
# `&lt;script&gt;` initialisation
# `&lt;script&gt;` 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.


===Total height budget===
===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 (`&lt;h2&gt;`)
| 40 px
|-
| Subtitle (`&lt;p&gt;`)
| 30 px
|-
| Chart `&lt;div&gt;`
| 850 px
|-
| Footnote (optional)
| 30 px
|-
| Safety padding
| 50 px
|-
| '''Total'''
| '''1000 px'''
|}


<syntaxhighlight>
If the footnote is omitted, the chart height can be increased to approximately 910 px.
// Example budget for a 1000 px panel
title        ≈  40 px
subtitle    ≈  30 px
chart div    ≈  850 px  ← leave headroom
footnote    ≈  30 px
padding      ≈  50 px
─────────────────────
total        ≈ 1000 px
</syntaxhighlight>


* Set the chart `&lt;div&gt;` height to `panel_height − (title + subtitle + footnote + padding)`, typically 80–90 % of the panel height.
* Set the chart `&lt;div&gt;` height to `panel_height − (title + subtitle + footnote + padding)`, typically 80–90 % of the panel height.
* Set `layout.height` to the same value as the `&lt;div&gt;` height.
* Set `layout.height` to the **same value** as the `&lt;div&gt;` 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 179:
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.


'''Design requirement: 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.
'''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 195:


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 210:
===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 lang="javascript">
// helper – run once before building the figure
(function () {
const minValue = Math.min(...values);
  const AXIS_PADDING_FACTOR = 0.15;
const maxValue = Math.max(...values);
  const MIN_AXIS_PADDING = 0.5;
const span = maxValue - minValue;
const padding = Math.max(span * 0.15, 0.5);


const yMin = minValue - padding;
  const minValue = Math.min(...values);
const yMax = maxValue + padding;
  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>


Then set the range on the layout object:
Then set the range on the layout object:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', [trace], {
  // layout
   yaxis: {
   yaxis: {
     range: [yMin, yMax] // ← layout.yaxis.range
     range: [yMin, yMax]
   }
   }
}, { staticPlot: false, displayModeBar: true });
});
</syntaxhighlight>
</syntaxhighlight>
(The `config` argument is omitted because the platform default is acceptable.)


===Choose dtick sensibly===
===Choose dtick sensibly===
Line 199: Line 243:
`dtick` controls the step between axis ticks. Set it alongside range on the layout object:
`dtick` controls the step between axis ticks. Set it alongside range on the layout object:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', [trace], {
  // layout
   yaxis: {
   yaxis: {
     range: [yMin, yMax],
     range: [yMin, yMax],
     dtick: 1 // ← layout.yaxis.dtick
     dtick: 1
   }
   }
}, { staticPlot: false, displayModeBar: true });
});
</syntaxhighlight>
</syntaxhighlight>


Too many ticks clutter the chart; too few hide structure. Pick a `dtick` that yields roughly 4–10 ticks over the visible range.
Pick a `dtick` that yields roughly 4–10 ticks over the visible range. Too many ticks clutter the chart; too few hide structure.


===Disclose truncation (recommended)===
===Truncation footnote (optional)===


If the axis does not start at zero, it is good practice to add a brief note in the surrounding panel HTML stating the actual starting value:
'''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 lang="html">
&lt;p class="footnote"&gt;
<p class="footnote">
   The y-axis starts at {{yMin}} °C to emphasise differences between categories.
   The y-axis starts at °C to emphasise differences between categories.
&lt;/p&gt;
</p>
</syntaxhighlight>
</syntaxhighlight>


Stating the concrete start value (rather than a generic "zoomed" sentence) prevents readers from misinterpreting bar lengths. This is a recommendation for clarity, not a mandatory field—the chart is acceptable without it as long as the axis is clearly labelled.
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.
 
===Avoid excessively wide ranges===
 
An axis range much wider than the data spread wastes 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. `[31, 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.


===Hardcoded ranges===
===Hardcoded ranges===
Line 239: Line 278:
When precise comparison matters, display values above the bars. These properties belong to the trace object:
When precise comparison matters, display values above the bars. These properties belong to the trace object:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// trace (one element of the traces array)
{
{
   type: "bar",
   type: 'bar',
   x: names,
   x: names,
   y: values,
   y: values,
   text: values.map((v) => v.toFixed(1) + "\u00B0C"),
   text: values.map((v) => v.toFixed(1) + '\u00B0C'),
   textposition: "outside" // ← trace.textposition
   textposition: 'outside'
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 252: Line 290:
Include units in the label string. Ensure the layout top margin is large enough to show outside labels:
Include units in the label string. Ensure the layout top margin is large enough to show outside labels:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', [trace], {
  // layout
   margin: { t: 60 }
   margin: { t: 60 } // ← layout.margin.t
});
}, { staticPlot: false, displayModeBar: true });
</syntaxhighlight>
</syntaxhighlight>


Line 269: Line 306:
Rotated labels need vertical space. Set the bottom margin on the layout object:
Rotated labels need vertical space. Set the bottom margin on the layout object:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', [trace], {
  // layout
   margin: { b: 140 }
   margin: { b: 140 } // ← layout.margin.b
});
}, { staticPlot: false, displayModeBar: true });
</syntaxhighlight>
</syntaxhighlight>


Line 282: Line 318:
Enable automatic margin adjustment on the layout object, where supported:
Enable automatic margin adjustment on the layout object, where supported:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', [trace], {
  // layout
   xaxis: {
   xaxis: {
     automargin: true // ← layout.xaxis.automargin
     automargin: true
   }
   }
}, { staticPlot: false, displayModeBar: true });
});
</syntaxhighlight>
</syntaxhighlight>


Line 297: Line 332:
Set a moderate rotation angle on the layout object:
Set a moderate rotation angle on the layout object:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', [trace], {
  // layout
   xaxis: {
   xaxis: {
     tickangle: -45 // ← layout.xaxis.tickangle
     tickangle: -45
   }
   }
}, { staticPlot: false, displayModeBar: true });
});
</syntaxhighlight>
</syntaxhighlight>


Line 312: Line 346:
Reducing font size can help, but only if labels remain readable. Set the tick font on the layout object:
Reducing font size can help, but only if labels remain readable. Set the tick font on the layout object:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', [trace], {
  // layout
   xaxis: {
   xaxis: {
     tickfont: { size: 11 } // ← layout.xaxis.tickfont.size
     tickfont: { size: 11 }
   }
   }
}, { staticPlot: false, displayModeBar: true });
});
</syntaxhighlight>
</syntaxhighlight>


Line 329: Line 362:
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:
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:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// trace
{
{
   type: "bar",
   type: 'bar',
   x: values, // note: x/y swapped for horizontal bars
   x: values,
   y: names,
   y: names,
   orientation: "h" // ← trace.orientation
   orientation: 'h'
}
}
</syntaxhighlight>
</syntaxhighlight>


When switching to horizontal bars, adjust margin settings accordingly (left margin instead of bottom for rotated labels):
When switching to horizontal bars, swap the axis roles and reserve left margin for category labels:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// layout
// layout
margin: { t: 40, r: 60, b: 40, l: 180 }
margin: { t: 40, r: 70, b: 40, l: 180 }
</syntaxhighlight>
</syntaxhighlight>


Line 356: Line 388:
===Required pattern===
===Required pattern===


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// trace (one element of the traces array)
(function () {
const trace = {
  const COLOR_PADDING_FACTOR = 0.15;
  type: "bar",
  const MIN_COLOR_PADDING = 0.5;
  x: names,
 
  y: values,
  const minValue = Math.min(...values);
  marker: {
  const maxValue = Math.max(...values);
    color: values,         // ← trace.marker.color (CRITICAL – without this the colorscale is inert)
  const span = maxValue - minValue || 1;
    colorscale: "Reds",     // ← trace.marker.colorscale
  const colorPadding = Math.max(span * COLOR_PADDING_FACTOR, MIN_COLOR_PADDING);
    cmin: colorMin,         // ← trace.marker.cmin
 
    cmax: colorMax,         // ← trace.marker.cmax
  const trace = {
    showscale: true,       // ← trace.marker.showscale
    type: 'bar',
    line: {                 // ← optional thin outline for light colors
    x: names,
      color: "#333333",
    y: values,
      width: 1
    marker: {
    },
      color: values,           // ← REQUIRED: without this the colorscale is inert
    colorbar: {             // ← trace.marker.colorbar
      colorscale: 'Reds',
      title: { text: "PET (\u00B0C)" },
      cmin: minValue - colorPadding,
      thickness: 14,
      cmax: maxValue + colorPadding,
      len: 0.8
      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], {
  // layout – reserve right margin for the colorbar
    margin: { r: 70 }
  margin: { r: 70 } // ← layout.margin.r
  });
}, { staticPlot: false, displayModeBar: true });
})();
</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. This failure is completely silent—there is no error message, no console warning. The chart simply renders in uniform blue. Misspelling `color` as `colors` has the same effect.
'''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 396: Line 436:
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.
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.


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// Filter by index pair to preserve alignment
// Filter by index pair to preserve alignment
const cleanNames = [];
const cleanNames = [];
const cleanValues = [];
const cleanValues = [];
for (let i = 0; i < names.length; i++) {
for (let i = 0; i < rawNames.length; i++) {
   if (values[i] != null && isFinite(values[i])) {
   const n = rawNames[i];
     cleanNames.push(names[i]);
  const v = rawValues[i];
     cleanValues.push(values[i]);
  if (n != null && v != null && isFinite(v)) {
     cleanNames.push(String(n));
     cleanValues.push(Number(v));
   }
   }
}
}
// Verify: cleanNames.length === cleanValues.length
</syntaxhighlight>
</syntaxhighlight>


Line 415: Line 456:
Do not sort the names array and the values array independently. Build paired objects first, sort those, then destructure:
Do not sort the names array and the values array independently. Build paired objects first, sort those, then destructure:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
const rows = [];
const rows = [];
for (let i = 0; i < names.length; i++) {
for (let i = 0; i < rawNames.length; i++) {
   if (values[i] != null && isFinite(values[i])) {
   rows.push({ name: rawNames[i], value: rawValues[i] });
    rows.push({ name: names[i], value: values[i] });
  }
}
}
rows.sort((a, b) => b.value - a.value);
rows.sort((a, b) => b.value - a.value);
Line 443: Line 482:
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:
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:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot('chart', [trace], {
Plotly.newPlot('chart', [trace], {
  // layout
   margin: { r: 70 }
   margin: { r: 70 }
}, { staticPlot: false, displayModeBar: true });
});
</syntaxhighlight>
</syntaxhighlight>


Line 454: Line 492:
If you are using discrete categories rather than a continuous scale, enable a legend on the trace object:
If you are using discrete categories rather than a continuous scale, enable a legend on the trace object:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// trace
{
{
   type: "bar",
   type: 'bar',
   x: names,
   x: names,
   y: values,
   y: values,
   showlegend: true // ← trace.showlegend
   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.
===Verify the rendered gradient===
Source code can look correct while the rendered chart still uses default colours. Always inspect the final image. See [[Text Panel Content Guidelines#Quality-assurance_checklist|QA checklist]] for the full rendered-image checklist.


==Choosing Color Domain Bounds==
==Choosing Color Domain Bounds==
Line 480: Line 513:
===The minimum-value problem===
===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.
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===
===Pad the lower bound===
Line 486: Line 519:
Compute padded bounds, then pass them to the trace's marker:
Compute padded bounds, then pass them to the trace's marker:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// helpers
(function () {
const minValue = Math.min(...values);
  const COLOR_PADDING_FACTOR = 0.15;
const maxValue = Math.max(...values);
  const MIN_COLOR_PADDING = 0.5;
const span = maxValue - minValue;
const colorPadding = Math.max(span * 0.15, 0.5);


const colorMin = minValue - colorPadding;
  const minValue = Math.min(...values);
const colorMax = maxValue + colorPadding;
  const maxValue = Math.max(...values);
  const span = maxValue - minValue || 1;
  const colorPadding = Math.max(span * COLOR_PADDING_FACTOR, MIN_COLOR_PADDING);


// trace
  const colorMin = minValue - colorPadding;
const trace = {
  const colorMax = maxValue + colorPadding;
  type: "bar",
 
  x: names,
  const trace = {
  y: values,
    type: 'bar',
  marker: {
    x: names,
    color: values,      // ← trace.marker.color
    y: values,
    colorscale: "Reds", // ← trace.marker.colorscale
    marker: {
    cmin: colorMin,     // ← trace.marker.cmin
      color: values,
    cmax: colorMax       // ← trace.marker.cmax
       colorscale: 'Reds',
   }
      cmin: colorMin,
};
      cmax: colorMax
    }
   };
})();
</syntaxhighlight>
</syntaxhighlight>


Line 516: Line 552:
Prefer dynamic bounds with padding:
Prefer dynamic bounds with padding:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// trace.marker
// trace.marker
cmin: minValue - padding,
cmin: minValue - padding,
Line 547: Line 583:
Set both `paper_bgcolor` and `plot_bgcolor` to a solid, high-contrast fill on the layout object:
Set both `paper_bgcolor` and `plot_bgcolor` to a solid, high-contrast fill on the layout object:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', [trace], {
  // layout
   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)"
});
}, { staticPlot: false, displayModeBar: true });
</syntaxhighlight>
</syntaxhighlight>


Line 559: Line 594:
Default Plotly fonts are dark grey/black, which works well on a light background. If you use a dark background, switch to light fonts:
Default Plotly fonts are dark grey/black, which works well on a light background. If you use a dark background, switch to light fonts:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// layout
// layout
font: { color: "#ffffff" },
font: { color: '#ffffff' },
xaxis: { tickfont: { color: "#ffffff" } },
xaxis: { tickfont: { color: '#ffffff' } },
yaxis: { tickfont: { color: "#ffffff" } }
yaxis: { tickfont: { color: '#ffffff' } }
</syntaxhighlight>
</syntaxhighlight>


Line 580: Line 615:
===Incorrect===
===Incorrect===


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// WRONG – entity inside a JS string
// WRONG – entity inside a JS string
const unit = "&deg;C";
const unit = '&deg;C';
const yAxisTitle = "Average PET (&deg;C)";
const yAxisTitle = 'Average PET (&deg;C)';
const hoverTemplate = "%{x}: %{y:.1f} &deg;C";
const hoverTemplate = '%{x}: %{y:.1f} &deg;C';
</syntaxhighlight>
</syntaxhighlight>


Line 593: Line 628:
Use a Unicode escape or the literal UTF-8 character:
Use a Unicode escape or the literal UTF-8 character:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// Option 1: Unicode escape
// Option 1: Unicode escape
const degree = "\u00B0";
const degree = '\u00B0';
const unit = degree + "C";
const unit = degree + 'C';
const yAxisTitle = "Average PET (" + unit + ")";
const yAxisTitle = 'Average PET (' + unit + ')';
const hoverTemplate = "%{x}: %{y:.1f} " + unit + "C";
const hoverTemplate = '%{x}: %{y:.1f} ' + unit + 'C';


// Option 2: Literal UTF-8
// Option 2: Literal UTF-8
const unit = "°C";
const unit = '°C';
</syntaxhighlight>
</syntaxhighlight>


Line 623: Line 658:
Configure the hover template on the trace to show the category, value, and unit:
Configure the hover template on the trace to show the category, value, and unit:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// trace
{
{
   type: "bar",
   type: 'bar',
   x: names,
   x: names,
   y: values,
   y: values,
   hovertemplate: "%{x}<br>Avg PET: %{y:.1f}\u00B0C<extra></extra>"
   hovertemplate: '%{x}<br>Avg PET: %{y:.1f}\u00B0C'
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 657: Line 691:
'''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:
'''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:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// CORRECT – both X-clause → flat arrays
// CORRECT – both X-clause → flat arrays
const names  = [$SELECT_NAME_WHERE_NEIGHBORHOOD_IS_X];
const names  = [$SELECT_NAME_WHERE_NEIGHBORHOOD_IS_X];
Line 663: Line 697:
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight>
<syntaxhighlight lang="javascript">
// WRONG – X-clause names + Y-clause values → flat + nested mismatch
// WRONG – X-clause names + Y-clause values → flat + nested mismatch
const names  = [$SELECT_NAME_WHERE_NEIGHBORHOOD_IS_X];
const names  = [$SELECT_NAME_WHERE_NEIGHBORHOOD_IS_X];
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 691: Line 725:
Panel JavaScript should fail visibly, not silently. Wrap chart initialisation in a `try/catch` block:
Panel JavaScript should fail visibly, not silently. Wrap chart initialisation in a `try/catch` block:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
const container = document.getElementById("chart");
(function () {
  const container = document.getElementById('chart');


try {
   if (!container) {
   if (!rows.length) {
     return;
     throw new Error("No data available");
   }
   }


   Plotly.newPlot(container, [trace], layout, { staticPlot: false, displayModeBar: true });
   try {
} catch (error) {
    if (!rows.length) {
  container.innerHTML =
      throw new Error('No data available');
    "<p style='color:#c00;padding:20px;'>Unable to render chart. Please check the data source.</p>";
    }
}
 
    Plotly.newPlot(container, [trace], layout);
  } catch (error) {
    container.innerHTML =
      'Unable to render chart. Please check the data source.';
  }
})();
</syntaxhighlight>
</syntaxhighlight>


Line 730: Line 770:
* footnote.
* footnote.


Define the unit string once and reuse it:
Define the unit once and reuse it:


<syntaxhighlight>
<syntaxhighlight lang="javascript">
const UNIT = "\u00B0C";
const UNIT = '\u00B0C';
// then reference UNIT everywhere
// then reference UNIT everywhere
</syntaxhighlight>
</syntaxhighlight>


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 `&deg;` or `&#176;` 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 (recommended)
| 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
| `{ staticPlot: false, displayModeBar: true }` passed to Plotly.newPlot
| 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.
* `config: { staticPlot: false, displayModeBar: true }` passed to `Plotly.newPlot`.
* Vertical orientation used (horizontal only with justification).
* Vertical orientation used (horizontal only with justification).
* Verified via `web/panel.html?id=…` showing both value labels and category labels.
* `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]].


{{article end
{{Article End
|seealso=
|seealso=
* [[Plotly]]
* [[Plotly]]

Latest revision as of 16:27, 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.

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:

  1. `<h2>` title
  2. `<p>` subtitle
  3. chart container `<div>`
  4. footnote `<p>` (optional)
  5. `<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.

  • 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  °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 < rawNames.length; i++) {
  const n = rawNames[i];
  const v = rawValues[i];
  if (n != null && v != null && isFinite(v)) {
    cleanNames.push(String(n));
    cleanValues.push(Number(v));
  }
}

Note: `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 < rawNames.length; i++) {
  rows.push({ name: rawNames[i], value: rawValues[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 + padding

Use 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 = '&deg;C';
const yAxisTitle = 'Average PET (&deg;C)';
const hoverTemplate = '%{x}: %{y:.1f} &deg;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'
}
  • 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 =
      'Unable to render chart. Please check the data source.';
  }
})();

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 everywhere

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 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.

Template:Article End