Conversation
- Import addLegend utility - Add showLegend and legendPosition options to Bar chart - Render legend with dataset labels and colors - Fixes issue #101: Legends not showing up for charts
There was a problem hiding this comment.
Pull request overview
Adds legend rendering support to the Bar chart so it can display a legend similarly to other chart types in the library (addressing missing legend behavior reported in #101).
Changes:
- Import and invoke the existing
addLegendutility fromsrc/utils/addLegend.js. - Add new Bar chart options:
showLegend(defaulttrue) andlegendPosition(defaultdownRight). - Build legend items and render the legend at the end of
Bar.render().
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| const legendItems = this.data.datasets.map((dataset, j) => ({ | ||
| color: this.options.dataColors[j], | ||
| text: `${dataset.label || ''}`, |
There was a problem hiding this comment.
Bar currently renders only the first dataset (this.data.datasets[0]), and colors bars by label index (dataColors[i] on hover). The new legend builds items from dataset index (datasets.map(... dataColors[j])), so for the common Bar usage (single dataset without a label) the legend will show a blank item and its color won’t correspond to bar colors. Either (a) build legend items from data.labels (matching Bar’s per-bar color scheme), or (b) update Bar rendering to support multiple datasets with consistent per-dataset colors and then keep the dataset-based legend.
| const legendItems = this.data.datasets.map((dataset, j) => ({ | |
| color: this.options.dataColors[j], | |
| text: `${dataset.label || ''}`, | |
| const legendItems = this.data.labels.map((label, i) => ({ | |
| color: this.options.dataColors[i], | |
| text: `${label}`, |
Problem
Bar chart component was missing legend support, while other chart types (Line, Pie, Radar, StackedBar, XY) all have it. This causes legends to not show up for bar charts.
Solution
addLegendutilityshowLegend(default: true) andlegendPosition(default: downRight) optionsChanges
src/Bar.js:addLegendutilityTesting
The legend should now appear on bar charts when
showLegendis true (default).Fixes #101