Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Creates beautiful charts in Blazor using Chart.js. Library for NET6, NET7 and NET8. Source code and demo available.

License

NotificationsYou must be signed in to change notification settings

erossini/BlazorChartjs

Repository files navigation

This library is a wrap aroundChart.js for using it withBlazor WebAssembly andBlazor Server. The component was built withNET6 until the version6.0.44. The version7.0 is forNET7.The version8.x is forNET8.

Links

Articles

Installation

First, you have to add the component fromNuGet. Then, open yourindex.html or_Host and add at the end of the page the following scripts:

<script src="_content/PSC.Blazor.Components.Chartjs/lib/Chart.js/chart.js"></script><script src="_content/PSC.Blazor.Components.Chartjs/Chart.js" type="module"></script>

The first script is the Chart.js library version 3.7.1 because I'm using this version to create the components. You can use other sources for it but maybe you can face issues in other versions.

Then, open your_Imports.razor and add the following:

@using PSC.Blazor.Components.Chartjs@using PSC.Blazor.Components.Chartjs.Enums@using PSC.Blazor.Components.Chartjs.Models@using PSC.Blazor.Components.Chartjs.Models.Common@using PSC.Blazor.Components.Chartjs.Models.Bar@using PSC.Blazor.Components.Chartjs.Models.Bubble@using PSC.Blazor.Components.Chartjs.Models.Doughnut@using PSC.Blazor.Components.Chartjs.Models.Line@using PSC.Blazor.Components.Chartjs.Models.Pie@using PSC.Blazor.Components.Chartjs.Models.Polar@using PSC.Blazor.Components.Chartjs.Models.Radar@using PSC.Blazor.Components.Chartjs.Models.Scatter

There is a namespace for each chart plus the common namespaces (Enum, Models and the base).

Add a new chart

On your page you can create a new chart by adding this code

<Chart Config="_config1" @ref="_chart1"></Chart>

In the code section you have to define the variables:

privateBarChartConfig_config1;privateChart_chart1;

Then, you can pass the configuration for the chart into_config1 (in the example code above). For a bar chart, the configuration is

_config1=newBarChartConfig(){Options=newOptions(){Plugins=newPlugins(){Legend=newLegend(){Align=LegendAlign.Center,Display=false,Position=LegendPosition.Right}},Scales=newDictionary<string,Axis>(){{Scales.XAxisId,newAxis(){Stacked=true,Ticks=newTicks(){MaxRotation=0,MinRotation=0}}},{Scales.YAxisId,newAxis(){Stacked=true}}}}};

Then, you have to define theLabels and theDatasets like that

_config1.Data.Labels=BarDataExamples.SimpleBarText;_config1.Data.Datasets.Add(newDataset(){Label="Value",Data=BarDataExamples.SimpleBar.Select(l=>l.Value).ToList(),BackgroundColor=Colors.Palette1,BorderColor=Colors.PaletteBorder1,BorderWidth=1});

The result of the code above is this chart

image

Implemented charts

  • Bar chart
  • Line chart
  • Area
  • Other charts
    • Scatter
    • Scatter - Multi axis
    • Doughnut
    • Pie
    • Multi Series Pie
    • Polar area
    • Radar
    • Radar skip points
    • Combo bar/line
    • Stacked bar/line

Add new values

When a graph is created, it means that the configuration is already defined and the datasets are passed to the chart engine. Without recreating the graph, it is possible to add a new value to a specific dataset and/or add a completely new dataset to the graph.

On your page, create a new chart by adding this code

<Chart Config="_config1" @ref="_chart1"></Chart>

In the code section you have to define the variables:

privateLineChartConfig_config1;privateChart_chart1;

chart1 is the reference to theChart component and from it, you can access all the functions and properties the component has to offer.

Add a new value

In an existing graph, it is possible to add a single new value to a specific dataset callingAddData function that is available on the chart.

Now, the functionAddData allows to add a new value in a specific existing dataset. The definition ofAddData is the following

AddData(List<string>labels,intdatasetIndex,List<decimal?>data)

For example, using _chart1, the following code adds a new labelTest1 to the list of labels, and for the dataset0 adds a random number.

_chart1.AddData(newList<string?>(){"Test1"},0,newList<decimal?>(){rd.Next(0,200)});

The result is visible in the following screenshot.

chart-addnewdata

Add a new dataset

It is also possible to add a completely new dataset to the graph. For that, there is the functionAddDataset. This function requires a new dataset of the same format as the others already existing in the chart.

For example, this code adds a new dataset usingLineDataset using some of the properties this dataset has.

privatevoidAddNewDataset(){Randomrd=newRandom();List<decimal?>addDS=newList<decimal?>();for(inti=0;i<8;i++){addDS.Add(rd.Next(i,200));}varcolor=String.Format("#{0:X6}",rd.Next(0x1000000));_chart1.AddDataset<LineDataset>(newLineDataset(){Label=$"Dataset{DateTime.Now}",Data=addDS,BorderColor=color,Fill=false});}

The result of this code is the following screenshot.

chart-addnewdataset

Callbacks

The component has a few callbacks (more in development) to customize your chart. The callbacks are ready to use are:

  • Tooltip
    • Labels
    • Titles

How to use it

In the configuration of the chart in your Blazor page, you can add your custom code for each callback.For an example, see the following code.

protectedoverrideasyncTaskOnInitializedAsync(){_config1=newBarChartConfig(){Options=newOptions(){Responsive=true,MaintainAspectRatio=false,Plugins=newPlugins(){Legend=newLegend(){Align=Align.Center,Display=true,Position=LegendPosition.Right},Tooltip=newTooltip(){Callbacks=newCallbacks(){Label=(ctx)=>{returnnew[]{$"DataIndex:{ctx.DataIndex}\nDatasetIndex:{ctx.DatasetIndex}"};},Title=(ctx)=>{returnnew[]{$"This is the value{ctx.Value}"};}}}},Scales=newDictionary<string,Axis>(){{Scales.XAxisId,newAxis(){Stacked=true,Ticks=newTicks(){MaxRotation=0,MinRotation=0}}},{Scales.YAxisId,newAxis(){Stacked=true}}}}};

For more info, please see my posts onPureSourceCode.com.

Add labels to the chart

I added thechartjs-plugin-datalabels plugin in the component. This plugin shows the labels for each point in each graph. For more details about this plugin, visit itswebsite.

image

First, in theindex.html, we have to add after thechart.js script, another script for this component. It is important to add the script forchartjs-plugin-datalabels afterchart.js. If the order is different, the plugin could not work. For example

<script src="_content/PSC.Blazor.Components.Chartjs/lib/Chart.js/chart.js"></script><script src="_content/PSC.Blazor.Components.Chartjs/lib/hammer.js/hammer.js"></script><script src="_content/PSC.Blazor.Components.Chartjs/lib/chartjs-plugin-zoom/chartjs-plugin-zoom.js"></script><script src="_content/PSC.Blazor.Components.Chartjs/lib/chartjs-plugin-datalabels/chartjs-plugin-datalabels.js"></script>

In the code, you have to change the propertyRegisterDataLabels underOptions totrue. That asks to the component to register the library if the library is added to the page and there is data to show. For example, if I define aLineChartConfig the code is

_config1=newLineChartConfig(){Options=newOptions(){RegisterDataLabels=true,Plugins=newPlugins(){DataLabels=newDataLabels(){Align=DatalabelsAlign.Start,Anchor=DatalabelsAnchor.Start,}}}};

With this code, the component will register the library inchart.js. It is possible to define aDataLabels for the entire chart. Also, each dataset can have its ownDataLabels that rewrites the common settings.

OnClickAsync

When a user click on a point on the chart with a value, it is possible to add in the chart configuration a specific function to receive the data for that point ad in particular the index of the dataset, the index of the value in the dataset and the value.

<Chart Config="_config1" @ref="_chart1" Height="400px"></Chart>

In the configuration, underOptions, there isOnClickAsync. Here, specified the function that has to receive the values (in this caseclickAsync).

_config1=newLineChartConfig(){Options=newOptions(){OnClickAsync=clickAsync,            ...}}

The functionclickAsync receives as a parameter aCallbackGenericContext that contains the 3 values:DatasetIndex andDataIndex as int and theValue as decimal.

In the following example, the function changes the stringClickString usingvalues.

publicValueTaskclickAsync(CallbackGenericContextvalue){ClickString=$"Dataset index:{value.DatasetIndex} - "+$"Value index:{value.DataIndex} - "+$"Value:{value.Value}";StateHasChanged();returnValueTask.CompletedTask;}

With this code, if the user clicks on a point, the function writes the values on the page.

image

OnHoverAsync

This function returns the position of the cursor on the chart. Define a new chart as usual.

<Chart Config="_config1" @ref="_chart1" Height="400px"></Chart>

In the configuration, underOptions, there isOnHoverAsync. This provides the position of the cursor on the chart.

_config1=newLineChartConfig(){Options=newOptions(){OnHoverAsync=hoverAsync,            ...}}

The functionhoverAsync receives as parameter aHoverContext that contains the 2 values:DataX andDataY as decimal.

In the following example, the function changes the stringHoverString usingvalues.

privateValueTaskhoverAsync(HoverContextctx){HoverString=$"X:{ctx.DataX} - Y:{ctx.DataY}";StateHasChanged();returnValueTask.CompletedTask;}

With this code, if the user moves the mouse on the chart, the function writes the values in the page.

chart-hover

Contribution

  • macias for adding the crosshair line to the components
  • Heitor Eleutério de Rezende for the migration to NET7 and adding:
    • Legend Labels Filtering
    • Support to Ticks' AutoSkip and Font properties
    • Tooltip Callback Label problem fixed.
    • Ticks callback

PureSourceCode.com

PureSourceCode.com is my personal blog where I publish posts about technologies and in particular source code and projects in.NET.

In the last few months, I created a lot of components forBlazor WebAssembly andBlazor Server.

My name is Enrico Rossini and you can contact me via:

Blazor Components

Component nameForumNuGetWebsiteDescription
AnchorLinkForumNuGet badgeAn anchor link is a web link that allows users to leapfrog to a specific point on a website page. It saves them the need to scroll and skim read and makes navigation easier. This component is forBlazor WebAssembly andBlazor Server
Autocomplete for BlazorForumNuGet badgeSimple and flexible autocomplete type-ahead functionality forBlazor WebAssembly andBlazor Server
Browser Detect for BlazorForumNuGet badgeDemoBrowser detect for Blazor WebAssembly and Blazor Server
ChartJs for BlazorForumNuGet badgeDemoAdd beautiful graphs based on ChartJs in your Blazor application
Clippy for BlazorForumNuGet badgeDemoDo you miss Clippy? Here the implementation for Blazor
CodeSnipper for BlazorForumNuGet badgeAdd code snippet in your Blazor pages for 196 programming languages with 243 styles
Copy To ClipboardForumNuGet badgeAdd a button to copy text in the clipboard
DataTable for BlazorForumNuGet badgeDemoDataTable component for Blazor WebAssembly and Blazor Server
Google Tag Manager[Forum]()NuGet badgeDemoAdds Google Tag Manager to the application and manages communication with GTM JavaScript (data layer).
Icons and flags for BlazorForumNuGet badgeLibrary with a lot of SVG icons and SVG flags to use in your Razor pages
ImageSelect for BlazorForumNuGet badgeThis is a Blazor component to display a dropdown list with images based on ms-Dropdown by Marghoob Suleman. This component is built with NET7 forBlazor WebAssembly andBlazor Server
Markdown editor for BlazorForumNuGet badgeDemoThis is a Markdown Editor for use in Blazor. It contains a live preview as well as an embeded help guide for users.
Modal dialog for BlazorForumNuGet badgeSimple Modal Dialog for Blazor WebAssembly
Modal windows for BlazorForumNuGet badgeModal Windows for Blazor WebAssembly
Quill for BlazorForumNuGet badgeQuill Component is a custom reusable control that allows us to easily consume Quill and place multiple instances of it on a single page in our Blazor application
ScrollTabsNuGet badgeTabs with nice scroll (no scrollbar) and responsive
Segment for BlazorForumNuGet badgeThis is a Segment component for Blazor Web Assembly and Blazor Server
Tabs for BlazorForumNuGet badgeThis is a Tabs component for Blazor Web Assembly and Blazor Server
Timeline for BlazorForumNuGet badgeThis is a new responsive timeline for Blazor Web Assembly and Blazor Server
Toast for BlazorForumNuGet badgeToast notification for Blazor applications
Tours for BlazorForumNuGet badgeGuide your users in your Blazor applications
TreeView for BlazorForumNuGet badgeThis component is a native Blazor TreeView component forBlazor WebAssembly andBlazor Server. The component is built with .NET7.
WorldMap for BlazorForumNuGet badgeDemoShow world maps with your data

C# libraries for .NET6

Component nameForumNuGetDescription
PSC.EvaluatorForumNuGet badgePSC.Evaluator is a mathematical expressions evaluator library written in C#. Allows to evaluate mathematical, boolean, string and datetime expressions.
PSC.ExtensionsForumNuGet badgeA lot of functions for .NET5 in a NuGet package that you can download for free. We collected in this package functions for everyday work to help you with claim, strings, enums, date and time, expressions...

More examples and documentation

Blazor

Blazor & NET8


About

Creates beautiful charts in Blazor using Chart.js. Library for NET6, NET7 and NET8. Source code and demo available.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp