Skip to content

Commit a2bbf07

Browse files
authored
chartjs update scenarios (#1412)
* Update charts to BlazorExpress.ChartJS 2.0.0 and add chart scenarios Load Chart.js 4.6.1 (the version BlazorExpress.ChartJS 2.0.0 is built for) in both demo hosts, and update the chart setup instructions in the demos callout and the docs: package 2.0.0, Chart.js 4.6.1 with SRI, supported versions, and a note on the 2.0.0 breaking changes. Add Data Visualization > Chart Scenarios (/demos/charts/scenarios) with four fixes for problems people report: charts that do not grow back in Bootstrap rows and cards (#1089, #797), days missing from query results (#643), pie charts with too many slices (top N plus Other), and colours that move between categories when the data changes (#411). * Add mixed bar and line chart scenarios Add a "Mixed bar and line charts" group to Chart Scenarios with three problem-led examples: - Revenue and margin: a percent line on the same axis as dollar bars is flat; move it to a second axis with its own format. - Pareto chart: sort causes, add a cumulative share line on a 0-100% axis with an 80% reference line, and fade the bars after it. - Stacked bars with reference lines: on a stacked axis, lines without a Stack are added together; give each line its own Stack.
1 parent f41cc97 commit a2bbf07

25 files changed

Lines changed: 897 additions & 20 deletions

‎BlazorBootstrap.Demo.RCL/Components/Layout/DemosMainLayout.razor.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ internal override IEnumerable<NavItem> GetNavItems()
115115
new (){ Id = "605", Text = "Polar Area Chart", Href = DemoRouteConstants.Demos_URL_PolarAreaChart, IconName = IconName.PieChartFill, ParentId = "6", Match = NavLinkMatch.All },
116116
new (){ Id = "606", Text = "Radar Chart", Href = DemoRouteConstants.Demos_URL_RadarChart, IconName = IconName.Radar, ParentId = "6", Match = NavLinkMatch.All },
117117
new (){ Id = "607", Text = "Scatter Chart", Href = DemoRouteConstants.Demos_URL_ScatterChart, IconName = IconName.GraphUpArrow, ParentId = "6", Match = NavLinkMatch.All },
118+
new (){ Id = "608", Text = "Chart Scenarios", Href = DemoRouteConstants.Demos_URL_ChartScenarios, IconName = IconName.Lightbulb, ParentId = "6", Match = NavLinkMatch.All },
118119

119120
new(){ Id = "7", Text = "Services", IconName = IconName.WrenchAdjustableCircleFill, IconColor = IconColor.Success },
120121
new (){ Id = "700", Text = "Breadcrumb Service", Href = DemoRouteConstants.Demos_URL_BreadcrumbService, IconName = IconName.SegmentedNav, ParentId = "7" },

‎BlazorBootstrap.Demo.RCL/Components/Layout/MainLayout.razor.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ internal override IEnumerable<NavItem> GetNavItems()
114114
new (){ Id = "605", Text = "Polar Area Chart", Href = DemoRouteConstants.Demos_URL_PolarAreaChart, IconName = IconName.PieChartFill, ParentId = "6", Match = NavLinkMatch.All },
115115
new (){ Id = "606", Text = "Radar Chart", Href = DemoRouteConstants.Demos_URL_RadarChart, IconName = IconName.Radar, ParentId = "6", Match = NavLinkMatch.All },
116116
new (){ Id = "607", Text = "Scatter Chart", Href = DemoRouteConstants.Demos_URL_ScatterChart, IconName = IconName.GraphUpArrow, ParentId = "6", Match = NavLinkMatch.All },
117+
new (){ Id = "608", Text = "Chart Scenarios", Href = DemoRouteConstants.Demos_URL_ChartScenarios, IconName = IconName.Lightbulb, ParentId = "6", Match = NavLinkMatch.All },
117118

118119
new(){ Id = "7", Text = "Services", IconName = IconName.WrenchAdjustableCircleFill, IconColor = IconColor.Success },
119120
new (){ Id = "701", Text = "Breadcrumb Service", Href = DemoRouteConstants.Demos_URL_BreadcrumbService, IconName = IconName.SegmentedNav, ParentId = "7" },

‎BlazorBootstrap.Demo.RCL/Components/Pages/Demos/Charts/ChartsDocumentation.razor‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@
2525
<li><a href="@DemoRouteConstants.Demos_URL_ScatterChart">Scatter Chart</a></li>
2626
</ol>
2727

28+
<div class="mb-3">
29+
For fixes to problems people hit in real screens, such as charts that do not grow back in Bootstrap rows, days missing from query results,
30+
pie charts with too many slices and colours that move between categories, see <a href="@DemoRouteConstants.Demos_URL_ChartScenarios">Chart Scenarios</a>.
31+
</div>
32+
2833
<Callout Color="CalloutColor.Info">
2934
<b>BarChart</b> and <b>LineChart</b> now support mixed bar/line datasets, and <b>BubbleChart</b> is available alongside the rest of the chart gallery.
3035
</Callout>
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
@attribute [Route(pageUrl)]
2+
@layout DemosMainLayout
3+
4+
<DemosPageHeadSection PageUrl="@pageUrl"
5+
PageTitle="@pageTitle"
6+
PageDescription="@pageDescription"
7+
MetaTitle="@metaTitle"
8+
MetaDescription="@metaDescription"
9+
ImageUrl="@imageUrl" />
10+
11+
<div class="mb-3">
12+
Each example below starts from a problem people hit when they put charts into real business screens, reported in the
13+
<a href="https://github.com/vikramlearning/blazorbootstrap/issues?q=is%3Aissue%20chart" target="_blank" rel="noopener noreferrer">Blazor Bootstrap issues</a>
14+
or common to Chart.js reports. For each chart type and option on its own, see the
15+
<a href="https://chartjs.blazorexpress.com/demos/samples" target="_blank" rel="noopener noreferrer">BlazorExpress.ChartJS samples</a>.
16+
</div>
17+
18+
<Section Size="HeadingSize.H2" Name="Charts that shrink and grow in Bootstrap rows and cards" PageUrl="@pageUrl" Link="responsive-layout">
19+
<div class="mb-3">
20+
<strong>The problem:</strong> a chart in a Bootstrap column or a flex card gets smaller when the window narrows but does not grow back, or
21+
pushes past the edge of its card when a side panel opens
22+
(<a href="https://github.com/vikramlearning/blazorbootstrap/issues/1089" target="_blank" rel="noopener noreferrer">#1089</a>,
23+
<a href="https://github.com/vikramlearning/blazorbootstrap/issues/797" target="_blank" rel="noopener noreferrer">#797</a>).
24+
Two things cause it. A Bootstrap <code>.col</code> is a flex item, and a flex item never gets narrower than its content, so the canvas holds the column open.
25+
And Chart.js never makes a chart taller than its container already is; a container without its own height is only as tall as the canvas,
26+
so the chart can shrink but never grow back.
27+
<br />
28+
<strong>The fix:</strong>
29+
<ol class="mt-2 mb-0">
30+
<li>Add <code>style="min-width: 0;"</code> to the column or flex item that holds the chart.</li>
31+
<li>
32+
Give the chart's container a height that follows its width: <code>ContainerStyle="position: relative; width: 100%; aspect-ratio: 2 / 1; min-height: 240px;"</code>.
33+
Keep <code>width: 100%</code>; without it, <code>aspect-ratio</code> turns the minimum height into a minimum width and the chart overflows on small screens.
34+
</li>
35+
<li>Set <code>MaintainAspectRatio = false</code> in the chart options, so the chart fills that container.</li>
36+
<li>Do not set <code>Width</code> or <code>Height</code> on the chart; a fixed size stops it following the layout.</li>
37+
</ol>
38+
</div>
39+
<Demo Type="typeof(ChartScenarios_Demo_01_Responsive_Layout)" Tabs="true" />
40+
</Section>
41+
42+
<Section Size="HeadingSize.H2" Name="Days missing from the query result" PageUrl="@pageUrl" Link="missing-dates">
43+
<div class="mb-3">
44+
<strong>The problem:</strong> a <code>GROUP BY</code> date query returns only the days that had data, so a chart of orders per day silently
45+
skips closed days and outages, and the bars look evenly spaced when they are not
46+
(<a href="https://github.com/vikramlearning/blazorbootstrap/issues/643" target="_blank" rel="noopener noreferrer">#643</a>).
47+
<br />
48+
<strong>The fix:</strong> build the full list of days for the range in C# and fill the days the query did not return.
49+
Use <code>0</code> when a missing day means nothing happened, and <code>null</code> when it means no data was reported, so the chart shows a gap.
50+
</div>
51+
<Demo Type="typeof(ChartScenarios_Demo_02_Missing_Dates)" Tabs="true" />
52+
</Section>
53+
54+
<Section Size="HeadingSize.H2" Name="Too many slices: top N plus Other" PageUrl="@pageUrl" Link="top-n-other">
55+
<div class="mb-3">
56+
<strong>The problem:</strong> a pie or doughnut chart of every customer, country or product turns into thin slices nobody can read,
57+
and once there are more slices than palette colours, colours repeat.
58+
<br />
59+
<strong>The fix:</strong> sort the rows, keep the largest few as their own slices, add the rest together as one <b>Other</b> slice in a neutral colour,
60+
and list what <b>Other</b> contains next to the chart.
61+
</div>
62+
<Demo Type="typeof(ChartScenarios_Demo_03_Top_N_Other)" Tabs="true" />
63+
</Section>
64+
65+
<Section Size="HeadingSize.H2" Name="Keep each category's colour when the data changes" PageUrl="@pageUrl" Link="stable-colors">
66+
<div class="mb-3">
67+
<strong>The problem:</strong> colours given by list position move to another category when the data is sorted differently or a category
68+
has no rows, so <b>Billing</b> is teal in one quarter and orange in the next, and readers compare the wrong slices
69+
(<a href="https://github.com/vikramlearning/blazorbootstrap/issues/411" target="_blank" rel="noopener noreferrer">#411</a>).
70+
<br />
71+
<strong>The fix:</strong> give every category a colour once, from the full category list, and look the colour up by name each time you build the data.
72+
Use the same lookup for every chart on the page.
73+
</div>
74+
<Demo Type="typeof(ChartScenarios_Demo_04_Stable_Colors)" Tabs="true" />
75+
</Section>
76+
77+
<Section Size="HeadingSize.H2" Name="Mixed bar and line charts" PageUrl="@pageUrl" Link="mixed-charts">
78+
<div class="mb-3">
79+
A <code>BarChart</code> can hold <code>LineChartDataset</code>s next to its <code>BarChartDataset</code>s. Bars and a line together answer
80+
two questions on one chart, such as how much and how good, but they bring their own traps: units that do not share a scale, lines drawn behind bars,
81+
and lines that get stacked by accident. Set <code>Order</code> on each dataset to choose what is drawn on top; a lower order is drawn later, in front.
82+
</div>
83+
</Section>
84+
85+
<Section Size="HeadingSize.H3" Name="Revenue and margin: two units on one chart" PageUrl="@pageUrl" Link="mixed-units">
86+
<div class="mb-3">
87+
<strong>The problem:</strong> revenue in dollars and gross margin in percent share one y-axis, so a 34% margin next to $538,000 of revenue
88+
is a flat line along the bottom and its ups and downs disappear.
89+
<br />
90+
<strong>The fix:</strong> add a second y-axis on the right with <code>Scales.AdditionalAxes["y1"]</code>, set <code>YAxisID = "y1"</code> on the line,
91+
give each axis its own number format and title, and turn off the second axis's grid lines with <code>DrawOnChartArea = false</code>.
92+
</div>
93+
<Demo Type="typeof(ChartScenarios_Demo_05_Mixed_Units)" Tabs="true" />
94+
</Section>
95+
96+
<Section Size="HeadingSize.H3" Name="Pareto chart: find the few causes behind most problems" PageUrl="@pageUrl" Link="pareto-chart">
97+
<div class="mb-3">
98+
<strong>The problem:</strong> a quality, support or returns team needs to know which few causes account for most of the problems.
99+
Chart.js has no Pareto chart type, and a plain bar chart of unsorted export data does not show where the 80% line falls.
100+
<br />
101+
<strong>The fix:</strong> sort the causes from most to fewest, add a running total as a share of the whole, and draw it as a line on a second axis from 0 to 100%.
102+
A dashed line at 80% and faded bars after it show which causes to fix first.
103+
</div>
104+
<Demo Type="typeof(ChartScenarios_Demo_06_Pareto)" Tabs="true" />
105+
</Section>
106+
107+
<Section Size="HeadingSize.H3" Name="Stacked bars with reference lines" PageUrl="@pageUrl" Link="stacked-bars-reference-lines">
108+
<div class="mb-3">
109+
<strong>The problem:</strong> with <code>Scales.Y.Stacked = true</code>, every dataset that has no <code>Stack</code> joins the default stack of its type.
110+
Two reference lines, such as team capacity and the same week last year, are then added together, and the second line is drawn far too high.
111+
Turning stacking off fixes the lines but breaks the bars.
112+
<br />
113+
<strong>The fix:</strong> keep the axis stacked, put the bars in one named stack, and give each reference line a <code>Stack</code> of its own.
114+
</div>
115+
<Demo Type="typeof(ChartScenarios_Demo_07_Stacked_Bars_Reference_Lines)" Tabs="true" />
116+
</Section>
117+
118+
<ChartJSCallout />
119+
120+
@code {
121+
private const string pageUrl = DemoRouteConstants.Demos_URL_ChartScenarios;
122+
private const string pageTitle = "Blazor Chart Scenarios";
123+
private const string pageDescription = "Fixes for problems people hit when they put charts into real business screens: charts that do not grow back in Bootstrap layouts, days missing from query results, pie charts with too many slices, colours that move between categories, and mixed bar and line charts: two units on one chart, a Pareto chart, and stacked bars with reference lines.";
124+
private const string metaTitle = "Blazor chart scenarios and fixes";
125+
private const string metaDescription = "Live Blazor chart examples with source code that fix common chart problems: responsive charts in Bootstrap rows and cards, missing dates, top N plus Other, stable category colours, and mixed bar and line charts with a second axis, a Pareto chart and stacked bars with reference lines.";
126+
private const string imageUrl = "https://i.imgur.com/IX3bajc.png";
127+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
2+
<Button Type="ButtonType.Button" Color="ButtonColor.Secondary" Outline="true" Size="ButtonSize.Small"
3+
aria-controls="revenue-filters" aria-expanded="@(showFilters ? "true" : "false")"
4+
@onclick="() => showFilters = !showFilters">
5+
<Icon Name="IconName.Funnel" class="me-1" aria-hidden="true" />@(showFilters ? "Hide filters" : "Show filters")
6+
</Button>
7+
<span class="text-body-secondary small">The chart resizes when the filter panel opens or closes, not only when the window resizes.</span>
8+
</div>
9+
10+
<div class="row g-3">
11+
@if (showFilters)
12+
{
13+
<div class="col-12 col-md-4 col-xl-3" id="revenue-filters">
14+
<div class="card h-100">
15+
<div class="card-body">
16+
<h3 class="h6 card-title">Regions</h3>
17+
@foreach (var region in regions)
18+
{
19+
<CheckboxInput Label="@region.Name" @bind-Value="region.Visible" @bind-Value:after="UpdateChartAsync" />
20+
}
21+
</div>
22+
</div>
23+
</div>
24+
}
25+
26+
@* A Bootstrap .col is a flex item, and a flex item never gets narrower than its content (min-width: auto).
27+
min-width: 0 lets this column shrink below the chart's current width, so the chart can shrink and grow again. *@
28+
<div class="col-12 col-md" style="min-width: 0;">
29+
<div class="card h-100">
30+
<div class="card-body">
31+
<h3 class="h6 card-title">Revenue by month, FY2026 (USD thousands)</h3>
32+
@* Chart.js never makes a chart taller than its container already is. A container without its own height is only as tall
33+
as the canvas, so the chart could shrink but never grow back. aspect-ratio gives the container a height that follows its width. *@
34+
<BarChart @ref="revenueChart" ContainerStyle="position: relative; width: 100%; aspect-ratio: 2 / 1; min-height: 240px;"
35+
role="img" aria-label="Bar chart: revenue in thousands of US dollars per month, April to September 2025, by region" />
36+
</div>
37+
</div>
38+
</div>
39+
</div>
40+
41+
@code {
42+
private BarChart revenueChart = default!;
43+
private BarChartOptions options = default!;
44+
private bool showFilters = true;
45+
46+
private static readonly List<string> months = ["Apr", "May", "Jun", "Jul", "Aug", "Sep"];
47+
48+
private readonly List<RegionRevenue> regions =
49+
[
50+
new("North America", [412, 398, 455, 471, 502, 538]),
51+
new("Europe", [286, 301, 297, 318, 289, 342]),
52+
new("Asia Pacific", [174, 193, 221, 236, 264, 291]),
53+
];
54+
55+
protected override void OnInitialized()
56+
{
57+
// MaintainAspectRatio = false: the chart fills its container, whose size the layout and aspect-ratio decide.
58+
options = new BarChartOptions { Responsive = true, MaintainAspectRatio = false, Interaction = new Interaction { Mode = InteractionMode.Index } };
59+
options.Scales.Y!.Title = new ChartAxesTitle { Text = "USD thousands", Display = true, Color = null };
60+
}
61+
62+
protected override async Task OnAfterRenderAsync(bool firstRender)
63+
{
64+
if (firstRender)
65+
await revenueChart.InitializeAsync(GetChartData(), options);
66+
67+
await base.OnAfterRenderAsync(firstRender);
68+
}
69+
70+
private async Task UpdateChartAsync() => await revenueChart.UpdateAsync(GetChartData(), options);
71+
72+
private ChartData GetChartData()
73+
{
74+
var datasets = new List<IChartDataset>();
75+
76+
for (var index = 0; index < regions.Count; index++)
77+
{
78+
if (!regions[index].Visible)
79+
continue;
80+
81+
var color = ColorUtility.CategoricalTwelveColors[index].ToChartColor().ToChartRgbString();
82+
83+
datasets.Add(new BarChartDataset
84+
{
85+
Label = regions[index].Name,
86+
Data = regions[index].Revenue,
87+
BackgroundColor = [color],
88+
BorderColor = [color],
89+
BorderWidth = [0],
90+
});
91+
}
92+
93+
return new ChartData { Labels = months, Datasets = datasets };
94+
}
95+
96+
private sealed class RegionRevenue(string name, List<double?> revenue)
97+
{
98+
public string Name { get; } = name;
99+
public List<double?> Revenue { get; } = revenue;
100+
public bool Visible { get; set; } = true;
101+
}
102+
}

0 commit comments

Comments
 (0)