Skip to main content

Blazor Bar Chart

A Blazor Bootstrap bar chart component is used to represent data values as vertical bars. It is sometimes used to show trend data and to compare multiple data sets side by side.

Blazor Chart Component - Blazor Bar Chart

Parameters

NameTypeDefaultRequiredDescriptionAdded / Modified Version
Heightint?nullGets or sets chart container height.1.0.0
HeightUnitUnitUnit.PxGets or sets chart container height unit of measure.1.0.0
Widthint?nullGets or sets chart container width.1.0.0
WidthUnitUnitUnit.PxGets or sets chart container width unit of measure.1.0.0

Methods

NameReturn typeDescriptionAdded / Modified Version
AddDataAsync(ChartData chartData, string dataLabel, IChartDatasetData data)Task<ChartData>Adds data to chart.1.10.0
AddDataAsync(ChartData chartData, string dataLabel, List<IChartDatasetData> data)Task<ChartData>Adds dataset to chart.1.10.0
AddDatasetAsync(ChartData chartData, IChartDataset chartDataset, IChartOptions chartOptions)Task<ChartData>Adds dataset to chart.1.10.0
InitializeAsync(ChartData chartData, IChartOptions chartOptions, string[]? plugins = null)TaskInitialize the chat.1.0.0
ResizeAsync(int width, int height, Unit widthUnit = Unit.Px, Unit heightUnit = Unit.Px)TaskResize the chart.1.0.0
UpdateAsync(ChartData chartData, IChartOptions chartOptions)TaskUpdate the chart.1.0.0

ChartData Members

Property NameTypeDefaultRequiredDescriptionAdded / Modified Version
DatasetsList<IChartDataset>?null✔️Gets or sets the Datasets.1.0.0
LabelsList<string>?null✔️Gets or sets the Labels.1.0.0

BarChartDataset Members

info

BarChartDataset implements IChartDataset and inherits from the parent class ChartDataset.

Property NameTypeDefaultRequiredDescriptionAdded / Modified Version
BackgroundColorList<string>?nullGet or sets the BackgroundColor.1.0.0
BarPercentagedouble0.9Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other.1.0.0
BarThicknessdouble?nullIt is applied to the width of each bar, in pixels. When this is enforced, barPercentage and categoryPercentage are ignored.3.0.0
BorderColorList<string>?nullGet or sets the BorderColor.1.0.0
BorderRadiusList<double>?nullBorder radius.3.0.0
BorderWidthList<double>nullGet or sets the BorderWidth.1.0.0
CategoryPercentagedouble0.8Percent (0-1) of the available width each category should be within the sample width.1.0.0
ClipstringnullHow to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. 0 = clip at chartArea. Clipping can also be configured per side: clip: {left: 5, top: false, right: -2, bottom: 0}1.0.0
DatalabelsBarChartDatasetDataLabelsGet or sets the data labels
DataList<double?>?null✔️Get or sets the Data.3.0.0
GroupedbooltrueShould the bars be grouped on index axis. When true, all the datasets at same index value will be placed next to each other centering on that index value. When false, each bar is placed on its actual index-axis value.
HiddenboolfalseConfigures the visibility state of the dataset. Set it to true, to hide the dataset from the chart.1.0.0
HoverBackgroundColorList<string>nullThe bar background color when hovered.1.0.0
HoverBorderColorList<string>nullThe bar border color when hovered.1.0.0
HoverBorderRadiusList<double>nullThe bar border radius when hovered (in pixels).3.0.0
HoverBorderWidthList<double>nullGet or sets the HoverBorderWidth.1.0.0
IndexAxisstring?nullThe base axis of the chart. 'x' for vertical charts and 'y' for horizontal charts. Supported values are 'x' and 'y'.3.0.0
Labelstring?nullThe label for the dataset which appears in the legend and tooltips.1.0.0
MaxBarThicknessdouble?nullSet this to ensure that bars are not sized thicker than this.3.0.0
MinBarLengthdouble?nullSet this to ensure that bars have a minimum length in pixels.3.0.0
Orderint0The drawing order of dataset. Also affects order for stacking, tooltip and legend.3.0.0
SkipNullboolfalseIf true, null or undefined values will not be used for spacing calculations when determining bar size.3.0.0
XAxisIDstring?nullThe ID of the x axis to plot this dataset on.1.0.0
YAxisIDstring?nullThe ID of the y axis to plot this dataset on.1.0.0

BarChartDatasetDataLabels Members

info

BarChartDatasetDataLabels inherits from the parent class ChartDatasetDataLabels.

Property NameTypeDefaultRequiredDescriptionAdded / Modified Version
AlignmentAlignmentAlignment.NoneGets or sets the data labels alignment.3.0.0
AnchorAnchorAnchor.NoneGets or sets the data labels anchor.3.0.0
BorderWidthdouble2Gets or sets the border width3.0.0

BarChartOptions Members

info

BarChartOptions inherits from the parent class ChartOptions.

Property NameTypeDefaultRequiredDescriptionAdded / Modified Version
IndexAxisstringxThe base axis of the chart. 'x' for vertical charts and 'y' for horizontal charts.1.0.0
InteractionInteractionGets or sets the Interaction.1.0.0
LayoutChartLayoutGets or sets the ChartLayout.1.0.0
Localestring?Gets or sets the locale. By default, the chart is using the default locale of the platform which is running on.1.10.0
MaintainAspectRatiobooltrueMaintain the original canvas aspect ratio (width / height) when resizing.3.0.0
PluginsBarChartPluginsGets or sets the Plugins.1.10.2
ResponsiveboolfalseResizes the chart canvas when its container does.1.0.0
ScalesScalesGets or sets the Scales.1.0.0

Examples

Prerequisites

Refer to the getting started guide for setting up charts.

How it works

In the following example, a categorical 12-color palette is used.

tip

For data visualization, you can use the predefined palettes ColorBuilder.CategoricalTwelveColors for a 12-color palette and ColorBuilder.CategoricalSixColors for a 6-color palette. These palettes offer a range of distinct and visually appealing colors that can be applied to represent different categories or data elements in your visualizations.

Blazor Bootstrap: Bar Chart Component - How it works
<BarChart @ref="barChart" Width="800" Class="mb-4" />

<Button Type="ButtonType.Button" Color="ButtonColor.Primary" Size="Size.Small" @onclick="async () => await RandomizeAsync()"> Randomize </Button>
<Button Type="ButtonType.Button" Color="ButtonColor.Primary" Size="Size.Small" @onclick="async () => await AddDatasetAsync()"> Add Dataset </Button>
<Button Type="ButtonType.Button" Color="ButtonColor.Primary" Size="Size.Small" @onclick="async () => await AddDataAsync()">Add Data</Button>
<Button Type="ButtonType.Button" Color="ButtonColor.Primary" Size="Size.Small" @onclick="async () => await ShowHorizontalBarChartAsync()">Horizontal Bar Chart</Button>
<Button Type="ButtonType.Button" Color="ButtonColor.Primary" Size="Size.Small" @onclick="async () => await ShowVerticalBarChartAsync()">Vertical Bar Chart</Button>
@code {
private BarChart barChart = default!;
private BarChartOptions barChartOptions = default!;
private ChartData chartData = default!;

private int datasetsCount = 0;
private int labelsCount = 0;
private string[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
private Random random = new();

protected override void OnInitialized()
{
chartData = new ChartData { Labels = GetDefaultDataLabels(6), Datasets = GetDefaultDataSets(3) };
barChartOptions = new BarChartOptions { Responsive = true, Interaction = new Interaction { Mode = InteractionMode.Index } };
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await barChart.InitializeAsync(chartData, barChartOptions);
}
await base.OnAfterRenderAsync(firstRender);
}

private async Task RandomizeAsync()
{
if (chartData is null || chartData.Datasets is null || !chartData.Datasets.Any()) return;

var newDatasets = new List<IChartDataset>();

foreach (var dataset in chartData.Datasets)
{
if (dataset is BarChartDataset barChartDataset
&& barChartDataset is not null
&& barChartDataset.Data is not null)
{
var count = barChartDataset.Data.Count;

var newData = new List<double>();
for (var i = 0; i < count; i++)
{
newData.Add(random.Next(200));
}

barChartDataset.Data = newData;
newDatasets.Add(barChartDataset);
}
}

chartData.Datasets = newDatasets;

await barChart.UpdateAsync(chartData, barChartOptions);
}

private async Task AddDatasetAsync()
{
if (chartData is null || chartData.Datasets is null) return;

if (datasetsCount >= 12)
return;

var chartDataset = GetRandomBarChartDataset();
chartData = await barChart.AddDatasetAsync(chartData, chartDataset, barChartOptions);
}

private async Task AddDataAsync()
{
if (chartData is null || chartData.Datasets is null)
return;

if (labelsCount >= 12)
return;

var data = new List<IChartDatasetData>();
foreach (var dataset in chartData.Datasets)
{
if (dataset is BarChartDataset barChartDataset)
data.Add(new BarChartDatasetData(barChartDataset.Label, random.Next(200)));
}

chartData = await barChart.AddDataAsync(chartData, GetNextDataLabel(), data);
}

private async Task ShowHorizontalBarChartAsync()
{
barChartOptions.IndexAxis = "y";
await barChart.UpdateAsync(chartData, barChartOptions);
}

private async Task ShowVerticalBarChartAsync()
{
barChartOptions.IndexAxis = "x";
await barChart.UpdateAsync(chartData, barChartOptions);
}

#region Data Preparation

private List<IChartDataset> GetDefaultDataSets(int numberOfDatasets)
{
var datasets = new List<IChartDataset>();

for (var index = 0; index < numberOfDatasets; index++)
{
datasets.Add(GetRandomBarChartDataset());
}

return datasets;
}

private BarChartDataset GetRandomBarChartDataset()
{
var c = ColorBuilder.CategoricalTwelveColors[datasetsCount].ToColor();

datasetsCount += 1;

return new BarChartDataset()
{
Label = $"Product {datasetsCount}",
Data = GetRandomData(),
BackgroundColor = new List<string> { c.ToRgbString() },
BorderColor = new List<string> { c.ToRgbString() },
BorderWidth = new List<double> { 0 },
};
}

private List<double> GetRandomData()
{
var data = new List<double>();
for (var index = 0; index < labelsCount; index++)
{
data.Add(random.Next(200));
}

return data;
}

private List<string> GetDefaultDataLabels(int numberOfLabels)
{
var labels = new List<string>();
for (var index = 0; index < numberOfLabels; index++)
{
labels.Add(GetNextDataLabel());
}

return labels;
}

private string GetNextDataLabel()
{
labelsCount += 1;
return months[labelsCount - 1];
}

#endregion Data Preparation
}

See the demo here.

Horizontal bar chart

Blazor Bootstrap: Bar Chart Component - Horizontal bar chart
<BarChart @ref="barChart" Height="300" Class="mb-4" />
@code {
private BarChart barChart = default!;
private BarChartOptions barChartOptions = default!;
private ChartData chartData = default!;

protected override void OnInitialized()
{
var labels = new List<string> { "Chrome", "Firefox", "Safari", "Edge" };
var datasets = new List<IChartDataset>();

var dataset1 = new BarChartDataset()
{
Data = new List<double> { 55000, 15000, 18000, 21000 },
BackgroundColor = new List<string> { ColorBuilder.CategoricalTwelveColors[0] },
BorderColor = new List<string> { ColorBuilder.CategoricalTwelveColors[0] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset1);

chartData = new ChartData {
Labels = labels,
Datasets = datasets };

barChartOptions = new BarChartOptions();
barChartOptions.Responsive = true;
barChartOptions.Interaction = new Interaction { Mode = InteractionMode.Y };
barChartOptions.IndexAxis = "y";

barChartOptions.Scales.X.Title.Text = "Visitors";
barChartOptions.Scales.X.Title.Display = true;

barChartOptions.Scales.Y.Title.Text = "Browser";
barChartOptions.Scales.Y.Title.Display = true;

barChartOptions.Plugins.Legend.Display = false;
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await barChart.InitializeAsync(chartData, barChartOptions);
}
await base.OnAfterRenderAsync(firstRender);
}
}

See the demo here.

Stacked bar chart

Blazor Bootstrap: Bar Chart Component - Stacked bar chart
<BarChart @ref="barChart" Height="300" Class="mb-4" />
@code {
private BarChart barChart = default!;
private BarChartOptions barChartOptions = default!;
private ChartData chartData = default!;

protected override void OnInitialized()
{
var colors = ColorBuilder.CategoricalTwelveColors;

var labels = new List<string> { "Chrome", "Firefox", "Safari", "Edge" };
var datasets = new List<IChartDataset>();

var dataset1 = new BarChartDataset()
{
Label = "Windows",
Data = new List<double> { 28000, 8000, 2000, 17000 },
BackgroundColor = new List<string> { colors[0] },
BorderColor = new List<string> { colors[0] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset1);

var dataset2 = new BarChartDataset()
{
Label = "macOS",
Data = new List<double> { 8000, 10000, 14000, 8000 },
BackgroundColor = new List<string> { colors[1] },
BorderColor = new List<string> { colors[1] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset2);

var dataset3 = new BarChartDataset()
{
Label = "Other",
Data = new List<double> { 28000, 10000, 14000, 8000 },
BackgroundColor = new List<string> { colors[2] },
BorderColor = new List<string> { colors[2] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset3);

chartData = new ChartData
{
Labels = labels,
Datasets = datasets
};

barChartOptions = new();
barChartOptions.Responsive = true;
barChartOptions.Interaction = new Interaction { Mode = InteractionMode.Y };
barChartOptions.IndexAxis = "y";

barChartOptions.Scales.X.Title.Text = "Visitors";
barChartOptions.Scales.X.Title.Display = true;

barChartOptions.Scales.Y.Title.Text = "Browser";
barChartOptions.Scales.Y.Title.Display = true;

barChartOptions.Scales.X.Stacked = true;
barChartOptions.Scales.Y.Stacked = true;

barChartOptions.Plugins.Title.Text = "Operating system";
barChartOptions.Plugins.Title.Display = true;
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await barChart.InitializeAsync(chartData, barChartOptions);
}
await base.OnAfterRenderAsync(firstRender);
}
}

See the demo here.

Locale

By default, the chart is using the default locale of the platform on which it is running. In the following example, you will see the chart in the German locale (de_DE).

Blazor Bootstrap: Bar Chart Component - Locale
<BarChart @ref="barChart" Height="300" Class="mb-4" />
@code {
private BarChart barChart = default!;
private BarChartOptions barChartOptions = default!;
private ChartData chartData = default!;

protected override void OnInitialized()
{
var colors = ColorBuilder.CategoricalTwelveColors;

var labels = new List<string> { "Chrome", "Firefox", "Safari", "Edge" };
var datasets = new List<IChartDataset>();

var dataset1 = new BarChartDataset()
{
Label = "Windows",
Data = new List<double> { 28000, 8000, 2000, 17000 },
BackgroundColor = new List<string> { colors[0] },
BorderColor = new List<string> { colors[0] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset1);

var dataset2 = new BarChartDataset()
{
Label = "macOS",
Data = new List<double> { 8000, 10000, 14000, 8000 },
BackgroundColor = new List<string> { colors[1] },
BorderColor = new List<string> { colors[1] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset2);

var dataset3 = new BarChartDataset()
{
Label = "Other",
Data = new List<double> { 28000, 10000, 14000, 8000 },
BackgroundColor = new List<string> { colors[2] },
BorderColor = new List<string> { colors[2] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset3);

chartData = new ChartData
{
Labels = labels,
Datasets = datasets
};

barChartOptions = new();
barChartOptions.Locale = "de-DE";
barChartOptions.Responsive = true;
barChartOptions.Interaction = new Interaction { Mode = InteractionMode.Y };
barChartOptions.IndexAxis = "y";

barChartOptions.Scales.X.Title.Text = "Visitors";
barChartOptions.Scales.X.Title.Display = true;

barChartOptions.Scales.Y.Title.Text = "Browser";
barChartOptions.Scales.Y.Title.Display = true;

barChartOptions.Scales.X.Stacked = true;
barChartOptions.Scales.Y.Stacked = true;

barChartOptions.Plugins.Title.Text = "Operating system";
barChartOptions.Plugins.Title.Display = true;
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await barChart.InitializeAsync(chartData, barChartOptions);
}
await base.OnAfterRenderAsync(firstRender);
}
}

See the demo here.

Data labels

Blazor Bootstrap: Bar Chart Component - Data labels
<BarChart @ref="barChart" Height="300" Class="mb-4" />
@code {
private BarChart barChart = default!;
private BarChartOptions barChartOptions = default!;
private ChartData chartData = default!;

protected override void OnInitialized()
{
var colors = ColorBuilder.CategoricalTwelveColors;

var labels = new List<string> { "Chrome", "Firefox", "Safari", "Edge" };
var datasets = new List<IChartDataset>();

var dataset1 = new BarChartDataset()
{
Label = "Windows",
Data = new List<double> { 28000, 8000, 2000, 17000 },
BackgroundColor = new List<string> { colors[0] },
BorderColor = new List<string> { colors[0] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset1);

var dataset2 = new BarChartDataset()
{
Label = "macOS",
Data = new List<double> { 8000, 10000, 14000, 8000 },
BackgroundColor = new List<string> { colors[1] },
BorderColor = new List<string> { colors[1] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset2);

var dataset3 = new BarChartDataset()
{
Label = "Other",
Data = new List<double> { 28000, 10000, 14000, 8000 },
BackgroundColor = new List<string> { colors[2] },
BorderColor = new List<string> { colors[2] },
BorderWidth = new List<double> { 0 },
};
datasets.Add(dataset3);

chartData = new ChartData
{
Labels = labels,
Datasets = datasets
};

barChartOptions = new();
barChartOptions.Responsive = true;
barChartOptions.Interaction = new Interaction { Mode = InteractionMode.Y };
barChartOptions.IndexAxis = "y";

barChartOptions.Scales.X.Title.Text = "Visitors";
barChartOptions.Scales.X.Title.Display = true;

barChartOptions.Scales.Y.Title.Text = "Browser";
barChartOptions.Scales.Y.Title.Display = true;

barChartOptions.Scales.X.Stacked = true;
barChartOptions.Scales.Y.Stacked = true;

barChartOptions.Plugins.Title.Text = "Operating system";
barChartOptions.Plugins.Title.Display = true;
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
// pass the plugin name to enable the data labels
await barChart.InitializeAsync(chartData: chartData, chartOptions: barChartOptions, plugins: new string[] { "ChartDataLabels" });
}
await base.OnAfterRenderAsync(firstRender);
}
}

See the demo here.