Creating Interactive Stacked Bar Chart Using D3

I'm currently working on creating a dynamic stacked bar chart using D3.js. The main requirement is that new data points will be received every few seconds, and the stacked chart should be updated smoothly. Below is the code I've written:

<html>
<head>
    <title>Page Title</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="d3/d3.js"></script>
    <script src="d3/d3.csv.js"></script>
    <script src="d3/d3.layout.js"></script>
</head>

<body>
    <style type="text/css">
        .chart rect {
        stroke: white;
        }
    </style>

<script>


    var t = 1297110663, // start time (seconds since epoch)
        v = 70, // start value (subscribers)
        sentidata = d3.range(33).map(next); // starting dataset

    var w = 20,
        h = 80;

    var x = d3.scale.linear()
        .domain([0, 1])
        .range([0, w]);

    var y = d3.scale.linear()
        .domain([0, 200])
        .rangeRound([0, h]);

    var z = d3.scale.ordinal()
        .range(["lightpink", "darkgray"]);

    //This function generates random test data in the format : time, posvalue, negvalue
    function next() {
        return {
        time: ++t,
        posvalue: v = ~~Math.max(10, Math.min(90, v + 10 * (Math.random() - .5))),
        negvalue: v = ~~Math.max(10, Math.min(90, v + 10 * (Math.random() - .5)))
        };
    }

    //This function updates the data with one new data point and calls the redraw function to update the graph
    setInterval(function() {
        sentidata.shift();
        sentidata.push(next());    
        redraw(sentidata);
        }, 1500);

    var svg = d3.select("body").append("svg:svg")
        .attr("class", "chart")
        .attr("width", w * sentidata.length - 1)
        .attr("height", h);


    //Transpose the data into layers by Sentiment
    var sent = d3.layout.stack()(["posvalue","negvalue"].map(function(sentiment){
        return sentidata.map(function(d){
            return {x:d.time, y:+d[sentiment]};
            });
        }));


    //Add a group for each Sentiment
    var sentiment = svg.selectAll("g.sentiment")
                        .data(sent)
                        .enter()
                        .append("svg:g")
                        .attr("class","sentiment")
                        .style("fill", function(d,i){return z(i);})
                        .style("stroke", function(d,i){return d3.rgb(z(i)).darker();});

    //Add a rectangle for each time value
    var rect = sentiment.selectAll("rect")
                        .data(Object)
                        .enter()
                        .append("svg:rect")
                        .attr("x",function(d, i) { return x(i) - .5; })
                        .attr("y",function(d){return h - y(d.y0)-y(d.y);})
                        .attr("height", function(d){return y(d.y);})
                        .attr("width",w);


    svg.append("line")
        .attr("x1", 0)
        .attr("x2", w * sentidata.length)
        .attr("y1", h - .5)
        .attr("y2", h - .5)
        .style("stroke", "#000");


    function redraw(data) {

        //Transpose the data into layers by Sentiment
        var sent = d3.layout.stack()(["posvalue","negvalue"].map(function(sentiment){
           return data.map(function(d){
               return {x:d.time, y:+d[sentiment]};
               });
           }));

        //Add a group for each Sentiment
        var sentiment = svg.selectAll("g.sentiment")
                        .data(sent)
                        .transition()
                        .duration(1000)
                        .attr("class","sentiment")
                        .style("fill", function(d,i){return z(i);})
                        .style("stroke", function(d,i){return d3.rgb(z(i)).darker();});

        var rect = sentiment.selectAll("rect")
                .data(Object)
                .transition()
                .duration(1000)
                .attr("y",function(d){return h - y(d.y0)-y(d.y);})
                .attr("height", function(d){return y(d.y);});

    }

</script>
</body>
</html>

The initial stacked chart plots correctly. However, when I trigger the redraw method, I encounter an error stating "[object Object] has no method 'data'". This error occurs when attempting to initialize the 'rect' variable.

var rect = sentiment.selectAll("rect")
                    .data(Object)

I'm unsure what mistake I might have made. Any suggestions or guidance would be greatly appreciated!

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

Combining and mapping arrays in Javascript to form a single object

I am using the following firebase function this.sensorService.getTest() .snapshotChanges() .pipe( map(actions => actions.map(a => ({ [a.payload.key]: a.payload.val() }))) ).subscribe(sensors => { ...

Incorporating information from an array into a Chart.js line chart

How can I dynamically add data in a loop for different array sizes using the code provided below? The data stored in dataGraph and measureAttr holds the attributes needed. currentChart = new Chart(document.getElementById("chart"), { type: &apo ...

Adjusting specific sections of a container in real-time

Fiddle: https://jsfiddle.net/1b81gv7q/ Sorry for the slightly cryptic title; I couldn't come up with a better way to phrase it. Imagine this scenario: there's a container with content that needs to be dynamically replaced. If I wanted to repla ...

Removing undesired entries from a table view using AngularJs

In my table, there is a column called status which could have values like 'Open', 'Closed', 'Verified' and 'Rejected'. I am looking for a way to implement a filter in ng-repeat that will hide the rows with the statu ...

How to resolve a Cross-Origin Resource Sharing (CORS) error when trying to access a local JSON file

Currently, I am attempting to use vanilla JS AJAX request in order to retrieve a JSON string from a locally stored JSON file. My main objective is to accomplish this without relying on JQuery. The code snippet below was inspired by this answer. Despite my ...

The Dropbox picker is now launching in a new tab instead of a new window when using Chrome

I am encountering an issue with opening Dropbox picker in a new modal window. It works perfectly in all browsers except for Google Chrome. Is there anyone who can guide me on why it opens in a new tab in Chrome? Is there a parameter in options that I can ...

Compilation of various route parameters

This route configuration example showcases how to extract parameters from a URL: URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby Route: /Chapter/:chapterId/Section/:sectionId Using this setup, we can obtain the following object: {chapt ...

Issues Arising from the Implementation of .on() on Newly Added Elements

After learning that .live() has been deprecated, I switched to using .on. However, I encountered an issue where .on is not working for dynamically added elements in the DOM. In my script, a table is added with multiple text boxes (input type="text"), and ...

Is there a callback or event that can be used to ensure that getComputedStyle() returns the actual width and height values?

Currently, I find myself in a situation where I need to wait for an image to load before obtaining its computed height. This information is crucial as it allows me to adjust the yellow color selector accordingly. Question: The process of setting the yello ...

An easy way to retrieve the accurate price based on quantity from a list using Cakephp 2.x

I am currently working on a listing page that displays item name, price, and quantity. My goal is to implement a feature where if a user increases the quantity of an item from the list, the price will also change accordingly. Below is a snippet from my f ...

JavaScript: Harnessing the power of scripts to handle dynamically loaded data via AJAX

I am currently working on a webpage where I need to display various events using AJAX and PHP. One requirement is that when a user clicks on the "view event" link at the bottom of each event, a modal window should pop up. To achieve this functionality, I h ...

Embarking on your journey with the Withings API

How can I connect to my website with the Withings API? I want to send weight values to the Withings API and receive body measurement values. Where can I find the code for the Withings API? $config['withings_settings']['widgets'] = &apo ...

Disable the form options listed on the table

I have a scenario where I have a table and a form containing a dropdown list: <table> <tr> <td class="text">Apple</td> <td class="name">John</td> </tr> <tr> <td class=" ...

Issue: ng-file-upload validation is not functioning correctly, resulting in the form always being considered valid

I'm looking to implement a file-upload feature for each item in an array. In order to achieve this, I am utilizing the ng-repeat directive to cycle through the array and incorporating the ng-file-upload plugin to manage the file upload process along w ...

Trigger a function in AngularJS when a div is scrolled to within a specific number of pixels from the bottom of the screen

I am experimenting with the AngularJS infinite-scroll directive. Below is the code snippet: angular.module('infiniteScroll', []) .directive('infiniteScroll', [ "$window", function ($window) { return { link:funct ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...

Switch between accordion items

Currently, I have a React Js accordion in which clicking on an item opens the panel. To close it, you need to click on another item. However, I am looking to enhance this functionality by allowing the active panel to be closed after clicking on the AccButt ...

Is it possible to refresh AdSense banner when the router changes?

Is there a way to reload the AdSense banner ads when the router changes? I've been encountering issues trying to re-add the script and HTML properly. Any guidance on how this should be done would be greatly appreciated... This is just a test for one ...

Error: The JSON ajax request encountered an unexpected number, resulting in an uncaught Syntax

My goal is to send a get request to a website and retrieve the response. Although I am able to successfully make the HTTP request and obtain a response, my code breaks due to a javascript error that keeps popping up. I suspect that the issue may be relat ...

Instructions on toggling button visibility based on dropdown selection?

My goal is to have a button hidden by default, and when I select an option from a dropdown list, the button should appear. Check out the code on JSFIDDLE $(function() { $('#cashbill').change(function() { $('#bill_icon').hide() ...