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

Learn how to iterate over an array and display items with a specific class when clicked using jQuery

I have an array with values that I want to display one by one on the screen when the background div is clicked. However, I also want each element to fade out when clicked and then a new element to appear. Currently, the elements are being produced but th ...

Error: Undefined variable in JavaScript obfuscation

My website has several small JavaScript files that I currently merge into one file and then minimize using terser. The website functions perfectly with the minimized version. Now, I want to take it a step further and obfuscate the code using JavaScript-Ob ...

The Vue.js error message "Unable to access property 'array_name' as it is undefined" indicates an issue with

I'm currently working on fetching data using Axios requests and storing it in an array. Below is the code I have been using: props: [ 'products', ], data: function () { return { algolia: '', pro ...

Online Adventure - Saving Conversations

I am interested in developing an RPG using JavaScript. The game will involve a significant amount of dialog. While I have knowledge of PHP and MySQL, I am new to XML. My queries are: Would it be more efficient to store the dialog in a MySQL database and ...

Wordpress functionality for filtering Ajax posts using radio buttons

I am in the process of creating an Ajax post filter system using radio buttons to allow users to filter through multiple categories. Below is the code I have implemented: Front-end form: <form id="filter"> <?php if( ...

Error: Attempting to assign a value to property 'x' of an undefined object has resulted in a TypeError

When I tried to create an array of randomly generated circles (stars) in my first code, I encountered a TypeError on this line: stars[i].x = Math.floor(Math.random() * w) Even though stars is defined in the code, the issue persisted. $(document).ready(f ...

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

How do I make the message "document.getElementById(...) is null" become true?

When running my code, only two of the document.getElementById calls (ctx1 and ctx2) successfully get values while the others (such as ctx3) do not. How can I ensure that all elements retrieve their values without receiving an error message? Below is a snip ...

Using a React component to import a module for publishing on NPM

Creating my first React component for NPM publication has been quite the learning experience. I decided to use the react-webpack-component package from Yeoman to kickstart my project. However, upon installing and importing my component into a React app, I ...

Switch up the like button for users who have previously liked a post

Greetings, I trust everything is going well. I am attempting to implement a feature where users can like a post or article created by others using a button. I have established a const function named "getAPostLikeRecord()," which retrieves a list of users w ...

"Firebase offers the flexibility to have several 'apps' configured, both on the client side and the server

Currently, I have a firebase app set up in my project for SSR using firebase-admin. However, I now want to add firebase@8 to be able to utilize it on the client-side and eventually apply firestore rules. The issue arises when I try to use firebase@8, I enc ...

Improving Performance of a Large Unordered List using JavaScript

My website currently features a search box that retrieves images and displays them in a list format. Each image has an associated click event that triggers an overlay on the parent li element when clicked. However, with search results exceeding 300 images ...

What is the reason for the failure of <option selected="selected">?

Even though my ng-selected expression is supposed to set the selected="selected" attribute in the <option> tag (as shown in the screenshot http://prntscr.com/bmgozg), for some mysterious reason, this particular <option> element still remains un ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

Ways to extract dropdown selection into a .php script

I am trying to capture the selected dropdown value in my .php file, which is used for sending emails. When a user selects one of the 6 options from the dropdown menu, I want that selected option to be included as the email subject. Below is the HTML code ...

Enhancing the functionality of the onclick function within the ng-repeat by incorporating a scope

I am looking to pass a parameter to a function that is called via onclick within an ng-repeat: <!-- Sliding bar (bottom) --> <div ng-show="currentSVG && currentLanguage && currentWidth && bannerHeight" pageslide ps-open=" ...

What is causing the PUT request to not go through when using POSTMAN?

As I navigate through the paths of my application, I encountered an issue with PUT requests that were not being fully processed by POSTMAN. Below is the configuration of my ExpressJS server: const express = require('express'); const morgan = re ...

VueJS / v-html is displaying a blank page (Bokeh-html)

Especially as a newcomer to VueJS, I am currently in the process of trying to showcase a local HTML file within the Vue Application. The method I'm using to fetch the HTML file involves Axios, here's how it goes: <template> <div> ...

Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form. I have attempted this ...

Matching a regular expression pattern at the beginning of a line for grouping strings

One of my tasks involves working with a markdown string that looks like this: var str = " # Title here Some body of text ## A subtitle ##There may be no space after the title hashtags Another body of text with a Twitter #hashtag in it"; My goal ...