Giter Site home page Giter Site logo

laytec-ag / plotly.blazor Goto Github PK

View Code? Open in Web Editor NEW
317.0 12.0 47.0 303.9 MB

This library packages the well-known charting library plotly.js into a razor component that can be used in a Blazor project.

License: MIT License

HTML 0.93% C# 98.92% JavaScript 0.12% CSS 0.04%
blazor plotly charting-library data-visualization webgl charts visualization dotnet aspnet aspnetcore blazor-webassembly razor chart plot visual-studio blazor-application csharp webassembly dotnet-core microsoft

plotly.blazor's Introduction

Plotly.Blazor

Build Status Examples Status NuGet Status Forks Stars License

This library packages the well-known charting library plotly.js into a Razor component that can be used in a Blazor project. The advantage of this wrapper is that the plotly scheme itself is used to generate the classes. So you can automatically update to the latest plotly.js version with the help of the generator.

Getting Started

Prerequisites

To create Blazor Server Apps, install the latest version of Visual Studio 2019 with the ASP.NET and web development workload. For Blazor WebAssembly you need at least Visual Studio 2019 16.6+. Another alternative would be to use Visual Studio code. Click here for more information.

Plotly.Blazor with version >= 2.0.0 requires .NET 6 or higher.

Installing

After you have created your Blazor project, you need to do the following steps:

Install the latest NuGet Package

Using Package Manager

Install-Package Plotly.Blazor

Using .NET CLI

dotnet add package Plotly.Blazor

If you are using 4.1.0 or lower, then add the following lines to your _Layout.cshtml above the _/framework/blazor.webassembly.js or _/framework/blazor.server.js

<script src="_content/Plotly.Blazor/plotly-latest.min.js" type="text/javascript"></script>
<script src="_content/Plotly.Blazor/plotly-interop.js" type="text/javascript"></script>

Add the following lines to your _Imports.razor

@using Plotly.Blazor
@using Plotly.Blazor.Traces

Now we're ready to go! ๐ŸŽ‰

Usage

Create the Razor component

Info: The chart reference is important so that we can update the chart later.

<PlotlyChart @bind-Config="config" @bind-Layout="layout" @bind-Data="data" @ref="chart"/>

Generate some initial data for your plot.

@code {
    PlotlyChart chart;
    Config config = new Config();
    Layout layout = new Layout();
    // Using of the interface IList is important for the event callback!
    IList<ITrace> data = new List<ITrace>
    {
        new Scatter
        {
            Name = "ScatterTrace",
            Mode = ModeFlag.Lines | ModeFlag.Markers,
            X = new List<object>{1,2,3},
            Y = new List<object>{1,2,3}
        }
    };
}

Generate some additional data for your plot.

private async Task AddData(int count = 100)
{
    if (!(chart.Data.FirstOrDefault() is Scatter scatter)) return;
    var (x, y) = Helper.GenerateData(scatter.X.Count + 1, scatter.X.Count + 1 + count);

    await chart.ExtendTrace(x, y, data.IndexOf(scatter));
}

Examples

Here you can find a running instance of the examples. This is always up-to-date with the current state of the develop branch.

What it might look like!

Image of Example

Missing Implementations

  • Events
  • Add multiple traces with one call
  • Delete multiple traces with one call
  • plotly.animate
  • plotly.addFrames
  • plotly.moveTraces

Contributors

Sean
Sean McLeish
Guido
Guido Altmann
Matthew
Matthew R Johnson
yaqian256/
yaqian256
Jesus
Jesus Vaquerizo
parnold75/
parnold75

Versioning

We implement SemVer using GitVersion

License

This project is licensed under the MIT License - see the LICENSE file for details

plotly.blazor's People

Contributors

alfattack avatar centreboard avatar danielchalmers avatar dependabot-preview[bot] avatar dependabot[bot] avatar georg-jung avatar github-actions[bot] avatar guido-altmann avatar jacekpapiniak avatar jvaque avatar parnold75 avatar sean-mcl avatar seanmcleish avatar yaqian256 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

plotly.blazor's Issues

Refresh Pie or Bar charts

Thanks for this contribution guys, It's working beautifully!

However, when I update the parameters, I new up a new list and re-calculate the data, however the chart doesn't refresh...
I tried by calling the chart.React method and still can't get it to update.

Do you have any ideas of what it could be?

Update to .NET 6

The current version works fine with .NET 6, but it seems worth updating for a few reasons:

  • The option I've outlined in #27 requires updates made to event handling in Blazor in .NET 6.
  • Dependabot is submitting pull requests to use version 6 nuget packages
  • .NET 5 is out of support on May 08, 2022

Difference in debug mode and build

I am using your repo as a base for a dashboard like website thats supposed to run only locally. I did not change anything in the structure. When I run the app in debug mode right out of VS, either IIS or just the examples project it all works fine, renders, all graphs are shown, no errors etc. I do have some warning because async methods crash some of the graphs but for a local environment sync methods should work fine I guess.
So when building the app, starting the exe and calling localhost in the browser, the app gets rendered partly, graphs are not rendered at all and when chanhing sites via the menu it crashes. Seems to be an issue with java interop, I paste the error and warnings from the console here.
If you have any idea what this is about I'd be happy about your answer. I have intermediate experience with c# but almost none in blazor yet.

Debug from visual studio
grafik

Debug or Release from build folder:
grafik

Errors/Warnings when running from Debug/Release:
grafik

Could not find 'plotlyInterop.newPlot' ('plotlyInterop' was undefined).

I used this library in the .net5 project. I added the library package according to the instructions in the markdown document, and the console reported an error during runtime:

  Unhandled exception rendering component: Could not find 'plotlyInterop.newPlot' ('plotlyInterop' was undefined).

Error: Could not find 'plotlyInterop.newPlot' ('plotlyInterop' was undefined).
at https://localhost:5001/_framework/blazor.server.js:1:67713
at Array.forEach ()
at e.findFunction (https://localhost:5001/_framework/blazor.server.js:1:67673)
at v (https://localhost:5001/_framework/blazor.server.js:1:69415)
at https://localhost:5001/_framework/blazor.server.js:1:70361
at new Promise ()
at e.beginInvokeJSFromDotNet (https://localhost:5001/_framework/blazor.server.js:1:70334)
at https://localhost:5001/_framework/blazor.server.js:1:26441
at Array.forEach ()
at e.invokeClientMethod (https://localhost:5001/_framework/blazor.server.js:1:26411)
Microsoft.JSInterop.JSException: Could not find 'plotlyInterop.newPlot' ('plotlyInterop' was undefined).

Surface chart orientation resets on React()

I'm wondering if it is possible to retain the viewport orientation for a Surface chart after calling React()? I make use of showing and hiding surfaces on a chart quite regularly, but having to manually reorient the chart to look at a particular location after hiding a surface and calling React() adds a lot of tedium.

I looked at the chart, its layout, the scene owned by the layout, and the camera owned by the scene, to see if there was some way of pulling out the values for the rotation, zoom, etc, but did not find anything that could be used.

If it's something that isn't currently possible, but could reasonably be implemented, let me know and I can look into creating a pull request.

Add a function to get the selected points in Blazor

With jQuery, we can get the selected points by a click on the line charts . Then we can generate another charts with the data point the user clicks on.
Could you add this feature in Blazor?
I googled the whole internet , found one website of ECharts has one feature . http://blazor-echarts.5izhy.cn/line/index .
I checked #147 and also demo https://plotly-blazor.azurewebsites.net/ , I did not find the function of getting the selected points . Could you make a demo ?

Stacked Bar Chart - chart.React() - Cannot access a disposed object.\r\nObject name: 'DotNetObjectReference

I am trying to update a stacked bar chart that is being used in a dashboard every 5 minutes or so and also has the capability of being able to be manually refreshed whenever the user wants to. When calling chart.React() this is the error I am getting.
Cannot access a disposed object.
Object name: 'DotNetObjectReference`1'.

With a stack trace of:
at Microsoft.JSInterop.DotNetObjectReference1.ThrowIfDisposed()
at Microsoft.JSInterop.DotNetObjectReference1.get_Value()
at Plotly.Blazor.PlotlyJsInterop.d__3.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Plotly.Blazor.PlotlyChart.d__49.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

Code being used to update the chart:

if (_chart != null) { await InvokeAsync(async () => { await _chart.React(); }); }

This same code works fine for the Line (Scatter) charts for updating values in realtime/manual refresh.

Example of 3D Charts

Hi

This is a really cool wrapper - however I am struggling to implement a 3D surface map. This there a plan to include one in the examples?

Many thanks
Jannes

Error in Plotly.Blazor.PlotlyChart.OnAfterRenderAsync(Boolean firstRender) when trying to display plot

I am trying to use Plotly to plot a graph in time domain (DateTime as X axis data elements). I get an error:

Error: System.AggregateException: One or more errors occurred. (One of the identified items was in an invalid format.)

---> System.FormatException: One of the identified items was in an invalid format.

at System.Text.Json.JsonElement.GetDecimal()

at Plotly.Blazor.Extensions.PrepareJsonElement(JsonElement obj)

at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()

at System.Text.Json.Serialization.Converters.IEnumerableDefaultConverter`2.OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonCollectionConverter`2.OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.Converters.DictionaryDefaultConverter`3.OnWriteResume(Utf8JsonWriter writer, TDictionary value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonDictionaryConverter`3.OnTryWrite(Utf8JsonWriter writer, TDictionary dictionary, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.Converters.IEnumerableDefaultConverter`2.OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonCollectionConverter`2.OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWriteAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.Converters.ArrayConverter`2.OnWriteResume(Utf8JsonWriter writer, TElement[] array, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonCollectionConverter`2.OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)

at System.Text.Json.JsonSerializer.WriteUsingSerializer[TValue](Utf8JsonWriter writer, TValue& value, JsonTypeInfo jsonTypeInfo)

at System.Text.Json.JsonSerializer.WriteStringUsingSerializer[TValue](TValue& value, JsonTypeInfo jsonTypeInfo)

at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, CancellationToken cancellationToken, Object[] args)

at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)

at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args)

at Plotly.Blazor.PlotlyJsInterop.NewPlot(IJSRuntime jsRuntime, DotNetObjectReference`1 objectReference)

at Plotly.Blazor.PlotlyChart.NewPlot()

at Plotly.Blazor.PlotlyChart.OnAfterRenderAsync(Boolean firstRender)

--- End of inner exception stack trace --

Any suggestions why this might be occuring are appriciated,

ExtendTraces should truncates the head of the data, couting backward max points from the tail.

According to plotly.js, ExtendTraces truncates the head of the data array, counting backward maxPoints from the tail.

/**
 * extend && prepend traces at indices with update arrays, window trace lengths to maxPoints
 *
 * Extend and Prepend have identical APIs. Prepend inserts an array at the head while Extend
 * inserts an array off the tail. Prepend truncates the tail of the array - counting maxPoints
 * from the head, whereas Extend truncates the head of the array, counting backward maxPoints
 * from the tail.
 *
 * If maxPoints is undefined, nonNumeric, negative or greater than extended trace length no
 * truncation / windowing will be performed. If its zero, well the whole trace is truncated.

but in Plotly.Blazor, ExtendTraces is using Take(max.Value) (see below), which truncates the tail of the data - counting maxPoints from the head.

if (max != null)
{
    traceType.GetProperty("X")?.SetValue(currentTrace, list?.Take(max.Value).ToList());
}

Example of CandleStick chart?

Is there an example of how to create a candlestick chart?

Specifically, this kind of chart.
https://plotly.com/javascript/candlestick-charts/

This is default example with Scatter type.

PlotlyChart chart;
Plotly.Blazor.Config config = new Plotly.Blazor.Config();
Plotly.Blazor.Layout layout = new Plotly.Blazor.Layout();
List<Scatter> data = new List<Scatter>
{
  new Scatter
  {
    Name = "Trace1",
    Mode = ScatterMode.Lines
  }
};

If I try to use CandleStick or Box as a type, VS complains that CandleStick is a static class and cannot be used as a type.

PlotlyChart chart;
Plotly.Blazor.Config config = new Plotly.Blazor.Config();
Plotly.Blazor.Layout layout = new Plotly.Blazor.Layout();
List<Plotly.Candlestick> data = new List<Plotly.Candlestick>
{
  new Plotly.Candlestick
  {
    Name = "Trace1",
    Mode = ScatterMode.Lines
  }
};

Example for aggregations

Hi,

I'd like to add a sum for the traces in my scatter plot, and I'm having trouble understanding the aggregation.target and aggregate.groups settings and how they work in Plotly.Blazor.

An example would be great if you can =) thanks.

Changing the min-height on the outer div

After setting the height and width in the layout I notice that when a bar chart renders that a min-height of 350px is set.

The element looks like the following upon inspecting HTML

The chart itself seems to render the correct height but then there is a ton of white space even after shrinking the margins. Is there a way to override that setting ?

Generated Equals-Method is incorrect

The property comparison is wrong.

Wrong:

Type == other.Type &&
Type != null && other.Type != null &&
Type.Equals(other.Type)

Correct:

Type == other.Type ||
Type != null &&
Type.Equals(other.Type)

Note: we only use properties, where null is allowed.

`NullReferenceException` in `PlotlyJsInterop` `React` call when calling `Chart.Update`

Code belows throws NullReferenceException on call to Update.

<PlotlyChart @bind-Config="config" @bind-Layout="layout" @bind-Data="data" @ref="chart"/>

@code {
  [Parameter] public IReadOnlyCollection<Bar<T>> Bars { get; set; } = null!;

  public PlotlyChart chart = new();

  public Config config = new()
  {
      Responsive = true,
  };

  public Plotly.Blazor.Layout layout = new()
  {
      DragMode = DragModeEnum.Zoom,
      Margin = new Margin
      {
          R = 10,
          T = 25,
          B = 40,
          L = 60,
      },
      XAxis = new List<XAxis>
      {
          new()
          {
              AutoRange = AutoRangeEnum.True,
              Type = typeof(T) == typeof(double) ? TypeEnum.Linear : TypeEnum.Date,
          },
      },
      YAxis = new List<YAxis>
      {
          new()
          {
              AutoRange = Plotly.Blazor.LayoutLib.YAxisLib.AutoRangeEnum.True,
              Type = Plotly.Blazor.LayoutLib.YAxisLib.TypeEnum.Linear,
          },
      },
      Height = 800,
      Title = new Title(),
  };

  private List<ITrace> GetData()
  {
    // Omitted...
  }

  protected override async Task OnParametersSetAsync()
  {
      this.data = this.GetData();
      try
      {
          await this.chart.Update();
      }
      catch
      {
      }
      await this.InvokeAsync(this.StateHasChanged);
  }
}

Somehow if I catch the exception, I still get the chart displayed.

Scatter trace line shape changes

After adding an annotation and then extending a trace, the line shape (initially set to Spline) reverts to a straight line, as per the attached image. Any pointers appreciated (am using chart,React() within a Razor component).
SplineLostWhenRefreshingAnnotations

In case of having two points on same x and y axis, I am unable to see both the points.

Hi, I am using Plotly blazor. The problem I am facing is that, when there are two points with same x and y axis then how to show count on that point.

Right now it shows one point on that x and y and I am unable to figure out how many points are there on same x and y.

image

In the above image there are two points on x-5000 and y-5000 but we are able to see only one. I wanted a way to show that there is two-points with the same values. I wanted something like when I hover on that point it shows me count (num of points with same x and y) as well.

CS1503: Argument 2: cannot convert from 'Microsoft.AspNetCore.Components.EventCallback<System.Collections.Generic.List<Plotly.Blazor.ITrace>>' to 'Microsoft.AspNetCore.Components.EventCallback'

I got the examples compiled and running. Works like a charm. However, when I tried to add a scatter plot to a page in a new project following instructions in the readme file, I got the following:

CS1503: Argument 2: cannot convert from 'Microsoft.AspNetCore.Components.EventCallback<System.Collections.Generic.List<Plotly.Blazor.ITrace>>' to 'Microsoft.AspNetCore.Components.EventCallback'

I am using .NET Core 3.1 with Blazor Server and the default project template.

Cannot hide axis ticks

I'm setting the XAxis.Ticks = TicksEnum.Empty but the ticks remain visible.

I suspect that because this is internally an empty string, something somewhere is treating this as equivalent to null and ignoring it, but I haven't traced it down specifically.

Slow rendering of Line Graph with 100000 data points

Hello

I am using Plotly.Blazor for plotting graphs. For a small data set, it is working really good but if the data set becomes large e.g 100000 data points. The plotted graph is very very slow. I cannot pan it neither I can use the rest of the controls.

image

The application which we are using is deployed upon the P1V2 Azure App Service instance. If I try to pan it the graph is unresponsive and I see the following message

image

One more thing I that I am using ScatterGl for traces. If I use simple scatter, it becomes unresponsive even on my machine. Kindly help me with this issue

Best Wishes
Saad

How to add GeoJSON data to a map?

I have a GeoJSON file with feature data as polygons. How do I add this to a map?

Setting the GeoJson property of a ScatterGeo with either the path to the json file or the file contents as a string does nothing.

Logarithmic axis

I would love the possibility for using logarithmic axis like matplotlib/matlab's semilogx / semilogy / loglog functionality described here for plotly.
I have searched for it but it does not yet seem be there...
Anyway, thanks for the excellent package.

Unable to make heatmap work

Hi,

I'm trying to implement heatmap using this library but due to lacking in examples of heatmap I'm struggling to make it to work.
Data for heatmap is from an internal API. The requirement are user select production types (Oil, Gas, BOE) and data levels (7 days, 30 days, etc.) from 2 dropdown lists. When I run, all the values for X, Y and Z were populated but the heatmap doesn't show up, only the axises (they are even wrong, not the ones I assigned, just generic 1, 2, 3, 4). All of the controls and CSS work fine. There's no error. Please help.

Note: I'm using MudBlazor for CSS

Front end:

@using Plotly.Blazor.LayoutLib

<div class="mt-5">
    <MudText Typo="Typo.h3" Color="Color.Primary" Align="Align.Center">GOM Production Heatmap</MudText>
</div>
<div class="mt-5">
    <MudGrid>
        <MudItem lg="12">
            <MudGrid Spacing="4" Justify="Justify.Center">
                <MudItem>
                    <MudSelect T="string" Variant="Variant.Outlined" Label="Select production type" @bind-Value="selectedProductionType" Style="width:250px;">
                        @foreach(var type in ProductionTypes)
                        {
                        <MudSelectItem Value="@type">@type</MudSelectItem>
                        }
                    </MudSelect>
                </MudItem>
                <MudItem>
                    <MudSelect T="string" Variant="Variant.Outlined" Label="Select level" @bind-Value="selectedLevel" Style="width:250px;">
                        @foreach(var level in DisplayLevels)
                        {
                        <MudSelectItem Value="@level">@level</MudSelectItem>
                        }
                    </MudSelect>
                </MudItem>
            </MudGrid>
        </MudItem>
    </MudGrid>
</div>
<div class="mt-5">
    <PlotlyChart Id="TestId" Config="config" Layout="layout" Data="data" @ref="chart" />
</div>

Code behind:

using Kosgo.Apps.Services;
using Kosgo.Models;
using Microsoft.AspNetCore.Components;
using Plotly.Blazor;
using Plotly.Blazor.LayoutLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Plotly.Blazor.Traces;

namespace Kosgo.Components
{
    public partial class GOMProdHeatmap : ComponentBase
    {
        [Inject]
        public IGOMHeatmapDataService GOMHeatmapDataService { get; set; }
        public IEnumerable<GOMProdHeatmapData> jsData { get; set; }
        private List<object> YValues { get; set; }
        private List<object> XValues { get; set; }
        private List<object> ZValues { get; set; } = new List<object>();
        private List<object> Levels { get; set; }
        private List<string> DisplayLevels { get; set; } = new List<string>
            {
                "7 days",
                "30 days",
                "90 days",
                "365 days"
            };
        private List<int> Periods { get; set; }
        private List<string> ProductionTypes { get; set; } = new List<string>
            {
                "Gross Oil",
                "Gross Gas",
                "Gross BOE",
                "Net BOE"
            };
        
        private string selectedProductionType { get; set; } = "Gross Oil";
        private string selectedLevel { get; set; } = "7 days";


        PlotlyChart chart { get; set; }
        Config config { get; set; }
        Layout layout { get; set; }
        IList<ITrace> data { get; set; }

        public override async Task SetParametersAsync(ParameterView parameters)
        {
            await base.SetParametersAsync(parameters);

            config = new Config 
            { 
                Responsive = true 
            };

            jsData = (await GOMHeatmapDataService.GetData()).ToList();

            ProcessData();

            data = new List<ITrace>
            {
                new HeatMap
                {
                    X = XValues,
                    Y = YValues,
                    Z = ZValues,
                    //ShowScale = true,
                    HoverOnGaps = false
                }
            };
        }

        private void ProcessData()
        {
            YValues = jsData.Select(d => Convert.ChangeType(d.WellName, typeof(object))).Distinct().OrderBy(y => y).ToList();

            Levels = jsData.Select(d => Convert.ChangeType(d.Level, typeof(object))).Distinct().OrderBy(x => x).ToList();
            
            if (!Levels.Any(l => l.ToString().Length < 4))
            {
                DisplayLevels = Levels.Select(l => l.ToString().Insert(l.ToString().Length - 4, " ")).ToList();
            }

            XValues = jsData.Where(d => d.Level == selectedLevel.Replace(" ", ""))
                .Select(d => Convert.ChangeType(d.MaxDate, typeof(object)))
                .OrderBy(d => d).Distinct().ToList();

            var z = new List<decimal?[]>();

            foreach (var well in YValues)
            {
                if (selectedProductionType == "Gross Oil")
                {
                    z.Add(jsData.Where(d => d.WellName == well.ToString() && d.Level == selectedLevel.Replace(" ", ""))
                        .Select(d => d.DeltaOil).ToArray());
                }
                else if (selectedProductionType == "Gross Gas")
                {
                    z.Add(jsData.Where(d => d.WellName == well.ToString() && d.Level == selectedLevel.Replace(" ", ""))
                        .Select(d => d.DeltaGas).ToArray());
                }
                else if (selectedProductionType == "Gross BOE")
                {
                    z.Add(jsData.Where(d => d.WellName == well.ToString() && d.Level == selectedLevel.Replace(" ", ""))
                        .Select(d => d.DeltaBoe).ToArray());
                }
                else
                {
                    z.Add(jsData.Where(d => d.WellName == well.ToString() && d.Level == selectedLevel.Replace(" ", ""))
                        .Select(d => d.DeltaNetBoe).ToArray());
                }
            }

            ZValues = z.Cast<object>().ToList();
        }
    }
}

Implement Sankey charts

Are there any plans to implement sankey charts ? I can't figure out how to display one from the given examples

Cannot successfully install version 2.0.0

When I install the 2.0.0 version of the package, there is no Plotly namespace that can be imported.

Steps to recreate:

  1. Install Plotly.Blazor: dotnet add package Plotly.Blazor --version 2.0.0
  2. Add imports in _Imports: @using Plotly.Blazor

Attempting to compile will say The type or namespace name Plotly could not be found

Instead installing version 1.5.0 will fix this issue.

  1. Install Plotly.Blazor: dotnet add package Plotly.Blazor --version 1.5.0
  2. Add imports: @using Plotly.Blazor

Import will work successfully

Async Function chart.React() is awaitable but blocks UI

Hi,

Im using Blazor with Telerik, but i wasn't a fan of their charts, so I decided to try these out. after asynchronysly loading the data i call "await chart.React()" so the Data in the chart is updated, Consequently my LoadingIcon is blocked and stops spinning for a couple of seconds until "chart.React" is finished.

Am I doing something wrong. Why is the chart not updates asynchronously, even if the function is awaitable.

Kind Regards,
Vlad

Cannot read properties of undefined (reading 'newPlot')

Getting the following error when trying to implement an example from the examples section of the project.
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Cannot read properties of undefined (reading 'newPlot')
TypeError: Cannot read properties of undefined (reading 'newPlot')
at Object.newPlot (http://localhost:5054/_content/Plotly.Blazor/plotly-interop.js:3:23)
at http://localhost:5054/_framework/blazor.webassembly.js:1:3332
at new Promise ()
at Object.beginInvokeJSFromDotNet (http://localhost:5054/_framework/blazor.webassembly.js:1:3306)
at Object.St [as invokeJSFromDotNet] (http://localhost:5054/_framework/blazor.webassembly.js:1:59849)
at _mono_wasm_invoke_js_blazor (http://localhost:5054/_framework/dotnet.6.0.4.dckq00jdfr.js:1:195300)
at http://localhost:5054/_framework/dotnet.wasm:wasm-function[219]:0x1a0fb
at http://localhost:5054/_framework/dotnet.wasm:wasm-function[167]:0xcac9
at http://localhost:5054/_framework/dotnet.wasm:wasm-function[166]:0xb9dc
at http://localhost:5054/_framework/dotnet.wasm:wasm-function[2810]:0xabb22
Microsoft.JSInterop.JSException: Cannot read properties of undefined (reading 'newPlot')
TypeError: Cannot read properties of undefined (reading 'newPlot')
at Object.newPlot (http://localhost:5054/_content/Plotly.Blazor/plotly-interop.js:3:23)
at http://localhost:5054/_framework/blazor.webassembly.js:1:3332
at new Promise ()
at Object.beginInvokeJSFromDotNet (http://localhost:5054/_framework/blazor.webassembly.js:1:3306)
at Object.St [as invokeJSFromDotNet] (http://localhost:5054/_framework/blazor.webassembly.js:1:59849)
at _mono_wasm_invoke_js_blazor (http://localhost:5054/_framework/dotnet.6.0.4.dckq00jdfr.js:1:195300)
at http://localhost:5054/_framework/dotnet.wasm:wasm-function[219]:0x1a0fb
at http://localhost:5054/_framework/dotnet.wasm:wasm-function[167]:0xcac9
at http://localhost:5054/_framework/dotnet.wasm:wasm-function[166]:0xb9dc
at http://localhost:5054/_framework/dotnet.wasm:wasm-function[2810]:0xabb22
at Microsoft.JSInterop.JSRuntime.d__161[[Microsoft.JSInterop.Infrastructure.IJSVoidResult, Microsoft.JSInterop, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].MoveNext() at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args) at Plotly.Blazor.PlotlyJsInterop.NewPlot(IJSRuntime jsRuntime, DotNetObjectReference1 objectReference)
at Plotly.Blazor.PlotlyChart.NewPlot()
at Plotly.Blazor.PlotlyChart.OnAfterRenderAsync(Boolean firstRender)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

My razor component:
`@using Plotly.Blazor.LayoutLib

PlotlyTestComponent

<PlotlyChart Id="TestId" Config="config" Layout="layout" Data="data" @ref="chart"/>

@code {
PlotlyChart chart;

Config config = new Config
{
    Responsive = true
};

Layout layout = new Layout
{
    Title = new Title
    {
        Text = "Bar"
    },
    BarMode = BarModeEnum.Stack,
    Height = 500
};

List<ITrace> data = new List<ITrace>
{
    new Bar
    {
        X = new List<object> {"giraffes", "orangutans", "monkeys"},
        Y = new List<object> {20, 14, 23},
        Name = "SF Zoo"
    },
    new Bar
    {
        X = new List<object> {"giraffes", "orangutans", "monkeys"},
        Y = new List<object> {12, 18, 29},
        Name = "LA Zoo"
    }
};

}`

_Imports.razor:
... @using Plotly.Blazor; @using Plotly.Blazor.Traces;

index.html:
<!-- Import the plotly.js library --> <script src="_content/Plotly.Blazor/plotly-latest.min.js" type="text/javascript"></script> <!-- Import the plotly.js interop functions --> <script src="_content/Plotly.Blazor/plotly-interop.js" type="text/javascript"></script>

Examples outdated

Hello there. I wanted to try to use Blazor Serverside and Plotly Blazor, but all Examples seem to be outdated.

For example, using the following is impossible with a current Installation of VS2019 Preview, .Net 6 Preview and Blazor Serverside

<PlotlyChart style="height: 60vh; min-height: 350px" @bind-Config="config" @bind-Layout="layout" @bind-Data="data" @ref="chart" />
@code {

    PlotlyChart chart;

    Config config = new Config
    {
        Responsive = true
    };

    Layout layout = new Layout
    {
        Title = new Title
        {
            Text = "Scatter"
        },
        YAxis = new List<YAxis>
{
            new YAxis
            {
                Title = new LayoutLib.YAxisLib.Title
                {
                    Text = "Scatter Unit"
                }
            }
        }
    };

    IList<ITrace> data = new List<ITrace>{
        new Scatter
        {
            Name = "ScatterTrace",
            Mode = ModeFlag.Lines | ModeFlag.Markers,
            X = new List<object>(),
            Y = new List<object>()
        }
    };
}

For reference, a List of the errors I am getting are:

  • Config is not a Type that can be resolved
  • "Title" is not of Type Title but instead just a string - Title appears to also have been renamed to title with lowercase letters
  • YAxis has been renamed to Yaxis
  • ITrace is not a Type that can be resolved
  • the @bind-Data Binding is also not accepted in Blazor. Error Message: "The attribute names could not be inferred from bind attribute data-Bind..."

Am I doing something wrong here?

Setting Heatmap Colorscale

I'm trying to set a custom color scale in a heatmap, but can't work out the C# syntax. I've various instances of the following but none work:

ColorScale = new List<object>
            {
                (0.0, "#f33"),
                (0.5, "#3f3"),
                (1.0, "#33f")
            },

ColorScale = new Dictionary<double, string>
            {
                {0.0, "#f33" },
                {0.5, "#3f3" },
                {1.0, "#33f" }
            },

The JS reference is:

    colorscale: [
        ['0.0', 'rgb(165,0,38)'],
        ['0.1', 'rgb(215,48,39)'],
        ['0.2', 'rgb(244,109,67)'],
        ['0.3', 'rgb(253,174,97)'],
        ['0.4', 'rgb(254,224,144)'],
        ['0.5', 'rgb(224,243,248)'],
        ['0.6', 'rgb(171,217,233)'],
        ['0.7', 'rgb(116,173,209)'],
        ['0.8', 'rgb(69,117,180)'],
        ['1.0', 'rgb(49,54,149)']
  ]

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.