Problem/Motivation
For pie and doughnut charts rendered with the Chart.js library, every legend entry shows the category name on one line and the numeric data value on a second line, e.g.:
Some legend designation
305The value is redundant — it is already the segment size and is shown in the tooltip on hover — and its presence causes a second, avoidable problem: when the legend is positioned left/right, the long name line gets clipped to fit the narrow column while the short value line survives.
Steps to reproduce
- Build a pie or doughnut chart with the Chart.js library (e.g. a Views chart with a category label field and a numeric data field).
- View the chart — each legend item shows the category name with the value on a line below it.
- Set the legend position to left or right — the category names are truncated.
Root cause
In charts_chartjs, Chartjs::populateCategories() builds data.labels for pie/doughnut from each #data item. The inline comment states the intent — "Get the first item in each array" — but the code returns the whole array via array_values():
// Get the first item in each array inside $element[$child]['#data'].
$categories = array_map(function ($item) {
if (!empty($item['color'])) {
unset($item['color']);
}
return gettype($item) === 'array' ? array_values($item) : $item; // returns [name, value]
}, $element[$child]['#data']);
So data.labels ends up as:
[["Legend 1", 305], ["Legend 2", 1824], ...]
Chart.js renders an array label as a multi-line label, which is exactly why the value appears as a second legend line (and why long names truncate on a side legend). The value is already present in data.datasets[0].data, which sizes the segments and feeds the tooltip, so keeping it in the label as well is redundant.
Proposed resolution
Return the first item (the name), matching the comment:
return gettype($item) === 'array' ? reset($item) : $item;
After the change, data.labels is ["Legend 2", "Legend 2", ...]; the legend shows names only, and Chart.js's native tooltip still shows Name: value on hover. Segment sizes are unchanged (they come from the dataset data, not the labels).
Only pie/doughnut on the Chart.js library is affected; other libraries build labels via their own code paths.
| Comment | File | Size | Author |
|---|---|---|---|
| charts-chartjs-pie-doughnut-legend-name-only.patch | 459 bytes | jrochate |
Issue fork charts-3611394
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #4
andileco commentedThanks for reporting this issue. I tried it on both Views and Chart Data Table-generated Charts. And looked at the Chart.js API Example. It does the job. However, I created a MR using is_array rather than gettype === 'array'.
Comment #5
jrochate commentedSure, I didn't want to over-change stuff. Just nail the problem.
Of course your MR is prefereable.
Thanks :)
Comment #7
andileco commented