mariusmuntean / chartjs.blazor Goto Github PK
View Code? Open in Web Editor NEWBrings Chart.js charts to Blazor
Home Page: https://www.iheartblazor.com/
License: MIT License
Brings Chart.js charts to Blazor
Home Page: https://www.iheartblazor.com/
License: MIT License
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?
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.
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.
all charts
If i add @OnClick:stopPropagation="true" to the chart, run OnClickHandler but not propagate to his parent div clickevent.
Other parameters, etc.
Thanks in advance.
I guess, it would be cool to have a nice icon for the NuGet package (and the Gitter community). I would provide one on my own, but I'm actually not that good in such things 😕
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.
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
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();
}
Migrated from Joelius300/ChartJSBlazor#55:
We should somehow make it possible to support callbacks (e.g. https://www.chartjs.org/docs/latest/configuration/tooltip.html#tooltip-callbacks).
Client-Side and server side.
Support for callbacks if possible. (I don't have an idea yet how to support them...
Use the filling modes for Line and Radar chart in a typesafe manner.
The properties are already there in LineDataset
and in RadarDataset
.
LineDataset
it's of type bool
so you can only disable it or use 'origin' (alias when true).RadarDataset
it's of type object
and there is a description to what values you can use.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
I just wanted to know whether this project is still maintained or not.
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
In enkodellc/blazorboilerplate#12 there was a request if I can add the Chart.Js Blazor examples to https://github.com/enkodellc/blazorboilerplate. In my opinion, this would make sense once the repositories are merged and the charts are reworked.
Migrated from Joelius300/ChartJSBlazor#76:
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
All.
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";
}
None.
Example: https://visualstudiomagazine.com/blogs/tool-tracker/2018/11/an-ad-hoc-approach.aspx.
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...
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'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?
https://www.iheartblazor.com/doughnutchart
hit update repeatedly to see what happens...
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?
I have tried this lib with core 3 preview 9, get lot of errors and I assume it is not compatible.
Is there plans for release a version that is compatible with core 3?
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",
}
}
}
};
}
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?
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.
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?
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.
Many times It is necessary to customize ticks in axis and this is normally do it using callback.
https://www.chartjs.org/docs/latest/axes/labelling.html#creating-custom-tick-formats
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.
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?
All charts
I'd like to suggest to add full OptionsTitle support, so I can change a Title color.
Default color looks bad on within theme and I can't change it with css.
https://www.chartjs.org/docs/latest/configuration/title.html
Thank You!
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.
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:
How can it be solved?
10x!
Migrated from Joelius300/ChartJSBlazor#34:
Maybe support https://github.com/chartjs/chartjs-plugin-datalabels.
I don't have an idea how at the moment, but it must be possible.
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
LineChart
The defined OnClick handler is not being fired when the bar is click, but when the legend is clicked
@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" />
@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();
}
}`
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).
All charts
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
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.
Change the js/ts on your own and link it statically but that's not desirable.
Here are the easing options and some more information we might need.
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.
my project need to financial chart but ChartJs.Blazor is not support.
i think, chartjs.blazor can be support, so, i import chartjs-chart-financial.js and tested
watch this repository Jong-uk-kim/ChartJs.Blazor
if can migrate this, it make me happy.
thank you
I cloned this project but could not run as it said "The run command property is not defined" :/
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.
All charts.
I think something like a 'Plugins' property in the Common property set could do the job, but I'm not sure.
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.
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.
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.
Migrated from Joelius300/ChartJSBlazor#2.
I am trying to display two ChartJsLineCharts on the same page. Only one grid is displayed. Second grid is not rendered and displayed.
Pretty much the title
ChartJsLineChart but i haven't tried other
Steps to reproduce the behavior:
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
OnClick callback should be called without throwing an exception
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
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?
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?
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.
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
It would be nice if Labels is declared without having to initialize it prior using AddRange such as here
_config.Data.Labels.AddRange(new[] {"A", "B", "C", "D"});
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.
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,
}
}
}
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.
ChartJsBarChart
Steps to reproduce the behavior:
All of the data should be visible within a bar chart
If applicable, add screenshots to help explain your problem.
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.
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);
}
}
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 :-)
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
All charts.
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.
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.
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!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.