Plotly Chart Guidelines: Difference between revisions

From Tygron Support wiki
Jump to navigation Jump to search
No edit summary
Line 9: Line 9:
</syntaxhighlight>
</syntaxhighlight>


* 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, and paper_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 (optional)* – controls interactivity: which toolbar buttons appear, drag mode, static vs. interactive rendering, etc.
* '''config''' (optional) – controls interactivity: which toolbar buttons appear, drag mode, static vs. interactive rendering, etc. For panel charts, set `staticPlot: true` to disable pan/zoom and reduce memory usage.


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


----
===Loading Plotly correctly===


==Axis Scaling for Narrow Data Bands==
[[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.
 
===Scoping===
 
Recommend wrapping chart code in an IIFE or clearly scoped script block to avoid leaking variables into the global panel scope.
 
 
 
==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.
 
===DOM order===
 
The recommended DOM order for a chart panel is:
 
# `<h2>` title
# `<p>` subtitle
# chart container `<div>`
# footnote `<p>`
# `<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.
 
===Total height budget===
 
A panel has a fixed pixel height (e.g. 1000 px). The sum of all elements must fit within that height:
 
<syntaxhighlight copy>
// 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 `<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.
 
A panel that requires scrolling to reveal axis labels or values should be resized or simplified.
 
===Overflow warnings===
 
Warn against `overflow: hidden` containers that can clip axis labels or footnotes. Verify that the last x-axis label is fully visible and that footnotes and no-data messages remain visible.
 
Full details: [[Text Panel Content Guidelines#Safe_DOM_Order_and_Initialization]].
 
 
 
==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.
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.
Line 55: Line 124:
<syntaxhighlight copy>
<syntaxhighlight copy>
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', traces, {
/ layout /
  // layout
yaxis: {
  yaxis: {
range: [yMin, yMax] // ← goes on layout.yaxis
    range: [yMin, yMax] // ← layout.yaxis.range
}
  }
});
});
</syntaxhighlight>
</syntaxhighlight>
Line 64: Line 133:
===Choose dtick sensibly===
===Choose dtick sensibly===


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 copy>
<syntaxhighlight copy>
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', traces, {
/ layout /
  // layout
yaxis: {
  yaxis: {
range: [yMin, yMax],
    range: [yMin, yMax],
dtick: 1 // ← layout.yaxis.dtick
    dtick: 1 // ← layout.yaxis.dtick
}
  }
});
});
</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.
Too many ticks clutter the chart; too few hide structure. Pick a `dtick` that yields roughly 4–10 ticks over the visible range.


===Disclose truncation===
===Disclose truncation===


If the axis does not start at zero, add a footnote in the surrounding panel HTML:
If the axis does not start at zero, add a footnote in the surrounding panel HTML that states the actual starting value:


<syntaxhighlight copy>
<syntaxhighlight copy>
<p class="footnote">
<p class="footnote">
The y-axis is zoomed to emphasise differences between categories.
  The y-axis starts at {{yMin}} °C to emphasise differences between categories.
</p>
</p>
</syntaxhighlight>
</syntaxhighlight>


This prevents readers from misinterpreting bar lengths.
Stating the concrete start value (rather than a generic "zoomed" sentence) prevents readers from misinterpreting bar lengths.


===Avoid excessively wide ranges===
===Avoid excessively wide ranges===


An axis range much wider than the data spread wastes space and reduces comparability. If the data spread is small, do not use a range many times larger than the spread unless there is a strong analytical reason.
An axis range much wider than the data spread wastes space and reduces comparability. If the data spread is small, do not use a range many times larger than the spread unless there is a strong analytical reason.
===Hardcoded ranges===
Warn against hardcoded axis ranges that may clip future data. If a fixed range is used, require justification and a footnote explaining the chosen bounds.
===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===
===Value labels===
Line 99: Line 176:


<syntaxhighlight copy>
<syntaxhighlight copy>
/ trace (one element of the traces array) /
// trace (one element of the traces array)
{
{
type: "bar",
  type: "bar",
x: names,
  x: names,
y: values,
  y: values,
text: values.map(function(v){ return v.toFixed(1) + "°C"; }),
  text: values.map(function(v){ return v.toFixed(1) + "\u00B0C"; }),
textposition: "outside" // ← trace.textposition
  textposition: "outside" // ← trace.textposition
}
}
</syntaxhighlight>
</syntaxhighlight>


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 copy>
<syntaxhighlight copy>
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', traces, {
/ layout /
  // layout
margin: { t: 60 } // ← layout.margin.t
  margin: { t: 60 } // ← layout.margin.t
});
});
</syntaxhighlight>
</syntaxhighlight>


See Text Panel Content Guidelines#Encoding_Special_Characters_in_JavaScript_Strings for details on encoding special characters in JavaScript strings.
Reserve top margin when displaying a y-axis title.
 
===Horizontal bar charts===
 
For horizontal bar charts, scale the value axis to the data extent and reserve space for category labels on the y-axis.
 
See [[Text Panel Content Guidelines#Encoding_Special_Characters_in_JavaScript_Strings]] for details on encoding special characters in JavaScript strings.
 


----


==Preventing Clipped Category Labels==
==Preventing Clipped Category Labels==
Line 132: Line 215:
<syntaxhighlight copy>
<syntaxhighlight copy>
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', traces, {
/ layout /
  // layout
margin: { b: 140 } // ← layout.margin.b
  margin: { b: 140 } // ← layout.margin.b
});
});
</syntaxhighlight>
</syntaxhighlight>


If labels are still clipped, increase the bottom margin further.
If labels are still clipped, increase the bottom margin further—within the total height budget described above.


===Use automargin===
===Use automargin===
Line 145: Line 228:
<syntaxhighlight copy>
<syntaxhighlight copy>
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', traces, {
/ layout /
  // layout
xaxis: {
  xaxis: {
automargin: true // ← layout.xaxis.automargin
    automargin: true // ← layout.xaxis.automargin
}
  }
});
});
</syntaxhighlight>
</syntaxhighlight>
Line 160: Line 243:
<syntaxhighlight copy>
<syntaxhighlight copy>
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', traces, {
/ layout /
  // layout
xaxis: {
  xaxis: {
tickangle: -45 // ← layout.xaxis.tickangle
    tickangle: -45 // ← layout.xaxis.tickangle
}
  }
});
});
</syntaxhighlight>
</syntaxhighlight>
Line 175: Line 258:
<syntaxhighlight copy>
<syntaxhighlight copy>
Plotly.newPlot('chart', traces, {
Plotly.newPlot('chart', traces, {
/ layout /
  // layout
xaxis: {
  xaxis: {
tickfont: { size: 11 } // ← layout.xaxis.tickfont.size
    tickfont: { size: 11 } // ← layout.xaxis.tickfont.size
}
  }
});
});
</syntaxhighlight>
</syntaxhighlight>
Line 191: Line 274:


<syntaxhighlight copy>
<syntaxhighlight copy>
/ trace /
// trace
{
{
type: "bar",
  type: "bar",
x: values, // note: x/y swapped for horizontal bars
  x: values, // note: x/y swapped for horizontal bars
y: names,
  y: names,
orientation: "h" // ← trace.orientation
  orientation: "h" // ← trace.orientation
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 202: Line 285:
When switching to horizontal bars, adjust margin settings accordingly (left margin instead of bottom for rotated labels).
When switching to horizontal bars, adjust margin settings accordingly (left margin instead of bottom for rotated labels).


===Test with the longest label===
===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.


During development, test the layout using the longest expected category name, not only the current sample data.


----


==Coloring Bar Charts by Value==
==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.
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===
===Required pattern===


<syntaxhighlight copy>
<syntaxhighlight copy>
/ trace (one element of the traces array) /
// trace (one element of the traces array)
var trace = {
var trace = {
type: "bar",
  type: "bar",
x: names,
  x: names,
y: values,
  y: values,
marker: {
  marker: {
color: values, // ← trace.marker.color (critical!)
    color: values,         // ← trace.marker.color (critical!)
colorscale: "Reds", // ← trace.marker.colorscale
    colorscale: "Reds",     // ← trace.marker.colorscale
cmin: colorMin, // ← trace.marker.cmin
    cmin: colorMin,         // ← trace.marker.cmin
cmax: colorMax, // ← trace.marker.cmax
    cmax: colorMax,         // ← trace.marker.cmax
showscale: true, // ← trace.marker.showscale
    showscale: true,       // ← trace.marker.showscale
colorbar: { // ← trace.marker.colorbar
    line: {                // ← optional thin outline for light colors
title: { text: "PET (°C)" },
      color: "#333333",
thickness: 14,
      width: 1
len: 0.8
    },
}
    colorbar: {             // ← trace.marker.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 /
  // layout – reserve right margin for the colorbar
margin: { r: 70 } // ← layout.margin.r
  margin: { r: 70 } // ← layout.margin.r
});
});
</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 colour.
The critical property is `marker.color`. Without it, `colorscale`, `cmin`, and `cmax` have no visible effect and the bars render in the default colour.
 
===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.


===Continuous data needs continuous encoding===
===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.
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===
===Add a colorbar===


The colorbar is declared inside trace.marker (see the block above). 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 copy>
<syntaxhighlight copy>
Plotly.newPlot('chart', [trace], {
Plotly.newPlot('chart', [trace], {
/ layout /
  // layout
margin: { r: 70 }
  margin: { r: 70 }
});
});
</syntaxhighlight>
</syntaxhighlight>
Line 262: Line 357:


<syntaxhighlight copy>
<syntaxhighlight copy>
/ trace /
// trace
{
{
type: "bar",
  type: "bar",
x: names,
  x: names,
y: values,
  y: values,
showlegend: true // ← trace.showlegend
  showlegend: true // ← trace.showlegend
}
}
</syntaxhighlight>
</syntaxhighlight>


Make sure the legend entries explain what each colour means.
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.


===Verify the rendered gradient===
===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 for the full rendered-image checklist.
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]] for the full rendered-image checklist.
 


----


==Choosing Color Domain Bounds==
==Choosing Color Domain Bounds==


Even when marker.color is present, the colour domain can still be misleading.
Even when `marker.color` is present, the colour domain can still be misleading.


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


===Pad the lower bound===
===Pad the lower bound===
Line 301: Line 400:
var colorMax = maxValue + colorPadding;
var colorMax = maxValue + colorPadding;


/ trace /
// trace
var trace = {
var trace = {
type: "bar",
  type: "bar",
x: names,
  x: names,
y: values,
  y: values,
marker: {
  marker: {
color: values, // ← trace.marker.color
    color: values,       // ← trace.marker.color
colorscale: "Reds", // ← trace.marker.colorscale
    colorscale: "Reds", // ← trace.marker.colorscale
cmin: colorMin, // ← trace.marker.cmin
    cmin: colorMin,     // ← trace.marker.cmin
cmax: colorMax // ← trace.marker.cmax
    cmax: colorMax       // ← trace.marker.cmax
}
  }
};
};
</syntaxhighlight>
</syntaxhighlight>


Padding keeps the minimum value visibly coloured rather than blending into the background.
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===
===Dynamic vs fixed bounds===
Line 343: Line 442:
* intermediate values are visually distinguishable,
* intermediate values are visually distinguishable,
* the colorbar gradient matches the actual bar colours.
* 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:
<syntaxhighlight copy>
Plotly.newPlot('chart', traces, {
  // layout
  paper_bgcolor: "rgba(255,255,255,0.95)",
  plot_bgcolor: "rgba(255,255,255,0.95)"
});
</syntaxhighlight>
===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:
<syntaxhighlight copy>
// layout
font: { color: "#ffffff" },
xaxis: { tickfont: { color: "#ffffff" } },
yaxis: { tickfont: { color: "#ffffff" } }
</syntaxhighlight>
===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: [[Text Panel Content Guidelines#Size_and_Content_Fit]].
==Encoding Special Characters in JavaScript Strings==
JavaScript strings are not HTML. HTML entities such as `&deg;` or `&#176;` are **not** decoded inside JavaScript string literals and will render literally.
===Incorrect===
<syntaxhighlight copy>
// WRONG – entity inside a JS string
const unit = "&deg;C";
const yAxisTitle = "Average PET (&deg;C)";
const hoverTemplate = "%{x}: %{y:.1f} &deg;C";
</syntaxhighlight>
This renders as: `41.8 &deg;C`
===Correct===
Use a Unicode escape or the literal UTF-8 character:
<syntaxhighlight copy>
// 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";
</syntaxhighlight>
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 `&deg;`, `&#176;`, or similar entity text:
* bar value labels (`text`),
* tooltip / hover template,
* y-axis title,
* colorbar title,
* subtitle,
* footnote.
Full details: [[Text Panel Content Guidelines#Encoding_Special_Characters_in_JavaScript_Strings]].
==Hover Templates and Tooltips==
Configure the hover template on the trace to show the category, value, and unit:
<syntaxhighlight copy>
// trace
{
  type: "bar",
  x: names,
  y: values,
  hovertemplate: "%{x}<br>Avg PET: %{y:.1f}\u00B0C<extra></extra>"
}
</syntaxhighlight>
* Use `\u00B0` (or the literal `°`) for the degree sign—never `&deg;`.
* 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.
{|class=wikitable
! 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:
<syntaxhighlight copy>
// 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];
</syntaxhighlight>
<syntaxhighlight copy>
// 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];
</syntaxhighlight>
Mixing an X-clause name array with a Y-clause value array feeds Plotly a nested y-series and the chart renders blank.
Do **not** construct TQL queries dynamically in JavaScript (e.g. string concatenation + `fetch`). Use static `$SELECT_…$` tags that the platform evaluates at render time.
Full details: [[Text Panel Content Guidelines#Choosing_X_and_Y_Clauses_for_Chart_Series]], [[TQL]], [[X (TQL)]], [[Y (TQL)]].
==Overlay Coupling and Timeframe Disclosure==
===Overlay coupling===
When the chart values come from a grid overlay, couple the panel 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.
If the panel is not coupled, either set the panel's overlay property or reword the subtitle so it does not imply a live overlay connection.
===Timeframe disclosure===
* Pin the timeframe explicitly in the TQL tag when the panel refers to a specific date or simulation step.
* Or clearly state in the subtitle that the panel uses the last timeframe by default.
* Show the resolved date or time when available.
* Keep the subtitle consistent with the TQL query.
Example subtitle:
<syntaxhighlight copy>
<p>Heat Stress (PET) per Neighborhood – 02 Aug 2013, last iteration.</p>
</syntaxhighlight>
Full details: [[Text Panel Content Guidelines#Timeframe_Behavior_in_Panels]], [[Text Panel Content Guidelines#Overlay_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:
<syntaxhighlight copy>
const container = document.getElementById("chart");
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>";
}
</syntaxhighlight>
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: [[Text Panel Content Guidelines#Error_Handling_and_No-Data_Messages]].
==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 string once and reuse it:
<syntaxhighlight copy>
const UNIT = "\u00B0C";
// then reference UNIT everywhere
</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.
==Quick-Reference Checklist==
Before shipping a Plotly chart panel, verify:
{|class=wikitable
! Check
! Pass criteria
|-
| DOM order
| title → subtitle → chart div → footnote → script
|-
| Height budget
| chart div + title + subtitle + footnote + padding ≤ panel height
|-
| Axis range
| fitted to data (no zero baseline for narrow bands); truncation disclosed with actual start value
|-
| X-axis labels
| all visible; tested with longest expected name and tallest content stack
|-
| 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 `&deg;`
|-
| TQL clauses
| same clause family (X/X or Y/Y) for names and values; static tags only
|-
| Overlay coupling
| panel coupled to the source grid overlay
|-
| Timeframe
| pinned in TQL or stated in subtitle; date shown
|-
| Error handling
| try/catch present; empty-data guard; no-data message styled
|-
| Units
| consistent across axis, labels, tooltip, colorbar, subtitle
|-
| No CDN script
| no external Plotly `<script>` tag; no `window.load` gate
|-
| Rendered image
| inspected: all labels visible, colours correct, no JS error
|}
Full QA procedure: [[Text Panel Content Guidelines#Quality_assurance]].


{{article end
{{article end
Line 350: Line 737:
* [[JavaScript]]
* [[JavaScript]]
* [[Panel]]
* [[Panel]]
* [[Panel properties]]
* [[TQL]]
* [[X (TQL)]]
* [[Y (TQL)]]
* [[Timeframe (TQL Param)]]
* [[Heat Stress]]
|howtos=
|howtos=
* [[How to insert a Plotly Graph]]
* [[How to insert a Plotly Graph]]
* [[How to plot neighborhood demographics in a pie chart]]
* [[How to plot neighborhood demographics in a pie chart]]
}}
}}

Revision as of 12:04, 1 December 2026

This page contains tips on adding a Plotly Chart to a Text Panel content successfully.

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 (optional) – controls interactivity: which toolbar buttons appear, drag mode, static vs. interactive rendering, etc. For panel charts, set `staticPlot: true` to disable pan/zoom and reduce memory usage.

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.

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.

Scoping

Recommend wrapping chart code in an IIFE or clearly scoped script block to avoid leaking variables into the global panel scope.


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.

DOM order

The recommended DOM order for a chart panel is:

  1. `

    ` title

  2. `

    ` subtitle

  3. chart container `
    `
  4. footnote `

    `

  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.

Total height budget

A panel has a fixed pixel height (e.g. 1000 px). The sum of all elements must fit within that height:

// 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
  • Set the chart `
    ` height to `panel_height − (title + subtitle + footnote + padding)`, typically 80–90 % of the panel height.
  • Set `layout.height` to the same value as the `
    ` 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.

A panel that requires scrolling to reveal axis labels or values should be resized or simplified.

Overflow warnings

Warn against `overflow: hidden` containers that can clip axis labels or footnotes. Verify that the last x-axis label is fully visible and that footnotes and no-data messages remain visible.

Full details: Text Panel Content Guidelines#Safe_DOM_Order_and_Initialization.


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.

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.

Data-driven range

First compute the bounds from your data:

// helper – run once before building the figure
const minValue = Math.min.apply(null, values);
const maxValue = Math.max.apply(null, values);
const span = maxValue - minValue;
const padding = Math.max(span * 0.15, 0.5);

const yMin = minValue - padding;
const yMax = maxValue + padding;

Then set the range on the layout object:

Plotly.newPlot('chart', traces, {
  // layout
  yaxis: {
    range: [yMin, yMax] // ← layout.yaxis.range
  }
});

Choose dtick sensibly

`dtick` controls the step between axis ticks. Set it alongside range on the layout object:

Plotly.newPlot('chart', traces, {
  // layout
  yaxis: {
    range: [yMin, yMax],
    dtick: 1 // ← layout.yaxis.dtick
  }
});

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

Disclose truncation

If the axis does not start at zero, add a footnote in the surrounding panel HTML that states the actual starting value:

<p class="footnote">
  The y-axis starts at {{yMin}} °C to emphasise differences between categories.
</p>

Stating the concrete start value (rather than a generic "zoomed" sentence) prevents readers from misinterpreting bar lengths.

Avoid excessively wide ranges

An axis range much wider than the data spread wastes space and reduces comparability. If the data spread is small, do not use a range many times larger than the spread unless there is a strong analytical reason.

Hardcoded ranges

Warn against hardcoded axis ranges that may clip future data. If a fixed range is used, require justification and a footnote explaining the chosen bounds.

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:

// trace (one element of the traces array)
{
  type: "bar",
  x: names,
  y: values,
  text: values.map(function(v){ return v.toFixed(1) + "\u00B0C"; }),
  textposition: "outside" // ← trace.textposition
}

Include units in the label string. Ensure the layout top margin is large enough to show outside labels:

Plotly.newPlot('chart', traces, {
  // layout
  margin: { t: 60 } // ← layout.margin.t
});

Reserve top margin when displaying a y-axis title.

Horizontal bar charts

For horizontal bar charts, scale the value axis to the data extent and reserve space for category labels on the y-axis.

See Text Panel Content Guidelines#Encoding_Special_Characters_in_JavaScript_Strings for details on encoding special characters in JavaScript strings.


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', traces, {
  // layout
  margin: { b: 140 } // ← layout.margin.b
});

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', traces, {
  // layout
  xaxis: {
    automargin: true // ← layout.xaxis.automargin
  }
});

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', traces, {
  // layout
  xaxis: {
    tickangle: -45 // ← layout.xaxis.tickangle
  }
});

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', traces, {
  // layout
  xaxis: {
    tickfont: { size: 11 } // ← layout.xaxis.tickfont.size
  }
});

Abbreviate long names

If full names are impractical, use controlled abbreviations and explain them in a footnote or tooltip.

Use horizontal bars

Horizontal bar charts give long category names more room because the labels move to the y-axis. Change the orientation on the trace object:

// trace
{
  type: "bar",
  x: values, // note: x/y swapped for horizontal bars
  y: names,
  orientation: "h" // ← trace.orientation
}

When switching to horizontal bars, adjust margin settings accordingly (left margin instead of bottom for rotated labels).

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

// trace (one element of the traces array)
var trace = {
  type: "bar",
  x: names,
  y: values,
  marker: {
    color: values,          // ← trace.marker.color (critical!)
    colorscale: "Reds",     // ← trace.marker.colorscale
    cmin: colorMin,         // ← trace.marker.cmin
    cmax: colorMax,         // ← trace.marker.cmax
    showscale: true,        // ← trace.marker.showscale
    line: {                 // ← optional thin outline for light colors
      color: "#333333",
      width: 1
    },
    colorbar: {             // ← trace.marker.colorbar
      title: { text: "PET (\u00B0C)" },
      thickness: 14,
      len: 0.8
    }
  }
};

Plotly.newPlot('chart', [trace], {
  // layout – reserve right margin for the colorbar
  margin: { r: 70 } // ← layout.margin.r
});

The critical property is `marker.color`. Without it, `colorscale`, `cmin`, and `cmax` have no visible effect and the bars render in the default colour.

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.

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], {
  // layout
  margin: { r: 70 }
});

Categorical coloring

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

// trace
{
  type: "bar",
  x: names,
  y: values,
  showlegend: true // ← trace.showlegend
}

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.

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 for the full rendered-image checklist.


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.

Pad the lower bound

Compute padded bounds, then pass them to the trace's marker:

// helpers
var minValue = Math.min.apply(null, values);
var maxValue = Math.max.apply(null, values);
var span = maxValue - minValue;
var colorPadding = Math.max(span * 0.15, 0.5);

var colorMin = minValue - colorPadding;
var colorMax = maxValue + colorPadding;

// trace
var trace = {
  type: "bar",
  x: names,
  y: values,
  marker: {
    color: values,       // ← trace.marker.color
    colorscale: "Reds",  // ← trace.marker.colorscale
    cmin: colorMin,      // ← trace.marker.cmin
    cmax: colorMax       // ← trace.marker.cmax
  }
};

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', traces, {
  // layout
  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 `

`, `

`, 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: Text Panel Content Guidelines#Size_and_Content_Fit.

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 `

`), 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: Text Panel Content Guidelines#Encoding_Special_Characters_in_JavaScript_Strings.


Hover Templates and Tooltips

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

// trace
{
  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.

Do **not** construct TQL queries dynamically in JavaScript (e.g. string concatenation + `fetch`). Use static `$SELECT_…$` tags that the platform evaluates at render time.

Full details: Text Panel Content Guidelines#Choosing_X_and_Y_Clauses_for_Chart_Series, TQL, X (TQL), Y (TQL).


Overlay Coupling and Timeframe Disclosure

Overlay coupling

When the chart values come from a grid overlay, couple the panel 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.

If the panel is not coupled, either set the panel's overlay property or reword the subtitle so it does not imply a live overlay connection.

Timeframe disclosure

  • Pin the timeframe explicitly in the TQL tag when the panel refers to a specific date or simulation step.
  • Or clearly state in the subtitle that the panel uses the last timeframe by default.
  • Show the resolved date or time when available.
  • Keep the subtitle consistent with the TQL query.

Example subtitle:

<p>Heat Stress (PET) per Neighborhood – 02 Aug 2013, last iteration.</p>

Full details: Text Panel Content Guidelines#Timeframe_Behavior_in_Panels, Text Panel Content Guidelines#Overlay_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:

const container = document.getElementById("chart");

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: Text Panel Content Guidelines#Error_Handling_and_No-Data_Messages.


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


Quick-Reference Checklist

Before shipping a Plotly chart panel, verify:

Check Pass criteria
DOM order title → subtitle → chart div → footnote → script
Height budget chart div + title + subtitle + footnote + padding ≤ panel height
Axis range fitted to data (no zero baseline for narrow bands); truncation disclosed with actual start value
X-axis labels all visible; tested with longest expected name and tallest content stack
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
Overlay coupling panel coupled to the source grid overlay
Timeframe pinned in TQL or stated in subtitle; date shown
Error handling try/catch present; empty-data guard; no-data message styled
Units consistent across axis, labels, tooltip, colorbar, subtitle
No CDN script no external Plotly `<script>` tag; no `window.load` gate
Rendered image inspected: all labels visible, colours correct, no JS error

Full QA procedure: Text Panel Content Guidelines#Quality_assurance.