Git Product home page Git Product logo

chartjs.blazor's Introduction

License: MIT GitHub issues GitHub forks GitHub stars

Join the chat at https://gitter.im/ChartJs-Blazor/community

NuGet Downloads (official NuGet)
NuGet Downloads (2.0 NuGet)

Netlify Status

Introduction

This is a Blazor library that wraps Chart.js. You can use it in both client- and server-side projects.

Don't know what Blazor is? Read this.

Getting started

Prerequisites

You need an IDE that supports Blazor and .NET Core SDK 3.x+

  1. Possible IDEs are: Visual Studio 2019 (Community Edition is fine) / VisualStudio for Mac, Jetbrains Rider and more
  2. .NET Core 3.1 or newer

Installation

Due to an unfortunate situation, the new 2.0 release is only available in an alternative NuGet package for the time being.
The original NuGet is ChartJs.Blazor.

Install our NuGet package: ChartJs.Blazor.Fork

You can install it with the Package Manager in your IDE or alternatively using the command line:

dotnet add package ChartJs.Blazor.Fork

Usage

Assets

Before you can start creating a chart, you have to add some static assets to your project.

In your _Host.cshtml (server-side) or in your index.html (client-side) add the following lines to the body tag after the _framework reference.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>

<!-- This is the glue between Blazor and Chart.js -->
<script src="_content/ChartJs.Blazor.Fork/ChartJsBlazorInterop.js"></script>

If you are using a time scale (TimeAxis), you also need to include Moment.js before including Chart.js.

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

If you don't want to use CDNs, check out the Chart.js installation page and the Moment.js installation page where you can find alternative ways to install the necessary libraries.

Imports

Now add a reference to ChartJs.Blazor in your _Imports.razor.

@using ChartJs.Blazor;

Other commonly used namespaces which you might want to import globally are:

  • ChartJs.Blazor.Common
  • ChartJs.Blazor.Common.Axes
  • ChartJs.Blazor.Common.Axes.Ticks
  • ChartJs.Blazor.Common.Enums
  • ChartJs.Blazor.Common.Handlers
  • ChartJs.Blazor.Common.Time
  • ChartJs.Blazor.Util
  • ChartJs.Blazor.Interop

Apart from that every chart type has a namespace e.g. ChartJs.Blazor.PieChart.

Chart

Now let's create a simple pie chart!

In order to use the classes for a pie chart, we need to add @using ChartJs.Blazor.PieChart to the top of our component.

Then we can add a Chart component anywhere in the markup like so:

<Chart Config="_config"></Chart>

The only thing left to do now is to provide the data and chart configuration by declaring an instance variable which we reference in the Chart component. We do this in the @code section of our component.

private PieConfig _config;

protected override void OnInitialized()
{
    _config = new PieConfig
    {
        Options = new PieOptions
        {
            Responsive = true,
            Title = new OptionsTitle
            {
                Display = true,
                Text = "ChartJs.Blazor Pie Chart"
            }
        }
    };

    foreach (string color in new[] { "Red", "Yellow", "Green", "Blue" })
    {
        _config.Data.Labels.Add(color);
    }

    PieDataset<int> dataset = new PieDataset<int>(new[] { 6, 5, 3, 7 })
    {
        BackgroundColor = new[]
        {
            ColorUtil.ColorHexString(255, 99, 132), // Slice 1 aka "Red"
            ColorUtil.ColorHexString(255, 205, 86), // Slice 2 aka "Yellow"
            ColorUtil.ColorHexString(75, 192, 192), // Slice 3 aka "Green"
            ColorUtil.ColorHexString(54, 162, 235), // Slice 4 aka "Blue"
        }
    };

    _config.Data.Datasets.Add(dataset);
}

This small sample should get you started and introduce you to the most basic concepts used for creating a chart. For more relevant examples, please see our samples.

Samples

Since Version 2.0 we'd like to keep the samples as similar to the official Chart.js samples as possible. Unfortunately, we're not up to date yet and many samples are missing. If you'd like to help, please check out this issue ❤️

To check out the code of the most recent (development version - explained below) samples, go to the ChartJs.Blazor.Samples/Client/Pages folder.

The ChartJs.Blazor.Samples folder contains the projects to showcase the samples. It's based on Suchiman/BlazorDualMode and allows you to switch between the server- and the client-side Blazor mode.

The samples should always be up to date with the current development on master. That means that the code you see on master might not work for your version. To browse the samples for the latest NuGet version, see the samples on the releases branch or select a specific tag. If there's not a sample for your use-case on the releases branch, check out the master one. Maybe someone already contributed what you're looking for and if not, why not do it yourself 😉

We would usually host the samples on https://www.iheartblazor.com but unfortunately, the version shown there is really old and we highly recommend downloading and running our samples on your machine.

Docs

We can't offer thorough docs at this time.

If you run into an issue, we recommend you to do the following steps:

  • It's simple but depending on your situation it helps to go to the definition of the C#-class you're working with. The XML-docs are usually quite detailed and often contain relevant links.
  • Browse our samples - You can find a lot of information there.
  • Browse the official Chart.js docs - This library is just a wrapper, there's a very high chance you can find what you need there.
  • Browse our issues - Your issue might've already been reported.
  • If none of that helped, open a new issue and fill out the template with your details. There's a good chance that someone else can help you.

Known Limitations

  • Client-side Blazor projects are currently affected by a bug in JSON.NET tracked by this issue. If you run into this issue, use one of these two workarounds:

    • Prefered Option - add a file named Linker.xml to the root of your client-side project to instruct the Mono linker to keep a certain constructor that JSON.NET invokes via reflection. Make sure to select BlazorLinkerDescription as the build action of the Linker.xml file. In case that your IDE doesn't offer that option, simply edit the .csproj file and add this to it:

      <ItemGroup>
          <BlazorLinkerDescriptor Include="Linker.xml" />
      </ItemGroup>

      The content of the Linker.xml should be similar to this (adjust to your project's entry point assembly):

      <?xml version="1.0" encoding="UTF-8" ?>
      <!--
      This file specifies which parts of the BCL or Blazor packages must not be
      stripped by the IL Linker even if they aren't referenced by user code.
      -->
      <linker>
          <assembly fullname="mscorlib">
              <!--
                  Preserve the methods in WasmRuntime because its methods are called by
                  JavaScript client-side code to implement timers.
                  Fixes: https://github.com/aspnet/Blazor/issues/239
              -->
              <type fullname="System.Threading.WasmRuntime" />
          </assembly>
          <assembly fullname="System.Core">
              <!--
                  System.Linq.Expressions* is required by Json.NET and any
                  expression.Compile caller. The assembly isn't stripped.
              -->
              <type fullname="System.Linq.Expressions*" />
          </assembly>
          <!-- The app's entry point assembly is listed. -->
          <assembly fullname="ChartJs.Blazor.Sample.ClientSide" />
          <!-- Take care of System.MissingMethodException: Constructor on type 'System.ComponentModel.ReferenceConverter' not found. -->
          <assembly fullname="System">
              <type fullname="System.ComponentModel.ReferenceConverter">
                  <method signature="System.Void .ctor(System.Type)" />
              </type>
          </assembly>
      </linker>
    • Alternative Option - manually invoke the ReferenceConverter constructor to avoid the linker optimizing it away. Example:

      private ReferenceConverter ReferenceConverter = new ReferenceConverter(typeof(Chart));

Contributors

We thank everyone who has taken their time to open detailed issues, discuss problems with us or contribute code to the repository. Without you, projects like this would be very hard to maintain!

Check out the list of contributors.

  • This project is currently unmaintained.
  • Owner of the project is Marius Muntean.

Contributing

We really like people helping us with the project. Nevertheless, take your time to read our contributing guidelines here.

chartjs.blazor's People

Contributors

akirayamamoto avatar esso23 avatar geracikha avatar ipax77 avatar jli103828 avatar joelius300 avatar larshg avatar marius-muntean avatar mariusmuntean avatar mashbrno avatar muqeet-khan avatar sepppenner avatar srowan avatar tomaszgrzmilas 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  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

chartjs.blazor's Issues

Unhandled Exception during build with latest previews

Hi,
After adding ChartJs.Blazor package to my Blazor client project, I got this error during build:
Unhandled Exception: Mono.Linker.MarkException: Error processing method: 'System.Void ChartJs.Blazor.ChartJS.Common.Legends.OnHover.DotNetInstanceHoverHandler::.ctor(ChartJs.Blazor.ChartJS.Common.Legends.OnHover.DotNetInstanceHoverHandler/LegendItemOnHover)' in assembly: 'ChartJs.Blazor.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve System.Void Microsoft.JSInterop.DotNetObjectRef::.ctor(System.Object)
at Mono.Linker.Steps.MarkStep.HandleUnresolvedMethod(MethodReference reference)
at Mono.Linker.Steps.MarkStep.MarkMethod(MethodReference reference)
at Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction)
at Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body)
at Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
at Mono.Linker.Steps.MarkStep.ProcessQueue()
--- End of inner exception stack trace ---
at Mono.Linker.Steps.MarkStep.ProcessQueue()
at Mono.Linker.Steps.MarkStep.ProcessPrimaryQueue()
at Mono.Linker.Steps.MarkStep.Process()
at Mono.Linker.Steps.MarkStep.Process(LinkContext context)
at Mono.Linker.Pipeline.ProcessStep(LinkContext context, IStep step)
at Mono.Linker.Pipeline.Process(LinkContext context)
at Mono.Linker.Driver.Run(ILogger customLogger)
at Mono.Linker.Driver.Execute(String[] args, ILogger customLogger)
at Mono.Linker.Driver.Main(String[] args)

Using:

  • VS 2019 Preview 2.0 (16.2.0)
  • Net Core 3.0 Preview
  • ChartJs.Blazor 0.9.1-preview
  • Blazor 3.0.0-preview6.19307.2

How can it be solved?
10x!

Ability to add plugins to chart options

Describe the feature request

This isn't necessarily a problem, but I'd like to add styling to my charts using the plugin chartjs-plugin-colorschemes, but currently I don't think this is possible.

Which charts does this feature request apply to?

All charts.

Describe the solution you'd like

I think something like a 'Plugins' property in the Common property set could do the job, but I'm not sure.

Describe alternatives you've considered

I don't think there is another way, because this has to be a property in the chart options. I'm going to look into just copying a style using the 'Tooltips' property.

Additional context

Don't have anything else to add. If this is easier than I'm thinking please let me know. Apologies for any incorrect terminology above. I'm new to C# and Blazor.

Remove build files from github

Describe the feature request

Currently the compiled javascript file including the js-map gets pushed to github. Since those are build files and only necessary in the final nuget, we don't need those on github. We should put them in the gitignore and delete them from github so only the typescript files stay up.

Using .Net Core 3.0 "version". no update when updating dataset from timer

Hi,

First of all, thanks for your amazing job.

I'm trying to use your library starting from sample.

If I use a button to add values to datasets the chart is updated, but if I update the dataset from a callback (timer) the update of the chart does not work until I call StateHasChanged() but I lost the "context" of the chart.

Could you help me about his ?

Regards

Apply changes from non-forked repo

Because I want to use this awesome library in a personal project of mine I downloaded the sources. I wasn't able to find the TimeAxis and there were many errors when updating everything to the latest previews.
For this reason I only copied the source of the actual library and worked on it (fix all the preview errors, lots of refactoring, add lots of properties which are supported by chartJs, ..).

Problem is, I didn't think about giving my adjustments back to the community. I really want to help with this awesome project but I don't know how I can transfer my commits and changes to a pull request here since it's not a fork and has a different folder structure.
I'm currently working on the TimeAxis which I have seen being requested so maybe there's interest for that. It's almost done and as I said, I'd love to let you include it in this repos.

One thing to keep in mind is that I have manually done some of the currently suggested pull request.
The ones I have (partly) done:

Another thing to keep in mind is that I'm almost only working on the Linechart and thus only really testing those properties. I have however reworked a lot of inheritance trees and options which are used for other charts as well. There shouldn't be any sideeffects but it's not tested like most of the library. It seems as many properties that are currently in the master branch weren't tested as well because some simply have the wrong name or are in the wrong place.

Does anyone know how you could import my changes without just copying the code and commiting all at once?

EDIT: my non-forked copy of this repo is here.

StopPropagation

Hi, i have a chart inside a div with an @OnClick function.
I want to stop click propagation.
If i click in the chart, for example, a doughnut with the click handler (from your samples)
OnClick = new DotNetInstanceClickHandler(OnClickHandler)
i dont want to run the onclick from the parent div.

Describe the feature request

With ASP.NET Core 3.1 there is a new option to do this (https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-core-3-1-preview-2):
@OnClick:stopPropagation="true"
But is not working with the chart component.

Which charts does this feature request apply to?

all charts

Describe the solution you'd like

If i add @OnClick:stopPropagation="true" to the chart, run OnClickHandler but not propagate to his parent div clickevent.

Describe alternatives you've considered

Other parameters, etc.

Additional context

Thanks in advance.

Suggesting minor echancements

I have been modifying my local version of ChartJs.Blazor, adding properties like 'Duration' to the ArcAnimation. I'm not a developer (just teaching myself Blazor now) & have zero experience with Github. Other than learning how to use Github, is there a way to contribute back to this project with the changes I've made?

Charts render only once

Hello it seems like this package is broken after last blazor update. Atleast for server-side projects.
In last version of Blazor changelog there is "fixed" Serialize server-side renders. https://github.com/aspnet/Blazor/releases

I dont know if its bug in blazor or in this package because I know very little about js but other things work for now. If its bug in blazor please tell them whats going on because I have no idea.

What happens:
If I open a page with chart it appear and I can update it or change it without issue. But when I go to different page and then come back the chart never show.
The chart have the default name "myFirstPieChart" and that seems to be issue because very simple workaround for this is just to change the CanvasId everytime then it show fine. I dont know how you render the chart but it seems like blazor thinks its already rendered or something like that.

protected override void OnInit()
{
    pieChartConfig = pieChartConfig ?? new PieChartConfig
    {
        CanvasId = "myFirstPieChart" + new Random().Next(),
        Options = new PieChartOptions
        {
            Text = "Sample chart from Blazor",
            Display = true,
            Responsive = true,
            Animation = new DoughnutAnimation { AnimateRotate = true, AnimateScale = true }
        },
        Data = new PieChartData
        {
            Labels = new List<string> { "A", "B", "C", "D" },
            Datasets = new List<PieChartDataset>
        {
            new PieChartDataset
            {
                BackgroundColor = new[] {"#ff6384", "#55ee84", "#4463ff", "#efefef"},
                Data = new List<int> {4, 5, 6, 7},
                Label = "Light Red",
                BorderWidth = 0,
                HoverBackgroundColor = new[] {"#f06384"},
                HoverBorderColor = new[] {"#f06384"},
                HoverBorderWidth = new[] {1}, BorderColor = "#ffffff",
            }
        }
        }
    };
}

Two charts on the same page

I am trying to display two ChartJsLineCharts on the same page. Only one grid is displayed. Second grid is not rendered and displayed.

Can't run

I cloned this project but could not run as it said "The run command property is not defined" :/

Error after installing

After having installed the package using the dotnet CLI

dotnet add package ChartJs.Blazor --version 0.9.0-preview

it started throwing the following error

Program.cs(12,23): error CS0433: The type 'IWebAssemblyHostBuilder' exists in both 'Microsoft.AspNetCore.Blazor.Browser, Version=0.7.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' and 'Microsoft.AspNetCore.Blazor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

I am running dotnet version 3.0.100-preview6-012264

Naming conventions discussion

In my repo we had a discussion about naming conventions regarding this project. It's quite lengthy and I cannot migrate it entirely so here's the link to it: Joelius300/ChartJSBlazor#22

If you have time, read the other discussion and want to make suggestions, feel free to leave a comment here (not on the issue there). I think it would be nice to compile our decisions into one big conventions file sometime in the future to keep the codebase as consistent as possible because there are lots of different styles and in many places the summaries are simply missing so it would be great to have a reference.

PieCharts and DonutCharts do not respect the Labels data element

For reference see the example pie charts and donut charts at https://www.iheartblazor.com

using the config:

var pieChartConfig = new PieChartConfig
            {
                CanvasId = "sample",
                Options = new PieChartOptions
                {
                    Text = "Sample Pie",
                    Display = true,
                    Responsive = true,
                    Animation = new DoughnutAnimation { AnimateRotate = true, AnimateScale = true }
                },
                Data = new PieChartData
                {
                    Labels = new List<string> { "first", "second" },
                    Datasets = new List<PieChartDataset>
                    {
                        new PieChartDataset
                        {
                            Label = "Amount",
                            BackgroundColor = "#00ACAC", "#21409A" ,
                            Data = new List<int> { 1, 2 },
                            BorderWidth = 2,
                            HoverBackgroundColor = new [] { "#BEBEBE" },
                            HoverBorderColor = new [] { "#A9A9A9" },
                            HoverBorderWidth = new[] {1},
                            BorderColor = "#ffffff",
                        }
                    }
                }
            };

I would expect to see labels at the top of the chart for "first" and "second", instead there is one label that reads "Amount" and when clicked will hide the chart altogether. The official javascript chart js library seems to behave as I've mentioned, see here. Is there a way to achieve this with ChartJs.Blazor ?

For clarity, I'd expect the examples posted at https://www.iheartblazor.com to have 1 label at the top of the chart for each color listed on the chart. Clicking on the label would hide that portion of the chart. Instead, what's there (and what I'm experiencing) is that there is only 1 label at the top of the chart and clicking it completely hides/shows the chart.

Typesafe filling mode

Describe the feature request

Use the filling modes for Line and Radar chart in a typesafe manner.

The properties are already there in LineDataset and in RadarDataset.

  • In LineDataset it's of type bool so you can only disable it or use 'origin' (alias when true).
  • In RadarDataset it's of type object and there is a description to what values you can use.

Docs

Describe the solution you'd like

We need a class FillingMode (derives from ObjectEnum) where you can use either an int, a string or a bool (private constructors). The supported values are here and you can also see the use cases below.

Here are the use cases we need to support:

  • Fill = FillingMode.Relative(2)
  • Fill = FillingMode.Relative(-1)
  • Fill = FillingMode.Absolute(1)
  • Fill = FillingMode.Disabled -> We might also use FillingMode.Off
  • Fill = FillingMode.Origin
  • Fill = FillingMode.Start
  • Fill = FillingMode.End

A nice to have would be to allow implicit boolean conversion which would be defined like this:

  • false = FillingMode.Disabled
  • true = FillingMode.Origin

Migration: Pass Chart elements by ref / ElementReference (not by id) to JSInterop

Migrated from Joelius300/ChartJSBlazor#76:

Describe the feature request

It would be a good idea to use the ElementReference type to reference the charts from C# to JS. Example (Although it's a bit outdated): https://visualstudiomagazine.com/blogs/tool-tracker/2018/11/an-ad-hoc-approach.aspx

Which charts does this feature request apply to?

All.

Describe the solution you'd like

Like in the example:

Razor:

<input type="text" ref="mytextbox" value="Peter" />

@code
{
    ElementReference mytextbox;

    protected override Task OnInitializedAsync()
    {
        await JSRuntime.Current.InvokeAsync<string>("SetName", mytextbox);
    }
}

Javascript:

function SetName(textbox) {
    textbox.value = "Vogel";
}

Describe alternatives you've considered

None.

Additional context

Example: https://visualstudiomagazine.com/blogs/tool-tracker/2018/11/an-ad-hoc-approach.aspx.

No chart rendered on server-hosted project

Alas, not having any luck with a brand-new server-hosted Blazor project. I have added the nuget package to both client and server projects and followed the instructions in GitHub and on the wiki to add the example PieChart.

A couple of observations which might provide clues...

  • env.WebRootPath is actually null when I run my server project. I've tried using this code...
 if (string.IsNullOrWhiteSpace(env.WebRootPath))
            {
                env.WebRootPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            }
            ChartJsBlazor.AddStaticResourcesToWebRootPath(env.WebRootPath);

but the chart is still not displayed.

  • I can't find any way to get PieChartAnimation so have just commented out the "Animation=" assignment in the example code.

I've also tried the linker.xml fix suggested in #20 but this makes no difference.

I notice that the startup code in program.cs is quite different between the sample code in GitHub (which does work!) and my actual server project. Mine looks like...


 public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseConfiguration(new ConfigurationBuilder()
                    .AddCommandLine(args)
                    .Build())
                .UseStartup<Startup>()
                .Build();
    }

Maybe this is a framework version problem?

Wrong paths to javascript files

Hey

According to the Wiki in point 4, you are supposed to include the following:

<script src="css/bootstrap/bootstrap-native.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script> <script src="ChartJsInterop.js" type="text/javascript" language="javascript"></script>

But I get an error when running the sample project:
Uncaught SyntaxError: Unexpected token < ChartJsInterop.js:1

And I get the above error and one equally about the bootstrap-native.min.js, since I haven't added that to my own project.

I found a CDN for bootstrap-native.minjs
//cdnjs.cloudflare.com/ajax/libs/bootstrap.native/2.0.24/bootstrap-native.min.js

and I can use the following path:

_content/ChartJs.Blazor/ChartJsInterop.js

to properly get the ChartJsInterop.js.

The charts does seem to work though, even when the above error(s) are present.
When I inspected the errors on my website, they showed 307 internal redirect.

But this doesn't seem to be the case in your example, so maybe that's not really the issue...

What is the intended way to properly refer to the mentioned files?

OnClick callback does not work, it throws an exception in the frontend

Describe the bug

Pretty much the title

Which Blazor project type is your bug related to?

  • Server-Side
    I am using the release 1.0.2

Which charts does this bug apply to?

ChartJsLineChart but i haven't tried other

To Reproduce

Steps to reproduce the behavior:

  1. Setup a OnClick callback on the chart LineConfig.LineOptions
  2. Go to the web browser (I tried Firefox and Chrome) and click on the chart
  3. A javascript error is thrown in the frontend:
TypeError: n.onClick.call is not a function 17 Chart.min.js:7:101051
    handleEvent https://localhost:5001/_content/ChartJs.Blazor/Chart.min.js:7
    eventHandler https://localhost:5001/_content/ChartJs.Blazor/Chart.min.js:7
    i https://localhost:5001/_content/ChartJs.Blazor/Chart.min.js:7
    <anonymous> https://localhost:5001/_content/ChartJs.Blazor/Chart.min.js:7

Expected behavior

OnClick callback should be called without throwing an exception

Unable to pass data to line chart other then TimeTuple<object>

Describe the bug

It is impossible to declare dataset with object such as decimal, integer etc. I only managed to successfully created a chart if TData is of Type TimeTuple
for example LineDataset<TimeTuple> where TData is always a class according to this.
public class LineDataset : BaseMixableDataset where TData : class

Which Blazor project type is your bug related to?

  • Client-Side

Which charts does this bug apply to?

LineChart

error RZ9978: The directives @addTagHelper, @removeTagHelper and @tagHelperPrefix are not valid in a component document.

After updating a solution from blazor 0.7 to 0.9 and ChartJs.Blazor to 0.91 I get this error thrown: error RZ9978: The directives @addTagHelper, @removeTagHelper and @tagHelperPrefix are not valid in a component document. Use '@using <namespace>' directive instead.

I think the getting started instructions need updating as this is what I have implemented:
3. Now you need to help VS a bit by adding this line @addTagHelper *,ChartJs.Blazor to _ViewImports.cshtml.

Support for time-axis

From the jschart documentation https://www.chartjs.org/docs/latest/axes/cartesian/time.html Chart.js can support time-series axes by passing in a Date for the x value. Just wondering if this could be supported in this package? AFAICS, it could be done in a number of ways - simplest would be to derive TimePoint from Point and treat the x coordinate as DateTime.ticks before converting to a JS Date on interop?

Change X and Y axis font color

I'm trying out the simple bar chart from the demo as a Blazor server experiment. Looks really good, but I can't figure out how to change the colors used for the text on the axis and data labels. Is there an example I can look to?

Chart does not show

Running the NugetDemo1.Demo does not show the BubblesChart. The reason for this perhaps simple complaint is that I cannot for the life of me get a simple Blazor App to display a simple ChartJS.Blazor chart. So I tried the above Demo project and it demonstrates the same problem.
The large sample does work however but I cannot see why and what the difference might be.
My claim is. A new Blazor app with the Nuget Pack and the edits in _ViewImports cannot display any chart.

Migration: Check if the label on dataset level is needed

Migrated from Joelius300/ChartJSBlazor#46:

From Joelius300/ChartJSBlazor#40 (comment):

We need to investigate whether the label on dataset basis is valid for all kind of charts.

For pie and doughnut, it has no effect: https://jsfiddle.net/g1anoety/ without the datalabels plugin enabled. (I would remove this for all charts where it's not yet needed and add it again if it's needed after we managed to get Joelius300/ChartJSBlazor#34 done).

Following https://www.chartjs.org/docs/latest/charts/:

I have asked the guys from Chart.Js to check this as well and tell us, what's the idea behind this: chartjs/Chart.js#6452.

BarChart color not being applied

Hello,
Very much enjoying what you've built here so far. I am experiencing an issue where the color of my bar chart bars are grey no matter what color I specify (I have tried using both hex and rgba). On your editable showcase, the color seems to apply fine. The BarChartData I am passing to my barchart looks as follows:

                Data = new BarChartData
                {
                    Labels = prevSixMonthNames,
                    Datasets = new List<BaseBarChartDataset>
                        {
                            new BarChartDataset
                            {
                                BackgroundColor = "#007bff",
                                Label = "Earnings",
                                Data =  new List<object>{9, 8, 7, 6, 5},
                                BorderWidth = 1,
                                BorderColor = "#0829FF",
                                HoverBackgroundColor = "#98F095",
                                HoverBorderColor = "#43F049",
                                BorderSkipped = null
                            },
                            new BarChartDataset
                            {
                                BackgroundColor = "#FF0F27",
                                Label = "Expenses",
                                Data = new List<object>{1, 2, 3, 4, 5},
                                BorderWidth = 1,
                                HoverBackgroundColor = "#98F095",
                                HoverBorderColor = "#43F049",
                                BorderColor = "#A30A19",
                                BorderSkipped = null,
                            }
                        }
                }


Zoom and pan support

Hello, as I understood currently here is no zooming or panning. Is there in plan to implement? Is iot possible to implement it at all?

Bar chart truncating first and last columns when using multiple datasets

Describe the bug

Bar chart truncating first and last columns when using multiple datasets. You can see that the width of the first and last columns appear to be half that of the columns in the middle. This can also be witnessed in a single dataset bar chart, but doesn't have the same impact of not previewing any data.

Which Blazor project type is your bug related to?

  • Server-Side

Which charts does this bug apply to?

ChartJsBarChart

To Reproduce

Steps to reproduce the behavior:

  1. Using this version of ChartJSBlazor '1.0.2'.
  2. Run this code 'The default VS template for Blazor server side'.
  3. With these arguments 'using the BarChart to chart the Celsius and Fahrenheit data from the forecasts service '.
  4. See error.

Expected behavior

All of the data should be visible within a bar chart

Screenshots

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

Additional context / logging

Replace the content of the FetchData.razor page with the code below. Note that in the screenshot I have charted Celsius twice for no other reason than to continue to review the behaviour of the chart.

Code example

Please provide full code examples below where possible to make it easier for the developers to check your issues.

@page "/fetchdata"

@using System.ComponentModel
@using logparser_results_dashboard.web.Data
@using ChartJs.Blazor.ChartJS.BarChart
@using ChartJs.Blazor.ChartJS.BarChart.Axes
@using ChartJs.Blazor.ChartJS.Common.Axes
@using ChartJs.Blazor.ChartJS.Common.Axes.Ticks
@using ChartJs.Blazor.ChartJS.Common.Properties
@using ChartJs.Blazor.ChartJS.Common.Wrappers
@using ChartJs.Blazor.Charts
@using ChartJs.Blazor.Util
@inject WeatherForecastService ForecastService

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
<div style="width:600px;height:300px">
    <ChartJs.Blazor.Charts.ChartJsBarChart @ref="_barChart" Config="@_barChartConfig" Width="400" Height="200" />
</div>    


    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    
    WeatherForecast[] forecasts;

    private ReferenceConverter ReferenceConverter = new ReferenceConverter(typeof(ChartJsBarChart));

    private BarConfig _barChartConfig;
    private ChartJsBarChart _barChart;
    private BarDataset<DoubleWrapper> _barCelciusDataSet;
    private BarDataset<DoubleWrapper> _barFarenheitsDataSet;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);

        _barChartConfig = new BarConfig
        {
            Options = new BarOptions
            {
                Title = new OptionsTitle
                {
                    Display = true,
                    Text = "Weather Chart"
                },
                Scales = new BarScales
                {
                    XAxes = new List<CartesianAxis>
                                        {
                                            new BarCategoryAxis
                                            {
                                                BarPercentage = 0.5,
                                                BarThickness = BarThickness.Flex
            }
        },
                    YAxes = new List<CartesianAxis>
                                        {
                                            new BarLinearCartesianAxis
                                            {
                                                Ticks = new LinearCartesianTicks
                                                {
                                                    BeginAtZero = false
                                                }
                                            }
                                        }
                }
            }
        };

        _barChartConfig.Data.Labels.AddRange(forecasts.OrderBy(o => o.Date).Select(x => x.Date.ToShortDateString()).ToArray());

        _barCelciusDataSet = new BarDataset<DoubleWrapper>
        {
            Label = "Celcius",
            BackgroundColor = ColorUtil.FromDrawingColor(System.Drawing.Color.Blue),
            BorderWidth = 0,
            HoverBackgroundColor = ColorUtil.FromDrawingColor(System.Drawing.Color.Blue),
            HoverBorderColor = ColorUtil.FromDrawingColor(System.Drawing.Color.Blue),
            HoverBorderWidth = 1,
            BorderColor = "#ffffff"
        };

        _barFarenheitsDataSet = new BarDataset<DoubleWrapper>
        {
            Label = "Farenheit",
            BackgroundColor = ColorUtil.FromDrawingColor(System.Drawing.Color.Red),
            BorderWidth = 0,
            HoverBackgroundColor = ColorUtil.FromDrawingColor(System.Drawing.Color.Red),
            HoverBorderColor = ColorUtil.FromDrawingColor(System.Drawing.Color.Red),
            HoverBorderWidth = 1,
            BorderColor = "#ffffff"
        };

        var _AnotherBarCelciusDataSet = new BarDataset<DoubleWrapper>
        {
            Label = "Another celcius",
            BackgroundColor = ColorUtil.FromDrawingColor(System.Drawing.Color.Green),
            BorderWidth = 0,
            HoverBackgroundColor = ColorUtil.FromDrawingColor(System.Drawing.Color.Green),
            HoverBorderColor = ColorUtil.FromDrawingColor(System.Drawing.Color.Green),
            HoverBorderWidth = 1,
            BorderColor = "#ffffff"
        };

        var _cData = forecasts.OrderBy(o => o.Date).Select(x => (double)x.TemperatureC).ToArray();
        var _fData = forecasts.OrderBy(o => o.Date).Select(x => (double)x.TemperatureF).ToArray();

        _barCelciusDataSet.AddRange(_cData.Wrap());
        _barFarenheitsDataSet.AddRange(_fData.Wrap());
        _AnotherBarCelciusDataSet.AddRange(_cData.Wrap());


        _barChartConfig.Data.Datasets.Add(_barCelciusDataSet);
        _barChartConfig.Data.Datasets.Add(_barFarenheitsDataSet);
        _barChartConfig.Data.Datasets.Add(_AnotherBarCelciusDataSet);
    }
}

Tooltip overflow is hidden

Describe the bug

Tooltip overflow is hidden when tooltip height is longer than the canvas

Which Blazor project type is your bug related to?

  • Server-Side

Which charts does this bug apply to?

BarCharts

Expected behavior

not to be hidden

Screenshots

Untitled

Chart not display after reload

Hi,

I am trying Blazor server side with this library and it works great, however, if I navigate away from the page that contains chart and comes back, the chart disappeared. I have included the below code and still does not work according to the documentation.

protected override void OnAfterRender()
{
    lineChartJs.Reload();
}

IE11 Compatibility?

Describe your question

Bit of a long shot - any idea on IE11 compatibility for ChartJS.Blazor for server-side? I'm using daddoon's Blazor/Polyfill which covers most basic scenarios, but I get a SCRIPT1002 Syntax Error on ChartJsBlazorInterop.js (3,1) in IE11's console. Are there any extra polyfills I might need?

Which Blazor project type is your question related to?

  • Server-Side

Which charts is this question related to?

All charts

Piechart support

First - great job and kudos to the entire team bought this capability with blazor.

Is there piechart support available today? couldnt find in the demo hence my ask.

Horizontal barchart doesn't show any bars

Hello,

I use latest feature/CleanupAndRefactorings branch and as far as I know it works really good but the horizontal barchart does not show any bars. You also can see it at your demo website.

OnClick handler not working on BarChart

The defined OnClick handler is not being fired when the bar is click, but when the legend is clicked

  • Server-Side

Code example

@page "/test"

@using ChartJs.Blazor.Charts
@using ChartJs.Blazor.ChartJS.Common.Properties
@using ChartJs.Blazor.Util
@using ChartJs.Blazor.ChartJS.BarChart
@using ChartJs.Blazor.ChartJS.BarChart.Axes
@using ChartJs.Blazor.ChartJS.Common.Axes
@using ChartJs.Blazor.ChartJS.Common.Wrappers
@using ChartJs.Blazor.ChartJS.Common.Axes.Ticks
@using ChartJs.Blazor.ChartJS.Common.Handlers.OnClickHandler
@using Newtonsoft.Json

<ChartJsBarChart @ref="barChartJs" Config="@_config" Height="250" />


Clear
<textarea rows="@rows" @bind-value="@eventargs" @bind-value:event="oninput" style="width: 100%; resize: both; height:auto "></textarea>

@code {

private ChartJsBarChart barChartJs;
private BarConfig _config;
public int Rows { get; set; } = 3;
private BarDataset<DoubleWrapper> _barDataSet;

public string EventArgs { get; set; } = "";

protected override void OnInitialized()
{
    _config = new BarConfig()
    {

        Options = new BarOptions
        {
            Title = new OptionsTitle
            {
                Display = true,
                Text = "Simple Bar Chart"
            },
            Scales = new BarScales
            {
                XAxes = new List<CartesianAxis>
            {
                    new BarCategoryAxis
                    {
                        BarPercentage = 0.5,
                        BarThickness = BarThickness.Flex
                    }
                },
                YAxes = new List<CartesianAxis>
            {
                    new BarLinearCartesianAxis
                    {
                        Ticks = new LinearCartesianTicks
                        {
                            BeginAtZero = true
                        }
                    }
                }
            },

            OnClick = new DotNetInstanceClickHandler(OnClickHandler),
            MaintainAspectRatio = false,
            Responsive = true
        }
    };

    _config.Data.Labels.AddRange(new[] { "A", "B", "C", "D" });

    _barDataSet = new BarDataset<DoubleWrapper>
    {
        Label = "My double dataset",
        BackgroundColor = new[] { ColorUtil.RandomColorString(), ColorUtil.RandomColorString(), ColorUtil.RandomColorString(), ColorUtil.RandomColorString() },
        BorderWidth = 0,
        HoverBackgroundColor = ColorUtil.RandomColorString(),
        HoverBorderColor = ColorUtil.RandomColorString(),
        HoverBorderWidth = 1,
        BorderColor = "#ffffff"
    };

    _barDataSet.AddRange(new double[] { 8, 5, 3, 7 }.Wrap());
    _config.Data.Datasets.Add(_barDataSet);

}

[JSInvokable]
public void OnClickHandler(object sender, object args)
{
    EventArgs += JsonConvert.SerializeObject(JsonConvert.DeserializeObject($"{Environment.NewLine}{args}"), Formatting.Indented);
    Rows = Math.Max(3, EventArgs.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length + 1);
    StateHasChanged();
}

private void OnClear()
{
    EventArgs = string.Empty;
    StateHasChanged();
}

}`

Incremental updates

First of all, thank you for this project! This makes it amazingly easy to add charts. I’ve done this so far with JavaScript and it is really time consuming. This will be a huge time saver for me :-)

Describe the feature request

After the chart has been rendered the first time, I would like to be able to add data to the chart without redrawing the whole chart again. Click on Add Data on this page to see the expected behavior:

https://www.chartjs.org/samples/latest/charts/bar/vertical.html

Which charts does this feature request apply to?

All charts.

Describe the solution you'd like

If I'm working with a PieDataset for instance, it would be nice to just being able to add data to this object and then the system figures out how to dynamically. Maybe this is crazy hard to do, I don’t know. But I can see that the javascript library seems to be able to figure deltas in a smart way.

Describe alternatives you've considered

Another way could be to have some delta functions we could call instead, that then calls into the JavaScript library. So, when we want to do incremental updates, we use these functions instead.

Additional context

I can’t say this is an important feature for me, but I think it’s worth mentioning. Also, I think this is an interesting problem :-)

Thanks again for all this amazing work!

Customizable chart-update

Describe the feature request

If I wanted to change how long it takes for the chart-update to render, I cannot do that because it's hardcoded without options in the ts-file (here).

Which charts does this feature request apply to?

All charts

Describe the solution you'd like

I'd like to be able to call Update on the chart-components with some additional, optional parameters like the duration, if the update should be lazy (can be interrupted) and which easing style. These should be optional parameters so

  1. you don't have to supply them
  2. you can only supply one or two if you want
  3. you can see the default values
  4. backwards-compatibility

However, since we'll have to implement a new string-enum, we won't be able to do it without an overload because an instance of that string-enum won't be a compile-time constant but that's not an issue.

These options are described here.

Describe alternatives you've considered

Change the js/ts on your own and link it statically but that's not desirable.

Additional context

Here are the easing options and some more information we might need.

I get an error when I use it in my project (nuget package)

I have created a small test example here:
https://github.com/larshg/ChartJSTest

It won't compile due to this error:
Pages\Index.cshtml(13,38,13,45): error CS0029: Cannot implicitly convert type 'Microsoft.AspNetCore.Blazor.ElementRef' to 'ChartJs.Blazor.Charts.ChartJsLineChart'

Do you think its an error on your side or on the Blazor side?

On a side node: the paramters Config, Width and Height is shown in red, as opposed to ref which is in purple.

In your project and Sample project they are all purple - but maybe there is a difference between using the nuget package and referencing the project directly?

Regards, Lars

Preparing Release 0.9.0

Increase version numbers
Extend documentation on how to use the library in client- and server-side projects
Credit the people who's PR were merged

Customising ChartTypes class

I found a great extension for chartJS which allows to create candlestick chart. https://github.com/chartjs/chartjs-chart-financial

I tired to implement Blazor extension version based on ChartJs.Blazor, However, I found that I cannot add additional ChartTypes. I used reflection to create valid objects.

public static class ChartTypeFactory
 {
     public static ChartTypes CreateCandlestick() =>
      Construct<ChartTypes>(
          new Type[] { typeof(string) },
          new object[] { "candlestick" }
      );

     public static ChartTypes CreateOhlc() =>
     Construct<ChartTypes>(
         new Type[] { typeof(string) },
         new object[] { "ohlc" }
     );

     public static T Construct<T>(Type[] paramTypes, object[] paramValues)
     {
         Type t = typeof(T);

         ConstructorInfo ci = t.GetConstructor(
             BindingFlags.Instance | BindingFlags.NonPublic,
             null, paramTypes, null);

         return (T)ci.Invoke(paramValues);
     }
 }

The sample project with candlestick chart can be access via link https://github.com/oleksiizapara/ChartJsBlazorFinancialSample

I hope that in future release the library will be able to do it straightforward.

May be it can be done via base class that can be inherited?

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.