Code Monkey home page Code Monkey logo

erossini / blazorchartjs Goto Github PK

View Code? Open in Web Editor NEW
107.0 3.0 41.0 2.76 MB

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

Home Page: https://www.puresourcecode.com/dotnet/blazor/blazor-component-for-chartjs/

License: MIT License

C# 13.99% CSS 0.40% JavaScript 85.47% HTML 0.15%
blazor blazor-webassembly blazor-server blazor-application blazor-component net6 net7 net8

blazorchartjs's Introduction

ChartJs component for Blazor

This library is a wrap around Chart.js for using it with Blazor WebAssembly and Blazor Server. The component was built with NET6 until the version 6.0.44. The version 7.0 is for NET7. The version 8.x is for NET8.

Links

Articles

Installation

First, you have to add the component from NuGet. Then, open your index.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:

private BarChartConfig _config1;
private Chart _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 = new BarChartConfig()
{
    Options = new Options()
    {
        Plugins = new Plugins()
        {
            Legend = new Legend()
            {
                Align = LegendAlign.Center,
                Display = false,
                Position = LegendPosition.Right
            }
        },
        Scales = new Dictionary<string, Axis>()
        {
            {
                Scales.XAxisId, new Axis()
                {
                    Stacked = true,
                    Ticks = new Ticks()
                    {
                        MaxRotation = 0,
                        MinRotation = 0
                    }
                }
            },
            {
                Scales.YAxisId, new Axis()
                {
                    Stacked = true
                }
            }
        }
    }
};

Then, you have to define the Labels and the Datasets like that

_config1.Data.Labels = BarDataExamples.SimpleBarText;
_config1.Data.Datasets.Add(new Dataset()
{
    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:

private LineChartConfig _config1;
private Chart _chart1;

chart1 is the reference to the Chart 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 calling AddData function that is available on the chart.

Now, the function AddData allows to add a new value in a specific existing dataset. The definition of AddData is the following

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

For example, using _chart1, the following code adds a new label Test1 to the list of labels, and for the dataset 0 adds a random number.

_chart1.AddData(new List<string?>() { "Test1" }, 0, new List<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 function AddDataset. 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 using LineDataset using some of the properties this dataset has.

private void AddNewDataset()
{
    Random rd = new Random();
    List<decimal?> addDS = new List<decimal?>();
    for (int i = 0; i < 8; i++)
    {
        addDS.Add(rd.Next(i, 200));
    }

    var color = String.Format("#{0:X6}", rd.Next(0x1000000));

    _chart1.AddDataset<LineDataset>(new LineDataset()
        {
            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.

protected override async Task OnInitializedAsync()
{
    _config1 = new BarChartConfig()
        {
            Options = new Options()
            {
                Responsive = true,
                MaintainAspectRatio = false,
                Plugins = new Plugins()
                {
                    Legend = new Legend()
                    {
                        Align = Align.Center,
                        Display = true,
                        Position = LegendPosition.Right
                    },
                    Tooltip = new Tooltip()
                    {
                        Callbacks = new Callbacks()
                        {
                            Label = (ctx) =>
                            {
                                return new[] { 
                                    $"DataIndex: {ctx.DataIndex}\nDatasetIndex: {ctx.DatasetIndex}" };
                            },
                            Title = (ctx) =>
                            {
                                return new[] { $"This is the value {ctx.Value}" };
                            }
                        }
                    }
                },
                Scales = new Dictionary<string, Axis>()
                {
                    {
                        Scales.XAxisId, new Axis()
                        {
                            Stacked = true,
                            Ticks = new Ticks()
                            {
                                MaxRotation = 0,
                                MinRotation = 0
                            }
                        }
                    },
                    {
                        Scales.YAxisId, new Axis()
                        {
                            Stacked = true
                        }
                    }
                }
            }
        };

For more info, please see my posts on PureSourceCode.com.

Add labels to the chart

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

image

First, in the index.html, we have to add after the chart.js script, another script for this component. It is important to add the script for chartjs-plugin-datalabels after chart.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 property RegisterDataLabels under Options to true. 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 a LineChartConfig the code is

_config1 = new LineChartConfig()
{
    Options = new Options()
    {
        RegisterDataLabels = true,
        Plugins = new Plugins()
        {
            DataLabels = new DataLabels()
            {
                Align = DatalabelsAlign.Start,
                Anchor = DatalabelsAnchor.Start,
            }
        }
    }
};

With this code, the component will register the library in chart.js. It is possible to define a DataLabels for the entire chart. Also, each dataset can have its own DataLabels 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, under Options, there is OnClickAsync. Here, specified the function that has to receive the values (in this case clickAsync).

_config1 = new LineChartConfig()
    {
        Options = new Options()
        {
            OnClickAsync = clickAsync,
            ...
        }
    }

The function clickAsync receives as a parameter a CallbackGenericContext that contains the 3 values: DatasetIndex and DataIndex as int and the Value as decimal.

In the following example, the function changes the string ClickString using values.

public ValueTask clickAsync(CallbackGenericContext value)
{
    ClickString = $"Dataset index: {value.DatasetIndex} - " +
                    $"Value index: {value.DataIndex} - " + 
                    $"Value: {value.Value}";
    StateHasChanged();

    return ValueTask.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, under Options, there is OnHoverAsync. This provides the position of the cursor on the chart.

_config1 = new LineChartConfig()
    {
        Options = new Options()
        {
            OnHoverAsync = hoverAsync,
            ...
        }
    }

The function hoverAsync receives as parameter a HoverContext that contains the 2 values: DataX and DataY as decimal.

In the following example, the function changes the string HoverString using values.

private ValueTask hoverAsync(HoverContext ctx)
{
    HoverString = $"X: {ctx.DataX} - Y: {ctx.DataY}";
    StateHasChanged();

    return ValueTask.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
  • Marius for using some of the functions from his code

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 for Blazor WebAssembly and Blazor Server.

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

Blazor Components

Component name Forum NuGet Website Description
AnchorLink Forum NuGet badge An 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 for Blazor WebAssembly and Blazor Server
Autocomplete for Blazor Forum NuGet badge Simple and flexible autocomplete type-ahead functionality for Blazor WebAssembly and Blazor Server
Browser Detect for Blazor Forum NuGet badge Demo Browser detect for Blazor WebAssembly and Blazor Server
ChartJs for Blazor Forum NuGet badge Demo Add beautiful graphs based on ChartJs in your Blazor application
Clippy for Blazor Forum NuGet badge Demo Do you miss Clippy? Here the implementation for Blazor
CodeSnipper for Blazor Forum NuGet badge Add code snippet in your Blazor pages for 196 programming languages with 243 styles
Copy To Clipboard Forum NuGet badge Add a button to copy text in the clipboard
DataTable for Blazor Forum NuGet badge Demo DataTable component for Blazor WebAssembly and Blazor Server
Google Tag Manager Forum NuGet badge Demo Adds Google Tag Manager to the application and manages communication with GTM JavaScript (data layer).
Icons and flags for Blazor Forum NuGet badge Library with a lot of SVG icons and SVG flags to use in your Razor pages
ImageSelect for Blazor Forum NuGet badge This is a Blazor component to display a dropdown list with images based on ms-Dropdown by Marghoob Suleman. This component is built with NET7 for Blazor WebAssembly and Blazor Server
Markdown editor for Blazor Forum NuGet badge Demo This 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 Blazor Forum NuGet badge Simple Modal Dialog for Blazor WebAssembly
Modal windows for Blazor Forum NuGet badge Modal Windows for Blazor WebAssembly
Quill for Blazor Forum NuGet badge Quill 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
ScrollTabs NuGet badge Tabs with nice scroll (no scrollbar) and responsive
Segment for Blazor Forum NuGet badge This is a Segment component for Blazor Web Assembly and Blazor Server
Tabs for Blazor Forum NuGet badge This is a Tabs component for Blazor Web Assembly and Blazor Server
Timeline for Blazor Forum NuGet badge This is a new responsive timeline for Blazor Web Assembly and Blazor Server
Toast for Blazor Forum NuGet badge Toast notification for Blazor applications
Tours for Blazor Forum NuGet badge Guide your users in your Blazor applications
TreeView for Blazor Forum NuGet badge This component is a native Blazor TreeView component for Blazor WebAssembly and Blazor Server. The component is built with .NET7.
WorldMap for Blazor Forum NuGet badge Demo Show world maps with your data

C# libraries for .NET6

Component name Forum NuGet Description
PSC.Evaluator Forum NuGet badge PSC.Evaluator is a mathematical expressions evaluator library written in C#. Allows to evaluate mathematical, boolean, string and datetime expressions.
PSC.Extensions Forum NuGet badge A 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

blazorchartjs's People

Contributors

anthodingo avatar bdebaere avatar cfreyfh avatar erossini avatar heitoreleuterio avatar hollandar avatar osnipezzini avatar quimalborch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

blazorchartjs's Issues

Cannot Change font size of AXIS X,Y ticks not have fontsize

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Issue when publishing to Azure App Service

Hi,

Thank you for your library! It works very nice when running locally, but I'm having problems when running from an Azure App, below the console logs from the browser:

`GET https://myapp.azurewebsites.net/_content/PSC.Blazor.Components.Chartjs/Chart.js net::ERR_ABORTED 404

GET https://myapp.azurewebsites.net/_content/PSC.Blazor.Components.Chartjs/lib/Chart.js/chart.js net::ERR_ABORTED 404

blazor.server.js:1 [2022-07-11T08:48:34.681Z] Error: There was an unhandled exception on the current circuit, so this circuit will be terminated. For more details turn on detailed exceptions by setting 'DetailedErrors: true' in 'appSettings.Development.json' or set 'CircuitOptions.DetailedErrors'. `

Any idea about what's happening?

Thanks in advance

Let mariusmuntean/ChartJs.Blazor (no-longer-maintained) community know about this?

While I haven't been able to compare the feature-set between this and the no-longer-maintained mariusmuntean/ChartJs.Blazor, I'm excited about there being an actively maintained ChartJs Blazor implementation.

Would you like to contact that community (via their Issues) and let them know of your package? Or another option is to pull-in features from that or fork that.

There's certainly interest:
mariusmuntean/ChartJs.Blazor#199
mariusmuntean/ChartJs.Blazor#191
mariusmuntean/ChartJs.Blazor#160
mariusmuntean/ChartJs.Blazor#179

Thanks for considering!

Dispose reference

Hello Enrico,

I re-create the charts on demand and I have some memory leaks because some references must be disposed (I am not an expert on this issue).

1.- moduleTask in ChartjsInterop:

  public async ValueTask DisposeAsync()
  {
      if (moduleTask.IsValueCreated)
      {
          await (await moduleTask.Value).DisposeAsync();
      }
  }

2.- JsModule and dotNetObjectRef in Chart.razor. :

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    try
    {
        ...
        dotNetObjectRef?.Dispose();
        dotNetObjectRef = DotNetObjectReference.Create(Config);

        JSModule ??= new ChartJsInterop(JSRuntime);
        ....
    }
    catch (ObjectDisposedException)
    {
        // Sometimes the object reference is released but JS invoke some event.
    }
}
public async ValueTask DisposeAsync()
{
    dotNetObjectRef?.Dispose();
    dotNetObjectRef = null;

    if (JSModule is not null)
    {
         await JSModule.DisposeAsync();
        JSModule = null;
    }
}

Let me know what do you think :)
Thank you,
Gaston

Tooltip Style Modification

Hello there, the tooltip feature of the charts is amazing as it is, however it isn't flexible enough I think. I will like to request the options to being able to pass the BackgroundColor, Position and TitleColor

Something like this

Tooltip = new Tooltip()
{
    Callbacks = new Callbacks()
    {
        Label = (ctx) =>
        {
            return new[] { 
                $"DataIndex: {ctx.DataIndex}\nDatasetIndex: {ctx.DatasetIndex}" };
        },
        Title = (ctx) =>
        {
            return new[] { $"This is the value {ctx.Value}" };
        },
       BackgroundColor = new() { "#ffffff" }
    }
}

License?

I just noticed it -- there is no license given. So what is it? :-) It would be great to see OSI compliant one.

Please note that once you add open source license GitHub Copilot will start harvesting the code violating the license. This is why I started migration of my projects (for now I am evaluating CodeBerg and so far so good).

Crash when declare callback for Ticks on Bar Chart

Describe the bug
When i declare a Callback for Ticks, i receive a critical error when loading component.

To Reproduce
Steps to reproduce the behavior:

  1. Create a demo project
  2. Follow instructions for add this package on README
  3. Create a empty page amd add a new Bar Chart
  4. On Scales.YAxisId configuration, set a empty CallBack returning a empty array

Expected behavior
A bar chart with no labels on ticks (on left)

Screenshots
image
image

Desktop:

  • OS: Windows 11
  • Browser: Microsoft Edge
  • Version: Release

X-axis and color change

Hi,

Is there any way to change the color as per the requirement,
for example:
My Requirement is

  1. I want the color to be green in the bar chart when the value is less than 1.25
  2. I want the color to be orange in the bar chart when the value is 1.25 to 2.5
  3. I want the color to be Red in the bar chart when the value is 2.5 to 3.75
  4. I want the color to be black in the bar chart when the value is 3.75 to 5

Is this possible, If possible please let me know.

then I also want to Define the x-axis value in the bar chart, can I define it with my own values, Just started to use your chart work. If there is any example for this please link it here.

I'm a beginner, If anything I have asked is wrong, I'm sorry.

SyntaxError - Chart.js:46

Hello,

I get this error on startup: Uncaught SyntaxError: export declarations may only appear at top level of a module Chart.js:46
Can you see it?

Thank you,
Gaston.

Miss alignment in grouped stacked bard

Hello there, I want to create a grouped/stacked Chart, similar to this one https://www.chartjs.org/docs/latest/samples/bar/stacked-groups.html when I emulate the configuration, I get the following result.
act

This is the configuration and the dataset I use
`_configBar5 = new BarChartConfig()
{
Options = new Options()
{
Interaction = new ()
{
Intersect = false
},
Plugins = new Plugins()
{
Title = new Title()
{
Display = true,
Text = "Population growth (millions)",
Font = new Font()
{
Size = 18
}
}
},
Scales = new Dictionary<string, Axis>()
{
{
Scales.XAxisId, new Axis()
{
//Stacked = true,
BeginAtZero = true,
}
},
{
Scales.YAxisId, new Axis()
{
Stacked = true,
BeginAtZero = true,
}
}
},
}
};

    _configBar5.Data.Labels.AddRange(Labels);

    List<decimal?> Grouped1 = new List<decimal?>() { 133, 221, 783, 2478 };
    List<decimal?> Grouped2 = new List<decimal?>() { 408, 547, 675, 734 };

    _configBar5.Data.Datasets.Add(new BarDataset()
        {
            Stack = new() {"One"},
            Type = "bar",
            Label = "Africa",
            Data = Grouped1,
            BackgroundColor = new List<string>() { "#3e95cd" }
        });

    _configBar5.Data.Datasets.Add(new BarDataset()
    {
        Stack = new() { "One" },
        Label = "India",
            Type = "bar",
            Data = Grouped2,
        BackgroundColor = new List<string>() { "#8e5eff" }
    });

    _configBar5.Data.Datasets.Add(new BarDataset()
        {
            Stack = new() { "Two" },
            Label = "Europe",
            Type = "bar",
            Data = Grouped1,
            BackgroundColor = new List<string>() { "#8e5ea2" }
        });`

Missing license attribution & potential endorsement/redirect

Hey there, I'm Joel, co-author and ex-maintainer of ChartJs.Blazor.
First of all, thank you for maintaining this library and giving the users an alternative to our outdated one!

I was contacted in regard to a potential license violation, because it seems that this project is using code from ChartJs.Blazor without attribution of license and copyright. A very obvious case of that is ColorUtil, which is a 1:1 copy of ours (apart from the namespace).

I am glad our project was able to inspire you and that our code helped you kickstart the project, but I am disappointed that you don't ever mention it anywhere. Primarily, I would like to see it because we're all doing this in our free time and out of passion, so showing appreciation for the work of others that you are building on is in my opinion much needed to sustain a friendly open source community. Additionally, from a legal perspective, not attributing is in violation of the MIT license, which states:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Could you please add appropriate attribution to your readme?

The correct attribution for your license file would be the following IIRC. For the readme I'm sure you can come up with something fitting.

Copyright (c) 2019 Marius Muntean
Copyright (c) 2021 Joel L.
Copyright (c) 2024 Enrico Rossini

Aside from this, I think it might be a good idea to point users of our library to yours. If you are interested, I can arrange that after the attribution issue is fixed.

Thanks in advance. If you have any questions let me know :)

Kind regards,
Joel

Ability to set PointStyle to false to hide points.

Is your feature request related to a problem? Please describe.
When trying to configure a line chart to hide the points, I am limited to the properties in PSC.Blazor.Components.Chartjs.Models.Common.PointStyle. Trying to set PointStyle to false results in a compilation error.

Describe the solution you'd like
Either the ability to set PointStyle to false, or add PointStyle.None.

Describe alternatives you've considered
none

Additional context
https://www.chartjs.org/docs/latest/configuration/elements.html#point-styles

Show value on Line And Bar graph ?

Hi,

I am testing this component with line and bar graph.

At the moment i am missing the option to show the value on the graph it self.

I see it is supported by ChartJS (using plugin) is it somehow possible with this component ?

I would appreciate any pointers,

Thanks in advance.

Canvas height is always "width / 2"

Describe the bug
For line charts (and maybe others, I only tried this one), if setting width and height, the height parameter is ignored and is always "width / 2". This issue probably is related to #15

To Reproduce
Steps to reproduce the behavior:

  • Go to LineSimple.Razor and set width and height, e. g.
    <Chart Config="_config1" @ref="_chart1" Width="500px" Height="400px"></Chart>
  • Run the demo and navigate to the "Line Simple" demo
  • Open the browsers developer tools
  • Using the element picker, check the canvas element
  • See width and height: height: 250px; width: 500p

Expected behavior

  • height parameter is as defined, in this example 400px

Desktop (please complete the following information):

  • OS: Windows
  • Browser Chrome, Edge
  • Version: Chrome: 121.0.6167.86

Additional context
As far as I can see, the _resize method in chart.js (from line 6855) overrides the width and height:

  _resize(width, height) {
    const options = this.options;
    const canvas = this.canvas;
    const aspectRatio = options.maintainAspectRatio && this.aspectRatio;
    const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);
    const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();
    const mode = this.width ? 'resize' : 'attach';
    this.width = newSize.width;
    this.height = newSize.height;
    this._aspectRatio = this.aspectRatio;
    if (!retinaScale(this, newRatio, true)) {
      return;
    

If I change the lines setting the width to this, it works as expected:

    this.width = width;
    this.height = height;

So, "this.platform.getMaximumSize(canvas, width, height, aspectRatio);" returns a smaller maximum size than requested. Although I have an idea how this happens, I'm not sure what the best fix for this is. There probably is a reason why getMaximumSize returns a smaller size.

As a side note, I've noticed that the canvas element can be removed from Chart.razor:

<canvas id="@Config.CanvasId" style="@(Height != null ? $"height:{Height}" : "") @(Width != null ? $"width:{Width};" : "")"></canvas>

I can remove this line, and everything still works as usual. It seems the canvas is created later in javascript.

Different type charts don't render correctly when either has DataLabels enabled

Describe the bug
When you have a line graph and a pie chart in the same page, and either of them has registerdatalabels set to true,
The result is that based on order of appearance, one chart will be partially rendered, and the other not rendered at all.

To Reproduce
In a blazor server project, create a PieChart Component...

<h3>Pie Simple</h3>

<Chart Config="_config2" Height="400px" />

private PieChartConfig? _config2;
private Chart? _chart2;

protected override Task OnInitializedAsync()
{
    _config2 = new PieChartConfig
    {
        Options = new PieOptions()
        {
            Responsive = true,
            MaintainAspectRatio = false,
            RegisterDataLabels = true,
            Plugins = new Plugins()
            {
                DataLabels = new DataLabels()
                {
                    Align = DatalabelsAlign.Center,
                    Anchor = DatalabelsAnchor.Center,
                }
            }
        },
        Data =
        {
            Labels = PieDataExamples.SimplePieText
        }
    };

    _config2.Data.Datasets.Add(new PieDataset()
    {
        Label = "My First Dataset",
        Data = PieDataExamples.SimplePie.ToList(),
        BackgroundColor = SampleColors.PaletteBorder1,
        HoverOffset = 4,
        DataLabels = new DataLabels()
        {
            BackgroundColor = "black",
            BorderRadius = 4,
            Color = "white",
            Font = new Font()
            {
                Weight = "bold"
            },
            Padding = new Padding(6)
        }
    });
    return Task.CompletedTask;
}

and a LineGraph component...

<h3>LineGraph</h3>

<Chart Config="_config1" Height="400px" />

private LineChartConfig? _config1 = new();
private Chart? _chart1 = new();

protected override Task OnInitializedAsync()
{
    _config1 = new LineChartConfig
    {
        Options = new Options()
        {
            Responsive = true,
            MaintainAspectRatio = false,
            Plugins = new Plugins()
            {
                Zoom = new Zoom()
                {
                    Enabled = true,
                    Mode = "xy",
                    ZoomOptions = new ZoomOptions()
                    {
                        Wheel = new Wheel()
                        {
                            Enabled = true
                        },
                        Pinch = new Pinch()
                        {
                            Enabled = true
                        }
                    },
                    Pan = new Pan()
                    {
                        Enabled = true,
                        Mode = "x"
                    }
                }
            }
        },
        Data =
        {
            Labels = LineDataExamples.SimpleLineText
        }
    };

    _config1.Data.Datasets.Add(new LineDataset()
    {
        Label = "Line 1",
        Data = LineDataExamples.SimpleLine.ToList(),
        BorderColor = SampleColors.PaletteBorder1.FirstOrDefault()
    });

    _config1.Data.Datasets.Add(new LineDataset()
    {
        Label = "Line 2",
        Data = LineDataExamples.SimpleLine2.ToList(),
        BorderColor = SampleColors.PaletteBorder1.Skip(1).FirstOrDefault(),
    });
    _config1.Data.Datasets.Add(new LineDataset()
    {
        Label = "Line 3",
        Data = LineDataExamples.SimpleLine3.ToList(),
        BorderColor = SampleColors.PaletteBorder1.Skip(2).FirstOrDefault(),
    });

    return Task.CompletedTask;
}

Reference the components in the _Imports.razor and use them in the Home page...

@page "/"

<PageTitle>Dashboard</PageTitle>

<LineGraph />
<PieChart />

Once you run the application, you will see something like...

image

if you open dev tools and look at console, you can see...

image

if you comment out the RegisterDataLabels setting in the PieOptions inside of the PieChartConfig,
you can see both the line graph and the simple pie chart, but of course with no labels as below...

image

if you enable RegisterDataLabels and only use the simple pie component like below...

@page "/"

<PageTitle>Dashboard</PageTitle>

<PieChart />

The pie chart renders with no problems.

image

Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
Both charts render and the labels are visible where enabled.

Desktop (please complete the following information):

  • OS: Windows
  • Browser Chrome/Edge
  • Version 127.0

Additional context
I have also noticed that when both charts are used, in here
image
_labels does not exists as a key

Does OnChartClick and OnChartOver not fired?

Hello :)

Is your feature request related to a problem? Please describe.
I need to know when a bar on the Bar Chart is clicked. I tried with OnChartClick and OnChartOver events but it does not write nothing to the console. Can you help me?

<Chart Config="_config1" @ref="_chart1" Class="mt-2 ml-2" Width="100px" 
    OnChartClick="(i) => OnChartClick(i)"
    OnChartOver="() => OnChartOver()"></Chart>

@code {
...

    private void OnChartOver()
    {
        Console.WriteLine("ChartOver");
    }

    private void OnChartClick(int i)
    {
        Console.WriteLine("ChartClick " + i);
    }
}

Describe the solution you'd like
I'd like the OnChartClick and OnChartOver work (with their parameters) .

https://www.chartjs.org/docs/2.8.0/general/interactions/events.html -->
onHover: Called when any of the events fire. Called in the context of the chart and passed the event and an array of active elements (bars, points, etc).

OnClick: Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed the event and an array of active elements.

Thank you.

Reset Zoom

Is your feature request related to a problem? Please describe.
The JavaScript chart-js-plugin-zoom library has a 'resetZoom' function that can be called on the chart to reset it to the defaults that were used before any zooming or panning occurred. It would be really helpful if the same function existed in this library.

Describe the solution you'd like
Provide a function that can be called on the chart reference to reset the zoom.

Describe alternatives you've considered
I thought about setting limits to the x and y axes instead of adding a reset zoom button however it also seems like the limits functionality is not fully defined (the class is empty).

GPL License

This library is licensed under the GPL, which requires that any project utilizing it must disclose all of its source code, thereby prohibiting its use in commercial projects that do not intend to release their source code publicly. is that the intention?

Support for zoom/pan

This plugin demonstrates the feature perfectly.
Integration of this plugin would be a killer feature. It would be appreciated by many users including me of course!
There are no alternative open-source solutions for this yet, as far as I'm concerned.

Bar chart mouse over the bar is black

I have an issue with the bar color when the mouse is over a bar. This is the example and how the bars are displaying at the beginning.

image

When the mouse goes over a bar, the bar becomes black first

image

and then, after few seconds, the bar has the expected colour.

image

How can I fix it?

Thank you,
Henry

When I initialize a Chart, I get an error

I have a simple Razor page

@page "/test"

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

@code {
    private BarChartConfig? _config1;
    private Chart? _chart1;

    protected override async Task OnInitializedAsync()
    {
        _config1 = new BarChartConfig()
            {
                Options = new Options()
                {
                    IndexAxis = "y",
                    Responsive = true,
                    MaintainAspectRatio = false,
                    Plugins = new Plugins()
                    {
                        Legend = new Legend()
                        {
                            Align = Align.Center,
                            Display = false,
                            Position = LegendPosition.Right
                        }
                    },
                    Scales = new Dictionary<string, Axis>()
                {
                    {
                        Scales.XAxisId, new Axis()
                        {
                            Stacked = true,
                            Ticks = new Ticks()
                            {
                                MaxRotation = 0,
                                MinRotation = 0
                            }
                        }
                    },
                    {
                        Scales.YAxisId, new Axis()
                        {
                            Stacked = true
                        }
                    }
                }
                }
            };

        _config1.Data.Labels = new List<string>() { "1900", "1950", "1999", "2050" };
        _config1.Data.Datasets.Add(new BarDataset()
            {
                Label = "Value",
                Data = new List<decimal>() { 408, 547, 675, 734 },
                BackgroundColor = ColorPalettes.MainPalette,
                BorderColor = ColorPalettes.MainPalette,
                BorderWidth = 1
            });
    }
}

The error I get is

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object reference not set to an instance of an object.

image

Tooltip Title CallBack

Hello :)

Can you implement the Title Callback?

Tooltip = new Tooltip()
{
    Callbacks = new Callbacks()
    {
        Title = (ctx) => XXXX,    <--- add this functionality
        Label = (ctx) => null
    }                   
}

Thank you in advance

Tooltips callback doesn't work in Blazor Server

Describe the bug
Does not work in .NET 6.0 Blazor Server.

To Reproduce
Can reproduce by creating a fresh .NET 6 Blazor Server project, importing latest nuget version, and copying over relevant files from Demo site. I have replicated in this repo here: https://github.com/riley-cochrane/ChartJSTest
Run site
Go to https://localhost:7245/testgraph
Hover over bar on bar graph and no tool tip displays.

Console displays error:
Uncaught Error: The current dispatcher does not support synchronous calls from JS to .NET. Use invokeMethodAsync instead. at y (blazor.server.js:1:1840) at e.invokeMethod (blazor.server.js:1:2834) at config.options.plugins.tooltip.callbacks.title (Chart.js:81:27) at Tooltip.getTitle (chart.js:11425:35) at Tooltip.update (chart.js:11510:25) at Tooltip.handleEvent (chart.js:11875:14) at Object.afterEvent (chart.js:11936:25) at callback (chart.js:53:15) at PluginService._notify (chart.js:6316:11) at PluginService.notify (chart.js:6303:25)

Any fix for this? Can make local changes to create a new version if necessary.

Thanks,
Riley

StepSize Parameter

Hello, one last thing :)

Can you implement the StepSize?

Scales.YAxisId, new Axis()
{
    Display = false,
    Ticks = new()
    {
       stepSize <-- Add this functionality 
    }
}

The Chartjs' config javascript:

scales: {
    y: {
        ticks: {stepSize: 1}
    }
}

Thank you in advance

Question: Pie chart options?

I'd like to create pie charts which have an arc of 180 degrees. Is it possible to set circumference and rotation options? For example, in pure JavaScript I would do this:

var chart = new Chart(canvas, {
  type: 'doughnut',
  data: ['400', '200'],
  options: {
    rotation: -90,
    circumference: 180,
}

Support for customising legend labels.

Is your feature request related to a problem? Please describe.
There is no ability to customise the appearance of a chart legend's labels, as there is no corresponding property in PSC.Blazor.Components.Chartjs.Models.Common.Legend.

Describe the solution you'd like
I would like the ability to customise a chart's legend labels, through the Legend plugin. (e.g. to display circles instead of boxes for datasets.) It is not possible to do this, as far as I can tell, with the current release.

Describe alternatives you've considered
none

Additional context
https://www.chartjs.org/docs/3.9.1/configuration/legend.html#legend-label-configuration

Line and Labels

I have checked the line and labels chart, and I tried it but on the webpage, it shows a line with labels like 65, 59, 91, etc.
But when I tried with the code you have given in linesimplelabel.razor, It doesn't show any label.
I'm getting lines without labels like this:

Screenshot 2023-05-08 192108

Is the code you have given correct, does it show the lines with the label, or do have to do anything else to get the labels?

Please let me know @erossini

Refresh Chart with new Data

Hey
I just stumbled upon your project and tried it out in my Blazor Webassembly Project.
Works pretty well on first load until the point, when I fetched new Data from an Api and tried to refresh the Chart.

Maybe I am just missing something or this is not implemented yet.
I tried removing and adding a new Config with the new Data, but nothing happens.

In the main ChartJS Project you can just call chart.update(); but did not found something similar here.

Is there a simple solution to refresh the Chart through your Wrapper Library?

Best regards
Michael

Re-rendering (i.e. responsive = True) broken in 6.0.10, 6.0.11 and 6.0.12

These versions contain the following code not present in the source code repository in wwwroot/Chart.js:

    chart.options.animation.onComplete = function (ctx) {
        window["AnimationComplete1"](ctx);
        DotNet.invokeMethodAsync('PSC.Blazor.Components.Chartjs', 'AnimationCompleted');
    }

    chart.options.scales.x.ticks.callback = function (val, index) {
        window["TickEvent1"](val, index);
        DotNet.invokeMethodAsync('PSC.Blazor.Components.Chartjs', 'ChartScaleXTicks', val, index);
    }

As there are no functions on the window object named AnimationComplete1 and TickEvent1, these cause Javascript errors resulting in no re-rendering taking place. In practice, this means as soon as the window is shrunk to a size that requires a re-render, the chart disappears.

6.0.9 works in this regard, since it does not have these lines of code

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.