Error in D3: stream_layers function is not defined

Utilizing nvd3.js to construct a basic stacked bar chart as detailed here

I inserted the code provided in the link into an Angular directive like this:

app.directive('stackBar', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            nv.addGraph(function() {
                var chart = nv.models.multiBarChart()
                            /*.transitionDuration(350)*/
                            .reduceXTicks(true)   //If 'false', every single x-axis tick label will be rendered.
                            /*.rotateLabels(0)    */  //Angle to rotate x-axis labels.
                            .showControls(true)   //Allow user to switch between 'Grouped' and 'Stacked' mode.
                            .groupSpacing(0.1);    //Distance between each group of bars.

                chart.xAxis
                            .tickFormat(d3.format(',f'));

                chart.yAxis
                            .tickFormat(d3.format(',.1f'));

                d3.select(element[0])
                            .datum(exampleData())
                            .call(chart);

                nv.utils.windowResize(chart.update);
                return chart;
            });

            //Generate some nice data.
            function exampleData() {
                return stream_layers(3,10+Math.random()*100,.1).map(function(data, i) {
                        return {
                            key: 'Stream #' + i,
                            values: data
                        };
                });
            }
        }
    }   
});

Below is my HTML:

<td class="centered" colspan="5">
      <div stack-bar>

      </div>
</td>

However, I am encountering the following error:

Uncaught ReferenceError: stream_layers is not defined

Any suggestions on where I might be mistaken?

In addition, 'transitonDuration' was not functional so I deactivated it. Initially, I presumed this could be due to a d3 version issue, but even with the latest version, the problem persists.

UPDATE:

The answer from Huang Feng assisted me in eliminating the error. Nonetheless, instead of receiving a chart, I'm seeing an abundance of text. Here's a screenshot:

https://i.stack.imgur.com/p6K7c.png

Any thoughts why this is happening?

Also, the directive is within an ng-repeat, which explains the multiple rows shown in the screenshot.

Answer №1

The reason why the code isn't working is because the stream_layers function is not defined in the nvd3 library.

You can find the function definition here:

To use this function, make sure to include the library in your HTML like this:

<script src="../stream_layers.js"></script>

For a more detailed example, you can refer to this link:

http://bl.ocks.org/mbostock/3943967

Answer №2

I faced a similar issue with the output and errors, but I found 3 solutions to resolve it:

1. Including stream_layers.js in the Path

Following advice from huan feng, it is necessary to add the stream_layers.js function to generate sample data for the example. You can download the source code from nvd3.org, where you will find the stream_layers.js file located at

novus-nvd3-8ceb270/test/stream_layers.js
(ensure to update the first part of your path based on the latest git hash).

2. Substituting transitionDuration with duration

An additional issue was identified with NVD3 API changes. Upon examining the source code (line 456 in

novus-nvd3-8ceb270/src/models/multiBarChart.js
), it was discovered that the method transitionDuration has been replaced by simply using duration. Below is an updated snippet incorporating the corrected duration option:

var chart = nv.models.multiBarChart()
  .duration(350)
  .reduceXTicks(true)
  .showControls(true)
  .groupSpacing(0.1)

3. Generating an SVG Element

The screenshot displayed only text which could be due to attempting to append the chart to a div instead of an SVG element. One way to address this issue is by appending an svg to element[0] and then utilizing that svg for visualization:

var svg = d3.select(element[0])
  .append('svg')
  .attr('id', 'my-bar-chart-svg')

d3.select('#my-bar-chart-svg')
   .datum(exampleData())
   .call(chart);

If no visualization appears, adjusting the width and height of the SVG element created might help. Here's a quick test hack:

var svg = d3.select(element[0])
  .append('svg')
  .attr('id', 'my-bar-chart-svg')
  .attr('width', 800)
  .attr('height', 400)

d3.select('#my-bar-chart-svg')
   .datum(exampleData())
   .call(chart);

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

Bootstrap-tour is incompatible with a row within a table structure

Is there a way to highlight a table row effectively? I've been struggling with it and tried using the fix mentioned in this bootstrap-tour issue here Check out this demonstration on jsFiddle: jsFiddle JAVASCRIPT $("#dialog").dialog(); var t = new ...

Exploring a one-dimensional nested array in order to make updates to the higher level nodes

I have a 1D nested array: nestedArr: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 2, parentId: 1, taskCo ...

React - assigning a value to an input using JavaScript does not fire the 'onChange' event

In my React application with version 15.4.2, I am facing an issue where updating the value of a text input field using JavaScript does not trigger the associated onChange event listener. Despite the content being correctly updated, the handler is not being ...

What is the best way to send information from App.js to components?

In my project, I am working with App.js and a functional component called "uploadlist". The goal is to pass a 'custid' value from App.js to the uploadlist component. Here's what I have attempted: app.js: export default class App extends Com ...

Chatting with a Discord bot

I am currently working on a Discord bot that will execute specific functions based on the questions asked, most of which are yes or no queries. Upon responding with "yes," a particular function should be performed, while answering "no" would terminate t ...

React infinite scroller - component fails to work when initial items are insufficiently loaded

In my Next.js app, I am dealing with a large firestore database containing many book objects. To filter these books based on keywords in their title, category, author, etc., I have implemented a searchbar. Due to the sheer volume of books, I am utilizing l ...

Exploring the Benefits of Combining Vue.js with Laravel

Being a newcomer to Vue, I decided to try it out in a recent project and quickly understood why it's so popular. Everything was running smoothly until I tested it in IE, where nothing seemed to work at all. Encountering errors like Object doesn' ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...

Sketch a straight path starting from the coordinates x,y at a specified angle and length

Is there a way to draw a line in Javascript starting from a specific x/y position with a given length and angle, without having to define two separate points? I have the x/y origin, angle, and length available. The line should be placed on top of a regula ...

Changing the image source when clicking on it and removing it can be done by using JavaScript

How can I add a class 'selected' to ".swiper-slide" when it is clicked? I also want to change the image src when svg-img1, 2, or 3 is clicked. However, I need the image to revert back to its default src when another swiper-slide is clicked. ...

Extracting JSON data within ajax's success callback

I am currently working on parsing and displaying JSON data that is returned from a server. To accomplish this, I have set up an AJAX call that reads user input, sends it to a PHP page via POST method, and the PHP page var_dumps the array containing the JSO ...

Reduce the amount of time it takes for a Google AdWords Script to generate a

According to Google Script best practices, it is recommended to store operations in an array and then call the methods once all the operations have been constructed. This helps minimize response time each time a service is called. For example, let's ...

I'm curious about integrating Font Awesome into my React.js project - any tips on

I'm having trouble getting Font Awesome to display in my React JS project. Here is the code I am using: import React, {Component} from 'react' import './category.css' import axios from 'axios' import Course from './c ...

Is it possible to send requests to multiple APIs using a TypeScript event handler?

I'm facing a challenge in pinging multiple APIs within a single function. It seems like it should be possible, especially since each API shares the same headers and observable. I attempted to write a function for this purpose, but unfortunately, it do ...

Utilizing socket.io to access the session object in an express application

While utilizing socket.io with express and incorporating express session along with express-socket.io-session, I am encountering difficulty in accessing the properties of the express session within the socket.io session object, and vice versa. const serve ...

Retrieve XML node through AJAX request

I am in need of using AJAX to retrieve values from XML nodes and then utilize those values within an existing JavaScript function. Here's a sample of the XML data: <cars> <car mfgdate="1 Jan 15" name="Ford" id="1"> <engine litre ...

Encountering a Next.js Strapi error. TypeError: Fetch request unsuccessful

An error occurred during module build: UnhandledSchemeError: The plugin does not support reading from "node:assert" URIs (Unhandled scheme). Webpack natively supports "data:" and "file:" URIs. You might require an extra plugin to handle "node:" URIs. ...

Navigate the JSON object at predetermined intervals, such as in the case of movie subtitles

Apologies if the title is not specific enough, open to any suggestions for improvement. Here's my issue: I have a JSON file (presented here as a JavaScript object) that contains subtitles for a movie. My goal is to display the text exactly as it appea ...

I encountered an error message saying "TypeError: response.json is not a function" while attempting to make a request using fetch in a project involving ReactJS and Node

Currently, I am in the process of developing a webpage using reactjs and have set up a simple REST api/database with nodejs. My main focus right now is on properly utilizing this API from the front end. The objective was to send a JSON payload containing { ...

The JSON data URLs in the `_next/data` directory of the NextJS app are returning a 404 error, however, when accessed directly in the

I am facing an issue with my Next.js (v13) app hosted on a self-hosted Kubernetes cluster. The AJAX JSON data calls from the _data directory are showing as 404 errors, even though when I directly visit the URLs in my browser, they load fine. I'm perp ...