RTL charts and data visualization
Learn how to choose chart axis direction, render Arabic labels and legends, format numbers, and test canvas charts and tooltips.
By Omran Khleifat, Founder of Ritla
Guide14 min read
An Arabic dashboard can have correctly aligned headings while its chart still shows English legends, clips Arabic labels, or opens a tooltip for the wrong point. Setting the page to dir="rtl" does not configure every drawing operation inside a chart library.
Axis direction also needs a product decision. Material Design's bidirectionality guidance leaves charts and graphs unmirrored, while mirroring timelines that show the passage of time. Those are different presentation conventions, even when both displays contain dates. Treating every horizontal sequence as something to reverse loses that distinction.
Separate the plot's geometry from its text. Decide where values belong, then configure Arabic labels, legend layout, number formatting, and interactions around that decision. For canvas charts, inspect the rendered labels as well as the surrounding HTML: correct DOM text does not prove that the pixels inside the canvas are correct.
Decide what the axis means before reversing it#
Consider a tram ridership dashboard. Its chart compares three service periods, with counts increasing upward. The following examples use invented fixture data, not measured passenger statistics.
If the dashboard follows a chart convention where earlier periods appear on the left, retain that convention on the Arabic route and translate the period labels. If research with its intended readers supports earlier periods on the right, reverse the horizontal scale deliberately. Record that choice in the chart specification so QA has an expected result.
Arabic reading direction alone does not settle whether a scientific coordinate system, a financial chart, or an operational timeline should change orientation. Ask what users compare this chart with. Mirroring one chart in a report while leaving another chart's shared time axis unchanged makes comparisons harder.
| Chart feature | Decision to make |
|---|---|
| Horizontal time axis | Which physical end represents the earliest instant? |
| Ordered categories | Is their order temporal, ranked, or part of a named process? |
| Vertical numeric axis | Does the established convention still put larger values higher? |
| Horizontal bars | Where is the zero baseline, and which direction represents an increase? |
| Geographic map | Keep actual geographic orientation unless the view explicitly changes it. |
| Legend | How should Arabic text and swatches be arranged, independently of the axes? |
A horizontal bar chart needs more attention than switching the category labels to the other side. Signed values must remain on the correct side of zero under the chosen scale. A logarithmic scale still needs its mathematical mapping. A diverging comparison still needs an explicit explanation of which measure each side represents.
Do not apply scaleX(-1) to the finished chart as an RTL patch. That transformation also reflects its text and graphical annotations. Use the chart's scale configuration when the data axis should reverse. What to mirror in RTL covers the surrounding interface decisions.
Preserve the relationship between labels and values#
The dangerous reversal is one that changes the meaning while leaving a plausible picture. In this fixture, the middle service period has the largest count:
const servicePeriods = [ { key: 'before-noon', label: 'قبل الظهر', riders: 1846 }, { key: 'afternoon', label: 'بعد الظهر', riders: 3275 }, { key: 'evening', label: 'المساء', riders: 2598 }];Problem: reversing only the labels when constructing the Arabic chart:
// servicePeriods is the fixture above.const brokenChartData = { labels: servicePeriods.map(period => period.label).reverse(), datasets: [{ data: servicePeriods.map(period => period.riders) }]};The first label now belongs to the evening, but its value still belongs to the period before noon. This is a data association bug, regardless of how Arabic text renders. Chart.js associates primitive dataset values with labels at the same array index, as its data structure documentation explains.
Build labels and values from the same ordered records. If the scale needs reversal, change the scale rather than mutating one array. Chart.js exposes reverse on each scale; it is separate from legend and tooltip direction. See its axis configuration.
For filtering, selection, and exports, retain the stable period key as well. A translated label is presentation text, not a record identifier. Two labels may become identical after abbreviation, and a translation update must not transfer a selected point to another period.
To catch the association bug, inspect all three label/value pairs. Checking only the tallest bar misses it here: reversing three labels leaves the middle label in place.
For stacked series, also record the stacking order. Reversing a legend to suit a visual design does not necessarily change which series sits against the baseline. Check the legend against the actual segments, including after hiding a series. Otherwise a comparison that names the first legend item can refer to a different physical segment than the reader expects.
Configure Arabic text without changing this chart's axis#
This Chart.js 4 example keeps the fixture's periods progressing from left to right. It explicitly sets Arabic legend and tooltip direction. The title and description remain HTML so readers can access them independently of the drawing.
<section lang="ar" dir="rtl" aria-labelledby="tram-title"> <h2 id="tram-title">ركاب خط النهر حسب فترة الخدمة</h2> <p id="tram-summary">أعلى عدد من الركاب في فترة بعد الظهر.</p> <div class="tram-chart-frame"> <canvas id="tram-chart" role="img" aria-labelledby="tram-title" aria-describedby="tram-summary"></canvas> </div></section>.tram-chart-frame { position: relative; block-size: 22rem; min-inline-size: 0;}Run this module after the markup exists, in a project with Chart.js 4 installed and a bundler that resolves its package import. It uses servicePeriods from the earlier fixture.
import Chart from 'chart.js/auto'; const riderCount = new Intl.NumberFormat('ar', { numberingSystem: 'arab', maximumFractionDigits: 0}); const tramChart = new Chart(document.querySelector('#tram-chart'), { type: 'bar', data: { labels: servicePeriods.map(period => period.label), datasets: [{ label: 'عدد الركاب', data: servicePeriods.map(period => period.riders), backgroundColor: '#176b80' }] }, options: { responsive: true, maintainAspectRatio: false, font: { family: 'sans-serif', size: 16 }, scales: { x: { reverse: false }, y: { beginAtZero: true, ticks: { callback: value => riderCount.format(value) } } }, plugins: { legend: { rtl: true, textDirection: 'rtl', reverse: false }, tooltip: { rtl: true, textDirection: 'rtl', titleAlign: 'right', bodyAlign: 'right', callbacks: { label: context => riderCount.format(context.parsed.y) } } } }});The tooltip title identifies the period; its value uses the same digit policy as the vertical ticks. This deliberately simple tooltip returns only the count. Add a translated unit or a fuller message when the surrounding context does not identify the measure.
The dedicated parent and disabled aspect-ratio preservation let its height control the responsive drawing. Chart.js documents these sizing requirements in Responsive Charts. A narrower canvas still needs label review; responsiveness does not guarantee that every translated label fits.
This example supplies a short summary, not a complete accessible data alternative or keyboard interaction model. Those require the additional work described below.
Legend direction is not dataset order#
Three settings that sound similar answer different questions. In the Chart.js legend configuration, rtl controls RTL legend rendering, textDirection controls text direction, and reverse changes the displayed dataset order. None means “mirror the horizontal axis.”
The example has one series, so changing legend order would reveal nothing. Test the real component with multiple series, including a hidden one. Confirm that each swatch still names and toggles the intended series after switching languages.
Keep series colors attached to stable identifiers. Assigning colors from the translated legend's sorted position can make the same service appear blue in English and orange in Arabic. The chart may look tidy while changing the meaning of the color across screenshots or reports.
For an HTML legend, inspect its actual DOM and focus order. Translating buttons and placing swatches beside their labels is only part of the job: hidden-series state must remain understandable without color alone. Do not reverse the source array simply to move a swatch. Decide the item order and the layout inside each item separately.
When a legend wraps, check where the next row begins and whether a long label remains beside its own swatch. A screenshot with one short dataset name cannot establish that behavior.
Format values at the presentation boundary#
The count formatter chooses Arabic-Indic digits explicitly. An Arabic product can instead choose Western digits with numberingSystem: 'latn'. Use the product's agreed convention consistently across ticks, tooltips, summaries, and the data alternative. MDN's number formatting reference describes locale-sensitive formatting.
Keep the underlying counts numeric. Formatting values before they reach the scale mixes presentation with calculation and can interfere with parsing, sorting, or aggregation. Format at tick and tooltip callbacks, and when producing the corresponding textual display.
A count axis may abbreviate large values while the tooltip gives an exact count. That is a useful distinction, but specify the abbreviation policy. Confirm that adjacent tick labels remain distinguishable after rounding. Two different values with identical labels make a scale difficult to read even when the bars are accurate.
Do not quietly turn a missing value into zero. For the ridership chart, zero means no recorded riders; a missing measurement means the count is unavailable. Decide how a missing point, its tooltip, and its data alternative communicate that distinction. A formatter that receives null without a guard can produce a misleading numeric result.
If the chart changes to percentages, check the input contract as well as the symbol position. A ratio and a percentage-point value are different inputs. If it changes to dates, define the grouping timezone before translating tick labels: localization must not move an observation into a different service day accidentally.
See numbers inside RTL text for mixed-direction value presentation. Keep this chart's numerical policy explicit rather than inheriting whichever defaults its plugins happen to use.
Give Arabic labels their actual space#
Translate every surface the reader encounters: axis titles, ticks, dataset names, tooltip headings, annotations, empty states, loading messages, zoom controls, and export labels. A translated chart title can conceal untranslated strings generated by a plugin.
Reserve space using real Arabic labels at the intended font size. For the tram fixture, compare the two multiword period labels with the shorter evening label. Then test the longest label the product allows, rather than assuming this small fixture represents the full content range.
Choose a response to crowding deliberately. A wider plot, fewer ticks, a horizontal bar layout, or line breaks at word boundaries can each help. Rotating everything diagonally may save width while making Arabic harder to inspect. Truncation needs an available full label; a hover-only reveal does not serve touch or keyboard readers.
Do not split an Arabic word into separately positioned letters to make it fit. Pass complete strings to the text renderer. If you introduce line breaks, choose them without breaking the word's connected letter sequence. MDN's canvas text tutorial covers text drawing and measurement.
Fonts affect the layout calculation, not just appearance. Configure a family that actually supports the Arabic text and verify what loads. The example uses a generic family so it has no undeclared webfont dependency; a product should apply its selected chart font deliberately. According to Chart.js font guidance, charts using asynchronously loaded fonts need an update after loading.
Recheck label bounds after that update. Text measured with a fallback font can occupy different space once the selected font appears. Test with an uncached font, then with a failed font request. Neither result should leave labels overlapping the plot or one another.
Canvas text direction does not reverse coordinates#
In custom canvas drawing, ctx.direction controls the text direction. Its default is inherit, but a library or plugin may set its own drawing state. Setting it explicitly for a custom label makes that operation's intent clear. MDN documents the direction property.
This helper draws an Arabic caption whose start edge sits at the supplied coordinate. The caller supplies the canvas's two-dimensional rendering context and the label position in its current coordinate system.
function drawTramCaption(ctx, label, x, y) { ctx.save(); ctx.direction = 'rtl'; ctx.textAlign = 'start'; ctx.font = '16px sans-serif'; ctx.fillText(label, x, y); ctx.restore();}With RTL text, start aligns the text's right edge to x. It does not relocate that x to the other side of the canvas. Physical left and right alignment stay physical; see canvas text alignment.
Saving and restoring prevents this helper's font, alignment, and direction from leaking into later drawing operations. It does not protect against a later plugin changing them before drawing its own labels. Inspect each custom renderer that contributes text.
Never reverse the caption string to make Arabic “look RTL.” That changes the content before the text renderer processes it. Nor can a canvas string interpret <bdi> as markup. If a custom tooltip needs independently directed text runs, an HTML tooltip can offer a clearer structure than manually assembling everything into one drawing call.
SVG charts have a related separation: inspect text attributes and actual path coordinates independently. An RTL wrapper does not establish that an arbitrary line path has changed direction. Avoid reflecting the SVG root to repair just its labels.
Keep tooltip content and tooltip position separate#
A tooltip has at least three independent concerns: which point it describes, how its contents read, and where its box fits. Fixing text alignment cannot correct a tooltip attached to the wrong observation.
Chart.js provides text-direction and line-alignment options separately from caret placement. Its tooltip documentation also supports external HTML tooltips. In the example, right alignment suits the Arabic content; caret placement remains the library's responsibility.
For an HTML tooltip, use semantic direction on the tooltip container. Isolate any inherently LTR identifier inside it instead of forcing the entire explanation to LTR. If the tooltip is mounted outside the Arabic section, check the direction where it actually renders. A portal's physical location in the document can differ from its component ownership.
Positioning code needs a declared coordinate system. A physical left calculated from a canvas-relative point is not automatically an RTL defect. Blindly replacing it with inset-inline-start can move the tooltip away from that point. First establish whether the supplied coordinate measures from the canvas's left edge, the viewport, or a containing block.
Let the chart library handle pointer-to-data conversion where possible. The Chart.js integration guide demonstrates converting event coordinates through scale methods. Avoid a second manual RTL reversal after the library has already applied a reversed scale.
Test the first and last points, then an interior point, at both plot edges. Include page scrolling and a resized chart. If the correct content appears beside the wrong bar, inspect coordinate conversion; if the correct tooltip clips against the viewport, inspect collision handling. These failures require different fixes.
Make the information available beyond hover#
A chart's accessible name identifies it; it does not expose every observation. The canvas markup above names the chart and gives a trend summary. It does not make the individual bars available to assistive technology. Chart.js accessibility guidance makes the author responsible for providing that access.
Offer the underlying values through a nearby semantic table or another structured alternative. Generate it from the same records and active filters as the plot. For this fixture it should preserve each service period, its count, and the count's unit. The summary should identify the afternoon peak without implying that the invented fixture is live reporting.
An alternative must explain the information needed for the chart's purpose. A list of values may suffice for a simple comparison; a more complex plot may need a description of a trend, threshold, or relationship. W3C's complex-image guidance explains short and extended text alternatives.
Interactive charts need an interaction path too. If legend entries hide series, provide keyboard-operable controls with an exposed state. If a tooltip contains information unavailable elsewhere, make that information reachable without requiring a mouse. Merely adding tabindex="0" to a canvas does not create navigation between points.
For keyboard navigation, define whether arrow keys follow physical point positions or chronological order. A reversed time scale makes those two meanings differ. Test against that definition rather than copying the English key mapping and guessing whether to invert it.
Update the chart when the locale changes#
The example creates one Arabic chart. A language switch inside a running dashboard has an additional requirement: update the chart's own configuration. Changing an ancestor's dir cannot translate strings already stored in its dataset or replace a formatter captured by a callback.
Build the next labels, dataset names, formatter callbacks, legend direction, and tooltip direction from the same locale state. Apply the agreed scale policy at the same time. Avoid a frame where Arabic labels accompany an English number formatter or a tooltip still names the previous language's period.
Chart.js supports updating data and options followed by chart.update(), and requires destroying an instance before reusing its canvas for a new chart. Its chart API describes those lifecycle operations. Choose update or recreation according to the integration rather than leaving two chart instances attached to the same surface.
Preserve selection and hidden-series state by stable keys when that state should survive the switch. Preserve the active time window by timestamps, not translated tick text. A point's index can change when filtering removes earlier records, so an index alone is insufficient for restoring the selected observation.
Test switching while a tooltip is open and while data is loading. The final labels, summary, and values should describe the same response. If a late response belongs to an older filter, reject or reconcile it using the application's request state before repainting either the plot or its data alternative.
Reproduce the failure with a small evidence set#
Use the three-period fixture to distinguish failures before testing a larger production dataset. Keep the same records on the English and Arabic routes. Changing the dataset during a direction comparison makes a geometry bug harder to isolate.
- Identify the earliest period and its count at both physical ends. Confirm the documented axis policy.
- Inspect the middle peak and both outer bars. Check each label/value pair in the tooltip and data alternative.
- Enable multiple real series. Toggle one, switch locale, and verify its identity, color, and visibility state.
- Narrow the chart's parent, including with the dashboard sidebar open. Inspect labels, legends, and edge tooltips at the resulting width.
- Repeat after a delayed font load and after a data refresh. Check that the chart redraws using the current text and records.
- Reach the same information with a keyboard and on a touch device. Include tooltip dismissal and series controls.
When labels are wrong, trace the string from translation resource to chart configuration to rendered output. If configuration contains English, investigate translation selection. If configuration contains Arabic but rendering is wrong, inspect the text renderer, font, and drawing state. If a label is missing only at narrow widths, inspect skipping, clipping, and available plot space.
Keep evidence appropriate to the renderer. DOM inspection can establish an HTML label's content. A canvas element's bounding box establishes the drawing surface's size, not the bounds of every painted tick. Capture the actual plot and record the hovered point when reporting a canvas issue.
Test signed, missing, and unusually large values when the production measure permits them. Add a no-data response. A chart that works only with three positive integers leaves the formatter, baseline, and empty-state branches unexplored.
Verify the exported chart as its own output#
An exported image can lose the HTML title, summary, and legend surrounding the canvas. Check what the export includes rather than assuming the dashboard card and downloaded image are equivalent.
Verify Arabic glyphs, digit policy, axis direction, units, and legend associations in the exported artifact. Include a long label and an active filter. If an export redraws through a different renderer, repeat the font and text-direction checks there. A correct on-screen canvas does not establish what a separate export service produces.
For downloadable data, retain the original numeric values alongside translated column labels as appropriate for the format. Do not reverse record order merely because the file was requested from the Arabic interface. State the ordering and active filters so the exported data can be reconciled with the plot.
A free Ritla scan can report Visible Latin-script body text above thresholds on an Arabic page and Arabic-Indic and Western digits mixed in the same context ; verify the painted chart labels and point interactions separately. For the next chart decision, see what to mirror in RTL and numbers inside RTL text.