Unable to display surface chart using Plotly in Angular 12

I've been attempting to display a 3D model using Plotly (https://github.com/plotly/angular-plotly.js/blob/master/README.md), but unfortunately, the chart is not appearing.

component.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-componente',
  templateUrl: './componente.component.html',
  styleUrls: ['./componente.component.css']
})
export class ComponenteComponent{
  
  getData() {
    var arr = [];
    for(let i=0;i<25;i++)
        arr.push(Array(25).fill(undefined).map(() => Math.random()))
    console.log(arr);
    return arr;
  } 
  data: any[] = this.getData();

  public graph = {
    z: this.data,
    type: 'surface',
    layout: {autosize: true, title: 'Modelo 3d'}
  };

}

componente.component.html

<plotly-plot [data]="graph.z" [layout]="graph.layout"></plotly-plot>

https://i.sstatic.net/gLhQe.png This is the current display.

It should look more like this: https://i.sstatic.net/4RB7g.png

I've been working on getting this to function with Angular all day, but I'm struggling a bit. Any assistance would be greatly appreciated. 😊

Answer â„–1

Here is my approach to solving the problem:

import * as PlotlyJS from 'plotly.js-dist-min';

getData() {
    var arr = [];
    for(let i=0;i<40;i++)
        arr.push(Array(40).fill(undefined).map(() => Math.random() * 256))
    //console.log(arr);
    arr.push({type: 'scatter3d'});
    return arr;
  }

testButton () {
    this.getModelo3d();
    PlotlyJS.newPlot('chart', [{
      z: this.getData(),
      type: 'surface'
    }]);
  }

within the context of HTML

<div id="chart"></div>

Answer â„–2

I encountered a similar issue to the one you described.

In my situation, the problem stemmed from importing the wrong module.

While using Vue and installing it through Vue-CLI, I mistakenly installed a module with a similar but different name.

As a result, although I tried to set up surface and heatmap visuals, it defaulted to displaying a line graph instead.

The import statement I used was: import * as Plotly from 'plotly.js-basic-dist';

However, based on the Github Readme, it should have been 'plotly.js-dist-min'.

https://github.com/plotly/plotly.js#load-as-a-node-module

Answer â„–3

Your post was a helpful guide for me as I aimed to create a 3d surface plot in Angular using Plotly. I appreciate the nudge in the right direction.

After encountering issues with rendering using your original code, I found an alternative solution which I wanted to share here for the benefit of others.

It seems that Plotly requires an object with both the data and the chart type within the same object. The binding from the plotly-plot UI element to the data was too deep and was missing the type property with the value "surface."

After making these adjustments, the rendering works perfectly for me:

getData() {
    var arr = [];
    for(let i=0;i<25;i++)
        arr.push(Array(25).fill(undefined).map(() => Math.random()))
    console.log(arr);
    return arr;
  } 
  data: any[] = this.getData();

  public graph = {
    data: [
      {
        z: this.getData(),
        type: 'surface'
      }
    ],
    layout: {autosize: true, title: 'Modelo 3d'}
  };

and the view...

<plotly-plot [data]="graph.data" [layout]="graph.layout"></plotly-plot>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When an event occurs, have Express make an HTTP call to Angular

In the process of developing an Angular application, I am working on a feature that will enable around a thousand users to connect simultaneously in order to book tickets. However, I only want a specific number of them, let's call it "XYZ", to access ...

The CORS policy is causing a blockage for the front-end application due to the Spring Boot backend

Currently working with Spring Boot and Angular. I have included the cross-origin annotation in my code to allow access from my Angular localhost port, but unfortunately, I am still encountering the following error: https://i.sstatic.net/4uDuv.png Here is ...

Encountering an Error: Unforeseen Token < Causing Webpack Configuration Problem in Typescript

Seeking assistance to resolve an issue that has arisen while working on a project with Typescript, React, and Webpack. I referred to the guide available at https://www.typescriptlang.org/docs/handbook/react-&-webpack.html After configuring everything, ...

Executing Angular CLI tasks using a script file rather than directly from the CLI? Embracing the power of Localization and Internationalization

Our Angular 2 app is gearing up for internationalization/localization, and I am looking to create scripts that can handle tasks such as generating translation source files or building/serving the application with translations in a specific language. Inste ...

Activation of Angular SwUpdate deprecation

Within my Angular project, I am currently utilizing the following code snippet: this.swUpdate.available.subscribe(() => { ... }); While this code functions correctly, it does generate a warning regarding the deprecation of activated. How can I addre ...

What method can be used to verify if a username exists within Angular data?

We want to display online users on a webpage by checking if they are currently active. The current code logs all online users in the console, but we need to show this visually on the page. public isOnline: boolean = false; ... ... ngOnInit() { ...

How to Pass Data as an Empty Array in Angular 6

After successfully implementing a search function that filters names from an array based on user input, I encountered an issue when trying to make the searchData dynamic by fetching it from a Firebase database: getArray(): void { this.afDatabase.list( ...

Tips for preventing duplicate entries in an AG Grid component within an Angular application

In an attempt to showcase the child as only 3 columns based on assetCode, I want to display PRN, PRN1, and PRN2. Below is the code for the list component: list.component.ts this.rowData.push( { 'code': 'Machine 1', &apo ...

Error class not being applied by Knockout validation

I've implemented knockout validation on a text input and the validation is working correctly. However, the errorMessageClass is not being applied to the error message. I must have made a mistake in my setup, but I can't seem to identify it. My H ...

Storing Angular header values in local storage

saveStudentDetails(values) { const studentData = {}; studentData['id'] = values.id; studentData['password'] = values.password; this.crudService.loginstudent(studentData).subscribe(result => { // Here should be the val ...

typescript add an html element to an existing html document

I'm experimenting with creating a dynamic HTML element using TypeScript to display on a webpage. In my .ts file, my code looks like this: const displayContent = document.getElementById("display-content") as HTMLOutputElement; var displayVariable = " ...

Error message in Typescript with React: "The type 'ComponentClass<StyledComponentProps<{}>>' cannot be assigned to type 'typeof MyComponent'"

Currently experimenting with integrating the Material UI 1.0 (beta) @withStyles annotation into a React component. The documentation provides a JavaScript example (), however, it results in a compilation error when using Typescript. Despite the error, the ...

Images with spaces in their names are failing to load in React Native

I am currently trying to utilize an image within my react native application. At this point, my code is very minimal. The following code snippet is all I have for now: import React from 'react'; import { ScrollView, View, Text } from 'reac ...

The ultimate guide to successfully implementing Angular Service Workers on IE11

Can the Angular Service Worker be utilized in IE11? Although CanIuse indicates that IE11 is not supported, there is a Polyfill available for older browsers that offers Promises support - the foundation on which the Service Worker operates. Has anyone succ ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

What is the best way to create a general getter function in Typescript that supports multiple variations?

My goal is to create a method that acts as a getter, with the option of taking a parameter. This getter should allow access to an object of type T, and return either the entire object or a specific property of that object. The issue I am facing is definin ...

Is the parent component not triggering the function properly?

Hey there, I'm working with the code snippet below in this component: <app-steps #appSteps [menuSteps]="steps" [currentComponent]="outlet?.component" (currentStepChange)="currentStep = $event"> <div appStep ...

Tips for creating a custom script in my React Native application

My React Native app requires a script to generate static files during the release process. The app is a game that utilizes pre-computed boards, which are resource-intensive to compute. Therefore, I am developing a script that will create these boards and s ...

Contrast: Colon vs. Not Equal Sign (Typescript)

Introduction Hello everyone, I am new to Typescript and currently grappling with some fundamental concepts. When defining a parameter for a function, I typically specify the type like this: function example(test: string){...} However, as I delve deeper ...

Troubleshooting Node.js and Angular: Resolving the "Cannot Get"

I've successfully retrieved data from Angular and can store it in my local database without any issues. However, when I check the backend server in the web browser, I'm seeing the error message below: Cannot GET Even though the server is rece ...