Blazorise Chart component

Flexible Chart.js-based charting for Blazor applications.

See Charts specifications for behavior details and edge cases.

The chart extension includes several chart components. Each chart type has its own dataset and option settings.

Supported chart types are:

  • Chart default chart component (testing only; see warning)
  • LineChart
  • BarChart
  • PieChart
  • PolarAreaChart
  • DoughnutChart
  • RadarChart

To use the chart components, install the Blazorise.Charts package first.

Installation

NuGet

Install chart extension from NuGet.
dotnet add package Blazorise.Charts

Imports

In your main _Imports.razor add:
@using Blazorise.Charts

Example

You should always define TItem data type.
<Button Color="Color.Primary" Clicked="@(async () => await HandleRedraw())">Redraw</Button>

<LineChart @ref="lineChart" TItem="double" />
@code{
    LineChart<double> lineChart;

    protected override async Task OnAfterRenderAsync( bool firstRender )
    {
        if ( firstRender )
        {
            await HandleRedraw();
        }
    }

    async Task HandleRedraw()
    {
        await lineChart.Clear();

        await lineChart.AddLabelsDatasetsAndUpdate( Labels, GetLineChartDataset() );
    }

    LineChartDataset<double> GetLineChartDataset()
    {
        return new LineChartDataset<double>
        {
            Label = "# of randoms",
            Data = RandomizeData(),
            BackgroundColor = BackgroundColors,
            BorderColor = BorderColors,
            Fill = true,
            PointRadius = 3,
            CubicInterpolationMode = "monotone",
        };
    }

    private static string[] Labels = { "A", "B", "C", "D", "E", "F" };

    private static List<string> BackgroundColors = new()
    {
        ChartColor.FromRgba( 76, 110, 245, 0.25f ),   // Indigo
        ChartColor.FromRgba( 18, 184, 134, 0.25f ),   // Teal
        ChartColor.FromRgba( 245, 159, 0, 0.25f ),    // Amber
        ChartColor.FromRgba( 240, 62, 62, 0.25f ),    // Red
        ChartColor.FromRgba( 132, 94, 247, 0.25f ),   // Purple
        ChartColor.FromRgba( 34, 139, 230, 0.25f )    // Blue
    };

    private static List<string> BorderColors = new()
    {
        ChartColor.FromRgba( 76, 110, 245, 1f ),      // Indigo
        ChartColor.FromRgba( 18, 184, 134, 1f ),      // Teal
        ChartColor.FromRgba( 245, 159, 0, 1f ),       // Amber
        ChartColor.FromRgba( 240, 62, 62, 1f ),       // Red
        ChartColor.FromRgba( 132, 94, 247, 1f ),      // Purple
        ChartColor.FromRgba( 34, 139, 230, 1f )       // Blue
    };

    List<double> RandomizeData()
    {
        var r = new Random( DateTime.Now.Millisecond );

        return new List<double> { 
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble() };
    }
}

Events

It is possible to use Clicked and Hovered events to interact with the chart. The usage is straightforward. The only thing to keep in mind is the Model field that needs to be cast to the right chart-model type. The available model types are:
  • LineChartModel
  • BarChartModel
  • DoughnutChartModel
  • PieChartModel
  • PolarChartModel
  • RadarChartModel
<Chart @ref="barChart" Type="ChartType.Bar" TItem="double" Clicked="@OnClicked" />
@code {
    Chart<double> barChart;

    protected override async Task OnAfterRenderAsync( bool firstRender )
    {
        if ( firstRender )
        {
            await HandleRedraw();
        }
    }

    async Task HandleRedraw()
    {
        await barChart.Clear();

        await barChart.AddLabelsDatasetsAndUpdate( Labels, GetBarChartDataset() );
    }

    private BarChartDataset<double> GetBarChartDataset()
    {
        return new()
            {
                Label = "# of randoms",
                Data = RandomizeData(),
                BackgroundColor = BackgroundColors,
                BorderColor = BorderColors,
                BorderWidth = 1
            };
    }

    private static string[] Labels = { "A", "B", "C", "D", "E", "F" };

    private static List<string> BackgroundColors = new()
    {
        ChartColor.FromRgba( 76, 110, 245, 0.25f ),   // Indigo
        ChartColor.FromRgba( 18, 184, 134, 0.25f ),   // Teal
        ChartColor.FromRgba( 245, 159, 0, 0.25f ),    // Amber
        ChartColor.FromRgba( 240, 62, 62, 0.25f ),    // Red
        ChartColor.FromRgba( 132, 94, 247, 0.25f ),   // Purple
        ChartColor.FromRgba( 34, 139, 230, 0.25f )    // Blue
    };

    private static List<string> BorderColors = new()
    {
        ChartColor.FromRgba( 76, 110, 245, 1f ),      // Indigo
        ChartColor.FromRgba( 18, 184, 134, 1f ),      // Teal
        ChartColor.FromRgba( 245, 159, 0, 1f ),       // Amber
        ChartColor.FromRgba( 240, 62, 62, 1f ),       // Red
        ChartColor.FromRgba( 132, 94, 247, 1f ),      // Purple
        ChartColor.FromRgba( 34, 139, 230, 1f )       // Blue
    };

    List<double> RandomizeData()
    {
        var r = new Random( DateTime.Now.Millisecond );

        return new List<double> {
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble(),
            r.Next( 3, 50 ) * r.NextDouble() };
    }

    Task OnClicked( ChartMouseEventArgs e )
    {
        var model = e.Model as BarChartModel;

        Console.WriteLine( $"Handling event for {nameof( BarChartModel )}: x:{model.X} y:{model.Y}" );
        return Task.CompletedTask;
    }
}

Complex Data

We also support using complex types as chart data. To represent complex data inside the charts you need to define the Parsing options.

<LineChart @ref="lineChart" TItem="WatcherEvent" Options="@lineChartOptions" />
@code {
    private LineChart<WatcherEvent> lineChart;

    LineChartOptions lineChartOptions = new()
    {
        Parsing = new ChartParsing
        {
            XAxisKey = "sector",
            YAxisKey = "count",
        }
    };

    private static List<string> BackgroundColors = new()
    {
        ChartColor.FromRgba( 76, 110, 245, 0.25f ),   // Indigo
        ChartColor.FromRgba( 18, 184, 134, 0.25f ),   // Teal
        ChartColor.FromRgba( 245, 159, 0, 0.25f ),    // Amber
        ChartColor.FromRgba( 240, 62, 62, 0.25f ),    // Red
        ChartColor.FromRgba( 132, 94, 247, 0.25f ),   // Purple
        ChartColor.FromRgba( 34, 139, 230, 0.25f )    // Blue
    };

    private static List<string> BorderColors = new()
    {
        ChartColor.FromRgba( 76, 110, 245, 1f ),      // Indigo
        ChartColor.FromRgba( 18, 184, 134, 1f ),      // Teal
        ChartColor.FromRgba( 245, 159, 0, 1f ),       // Amber
        ChartColor.FromRgba( 240, 62, 62, 1f ),       // Red
        ChartColor.FromRgba( 132, 94, 247, 1f ),      // Purple
        ChartColor.FromRgba( 34, 139, 230, 1f )       // Blue
    };

    private bool isAlreadyInitialised;

    public class WatcherEvent
    {
        public string Sector { get; set; }

        public int Count { get; set; }

        public DateTime Date { get; } = DateTime.Now;
    }

    protected override async Task OnAfterRenderAsync( bool firstRender )
    {
        if ( !isAlreadyInitialised )
        {
            isAlreadyInitialised = true;

            await lineChart.Clear();
            await lineChart.AddDataSet( GetLineChartDataset() );
        }
    }

    private LineChartDataset<WatcherEvent> GetLineChartDataset()
    {
        return new()
        {
            Label = "# of randoms",
            Data = new List<WatcherEvent>
            {
                new WatcherEvent { Sector = "A", Count = 1400 },
                new WatcherEvent { Sector = "B", Count = 900 },
                new WatcherEvent { Sector = "C", Count = 1800 },
                new WatcherEvent { Sector = "D", Count = 1300 },
            },
            BackgroundColor = BackgroundColors[0], // line chart can only have one color
            BorderColor = BorderColors[0],
            Fill = true,
            PointRadius = 3,
            BorderWidth = 1,
            PointBorderColor = Enumerable.Repeat( BorderColors.First(), 6 ).ToList(),
            CubicInterpolationMode = "monotone",
        };
    }
}

Horizontal Bar Chart

By adjusting the BarChartOptions and changing the IndexAxis you can make the horizontal Bar Chart.
<Button Color="Color.Primary" Clicked="@(async () => await HandleRedraw())">Redraw</Button>

<BarChart @ref="barChart" TItem="double" Options="@options" />
@code {
    BarChart<double> barChart;

    BarChartOptions options = new()
    {
        IndexAxis = "y",
        Elements = new()
        {
            Bar = new()
            {
                BorderWidth = 2,
            }
        },
        Responsive = true,
        Plugins = new()
        {
            Legend = new()
            {
                Position = "right"
            },
            Title = new()
            {
                Display = true,
                    Text = "Chart.js Horizontal Bar Chart"
            }
        }
    };

    protected override async Task OnAfterRenderAsync( bool firstRender )
    {
        if ( firstRender )
        {
            await HandleRedraw();
        }
    }

    async Task HandleRedraw()
    {
        await barChart.Clear();

        await barChart.AddLabelsDatasetsAndUpdate( Labels,
            GetBarChartDataset( "Dataset 1" ),
            GetBarChartDataset( "Dataset 2" ) );
    }

    BarChartDataset<double> GetBarChartDataset( string label )
    {
        return new BarChartDataset<double>
        {
            Label = label,
            Data = RandomizeData(),
            BackgroundColor = BackgroundColors,
            BorderColor = BorderColors,
        };
    }

    private static string[] Labels = { "A", "B", "C", "D", "E", "F" };

    private static List<string> BackgroundColors = new()
    {
        ChartColor.FromRgba( 76, 110, 245, 0.25f ),   // Indigo
        ChartColor.FromRgba( 18, 184, 134, 0.25f ),   // Teal
        ChartColor.FromRgba( 245, 159, 0, 0.25f ),    // Amber
        ChartColor.FromRgba( 240, 62, 62, 0.25f ),    // Red
        ChartColor.FromRgba( 132, 94, 247, 0.25f ),   // Purple
        ChartColor.FromRgba( 34, 139, 230, 0.25f )    // Blue
    };

    private static List<string> BorderColors = new()
    {
        ChartColor.FromRgba( 76, 110, 245, 1f ),      // Indigo
        ChartColor.FromRgba( 18, 184, 134, 1f ),      // Teal
        ChartColor.FromRgba( 245, 159, 0, 1f ),       // Amber
        ChartColor.FromRgba( 240, 62, 62, 1f ),       // Red
        ChartColor.FromRgba( 132, 94, 247, 1f ),      // Purple
        ChartColor.FromRgba( 34, 139, 230, 1f )       // Blue
    };

    Random random = new Random( DateTime.Now.Millisecond );

    List<double> RandomizeData()
    {
        return new List<double> {
            random.Next( -50, 50 ) * random.NextDouble(),
            random.Next( -50, 50 ) * random.NextDouble(),
            random.Next( -50, 50 ) * random.NextDouble(),
            random.Next( -50, 50 ) * random.NextDouble(),
            random.Next( -50, 50 ) * random.NextDouble(),
            random.Next( -50, 50 ) * random.NextDouble() };
    }
}

API

See the API reference for the parameters, events, methods, and related types available to the components covered on this page.

Options

ChartOptions

NameDefaultType
ScalesnullChartScales

Configuration for chart scales.
AnimationnullChartAnimation

Configuration for chart animation.
PluginsnullChartPlugins

Configuration for chart plugins.
InteractionnullChartInteraction

Configuration for chart interactions.
ParsingnullChartParsing

Configuration for chart parsing.
ElementsnullChartElements

Configuration for chart elements.
LayoutnullChartLayout

Configuration for chart layout.
IndexAxisnullstring

Index axis for the chart.
Responsivenullbool?

Resizes the chart canvas when its container does.
MaintainAspectRationullbool?

Maintain the original canvas aspect ratio (width / height) when resizing.
AspectRationulldouble?

Canvas aspect ratio (i.e. width / height, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style.
ResizeDelaynullint?

Delay the resize update by given amount of milliseconds. This can ease the resize process by debouncing update of the elements.
Localenullstring

A string with a BCP 47 language tag, leveraging on .

ChartScales

NameDefaultType
XnullChartAxis

Configuration for the x-axis.
YnullChartAxis

Configuration for the y-axis.
AdditionalAxesnullDictionary<string, ChartAxis>

Configuration for custom named axes.

ChartAnimation

NameDefaultType
Durationnullint?

The number of milliseconds an animation takes.
Easingnullstring

Easing function to use. more...
Delaynullint?

Delay before starting the animations.
Loopnullbool?

If set to true, the animations loop endlessly.

ChartPlugins

NameDefaultType
LegendnullChartLegend

Configuration for the chart legend.
TooltipsnullChartTooltips

Configuration for the chart tooltips.
TitlenullChartTitle

Configuration for the chart title.
SubtitlenullChartSubtitle

Configuration for the chart subtitle.
DecimationnullChartDecimation

Configuration for chart data decimation.

ChartInteraction

NameDefaultType
Modenullstring

Sets which elements appear in the interaction.
Intersectnullbool?

If true, the interaction mode only applies when the mouse position intersects an item on the chart.
Axisnullstring

Can be set to 'x', 'y', or 'xy' to define which directions are used in calculating distances. Defaults to 'x' for 'index' mode and 'xy' in dataset and 'nearest' modes.

ChartParsing

NameDefaultType
XAxisKeynullstring

Key for the x-axis values in the data.
YAxisKeynullstring

Key for the y-axis values in the data.

ChartLayout

NameDefaultType
AutoPaddingnullbool?

Apply automatic padding so visible elements are completely drawn.
PaddingnullChartPadding

The padding to add inside the chart.

ChartElements

NameDefaultType
PointnullChartPointElements

Point elements are used to represent the points in a line, radar or bubble chart.
LinenullChartLineElements

Line elements are used to represent the line in a line chart.
BarnullChartBarElements

Bar elements are used to represent the bars in a bar chart.
ArcnullChartArcElements

Arcs are used in the polar area, doughnut and pie charts.

ChartLegend

NameDefaultType
Displaynullbool?

Is the legend shown.
Positionnullstring

Position of the legend.
Alignnullstring

Alignment of the legend.
MaxHeightnullint?

Maximum height of the legend, in pixels.
MaxWidthnullint?

Maximum width of the legend, in pixels.
FullSizenullbool?

Marks that this box should take the full width/height of the canvas (moving other boxes). This is unlikely to need to be changed in day-to-day use.
Reversenullbool?

Legend will show datasets in reverse order.
LabelsnullChartLegendLabel

Options to change legend labels.
Rtlnullbool?

true for rendering the legends from right to left.
TextDirectionnullstring

This will force the text direction 'rtl' or 'ltr' on the canvas for rendering the legend, regardless of the css specified on the canvas.
TitlenullChartLegendTitle

Options to change legend title.

ChartTooltips

NameDefaultType
Enablednullbool?

Are on-canvas tooltips enabled.
Modenullstring

Sets which elements appear in the tooltip.
Intersectnullbool?

If true, the tooltip mode applies only when the mouse position intersects with an element. If false, the mode will be applied at all times.
Positionnullstring

The mode for positioning the tooltip.
BackgroundColornullIndexableOption<object>

Background color of the tooltip.
TitleColornullIndexableOption<object>

Color of title text.
TitleFontnew ChartFont { Weight = "bold" }ChartFont

See Fonts.
TitleAlignnullstring

Horizontal alignment of the title text lines.
TitleSpacingnullint?

Spacing to add to top and bottom of each title line.
TitleMarginBottomnullint?

Margin to add on bottom of title section.
BodyColornullIndexableOption<object>

Color of body text.
BodyFontnullChartFont

See Fonts.
BodyAlignnullstring

Horizontal alignment of the body text lines.
BodySpacingnullint?

Spacing to add to top and bottom of each tooltip item.
FooterColornullIndexableOption<object>

Color of footer text.
FooterFontnullChartFont

See Fonts.
FooterAlignnullstring

Horizontal alignment of the footer text lines.
FooterSpacingnullint?

Spacing to add to top and bottom of each footer line.
FooterMarginTopnullint?

Margin to add before drawing the footer.
Paddingnullobject

Padding inside the tooltip.
CaretPaddingnullobject

Extra distance to move the end of the tooltip arrow away from the tooltip point.
CaretSizenullint?

Size, in px, of the tooltip arrow.
CornerRadiusnullint?

Radius of tooltip corner curves.
MultiKeyBackgroundnullIndexableOption<object>

Color to draw behind the colored boxes when multiple items are in the tooltip.
DisplayColorsnullbool?

If true, color boxes are shown in the tooltip.
BoxWidthnullint?

Width of the color box if displayColors is true.
BoxHeightnullint?

Height of the color box if displayColors is true.
BoxPaddingnullint?

Padding between the color box and the text.
UsePointStylenullbool?

Use the corresponding point style (from dataset options) instead of color boxes, ex: star, triangle etc. (size is based on the minimum value between boxWidth and boxHeight).
BorderColornullIndexableOption<object>

Color of the border.
BorderWidthnullint?

Size of the border.
Rtlnullbool?

true for rendering the tooltip from right to left.
TextDirectionnullstring

This will force the text direction 'rtl' or 'ltr on the canvas for rendering the tooltips, regardless of the css specified on the canvas.
XAlignnullstring

Position of the tooltip caret in the X direction.
  • "left" (default)
  • "center"
  • "right"
YAlignnullstring

Position of the tooltip caret in the Y direction.
  • "left" (default)
  • "center"
  • "right"

ChartAxis

NameDefaultType
Typenullstring

Type of scale being employed. Custom scales can be created and registered with a string key. This allows changing the type of an axis for a chart.
AlignToPixelsnullbool?

Align pixel values to device pixels.
Displaytruebool

Controls the axis global visibility (visible when true, hidden when false). When display: "auto", the axis is visible only if at least one associated dataset is visible.
Grid—ChartAxisGridLine

Grid line configuration. more....
Min—double?

User defined minimum number for the scale, overrides minimum value from data. more...
Max—double?

User defined maximum number for the scale, overrides maximum value from data. more...
Reverse—bool?

Reverse the scale.
Stacked—bool?

Should the data be stacked.
SuggestedMin—double?

Adjustment used when calculating the minimum data value. more...
SuggestedMax—double?

Adjustment used when calculating the maximum data value. more...
Ticks—ChartAxisTicks

Tick configuration.
Time—ChartAxisTime

Time configuration.
Weight—double?

The weight used to sort the axis. Higher weights are further away from the chart area.
Title—ChartScaleTitle

Defines options for the scale title. Note that this only applies to cartesian axes.
BeginAtZero—bool?

If true, scale will include 0 if it is not already included.
Grace—object

Percentage (string ending with %) or amount (number) for added room in the scale range above and below data.

ChartAxisTicks

NameDefaultType
BackdropColornullIndexableOption<object>

Color of label backdrops.
BackdropPaddingnullobject

Padding of label backdrop. See more...
CallbacknullExpression<Func<double, int, double[], string>>

Defines the Expression which will be converted to JavaScript as a string representation of the tick value as it should be displayed on the chart.

Eg. Callback = ( value, index, values ) => value / 1000 + "K"

Displaynullbool?

If true, show tick marks.
ColornullIndexableOption<object>

Color of ticks.
FontnullChartFont

Font color for tick labels.
MajornullChartAxisMajorTick

Major ticks configuration. Omitted options are inherited from options above.
Paddingnulldouble?

Sets the offset of the tick labels from the axis.
ShowLabelBackdropnullbool?

If true, draw a background behind the tick labels.
TextStrokeColornullIndexableOption<object>

The color of the stroke around the text.
TextStrokeWidthnulldouble?

Stroke width around the text.
Znulldouble?

z-index of tick layer. Useful when ticks are drawn on chart area. Values <= 0 are drawn under datasets, > 0 on top.
Countnullint?

The number of ticks to generate. If specified, this overrides the automatic generation.
Formatnullobject

The number format options used by the default label formatter.
Precisionnulldouble?

If defined and StepSize is not specified, the step size will be rounded to this many decimal places.
StepSizenulldouble?

User-defined fixed step size for the scale.