Differentiating datasets in a single JSON file through d3

I am currently working on customizing the Line Plus Bar chart from nvd3 in a way that allows the chart to switch to data from a different day of the week (Sun-Sat) when a button is clicked.

At present, I am facing some difficulties as the chart is displaying data for all days of the week instead of just one. Below is my code snippet:

d3.json("employee_data.json",function(error,data) {
  if(error) return console.warn(error);
  nv.addGraph(function() {
      var chart = nv.models.linePlusBarChart()
            .margin({top: 30, right: 60, bottom: 50, left: 70})
            //We can set x data accessor to use index. Reason? So the bars all appear evenly spaced.
            .x(function(d,i) {
              console.log(i)
              return i })
            .y(function(d,i) {
              return d[1] })
            ;

      chart.xAxis.tickFormat(function(d,i) {
        var dx = data[0].values[i] && data[0].values[i][0] || 0;
        return 'Sun' + dx
      });

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

      chart.y2Axis
          .tickFormat(function(d) { return d3.format(',f')(d) });

      chart.bars.forceY([0]);

      d3.select('#chart svg')
        .datum(data)
        .transition()
        .duration(0)
        .call(chart);

      nv.utils.windowResize(chart.update);

      return chart;
  });

});

The structure of the JSON file resembles:

[
  {
    "key" : "Sun_Employees",
    "bar" : true,
    "color" : "#ccf",
    "values" : [[0,2],[1,2],[3,2],[4,3],...,[23,1]]
  },
  {
    "key": "Sun_Tasks",
    "color" : "#333",
    "values" : [[0,5],[1,6],[2,5],[3,7],...,[23,2]]
  },
  {
    "key" : "Mon_Employees",
    "bar" : true,
    "color" : "#ccf",
    "values" : [[0,2],[1,2],[3,2],[4,3],...,[23,1]]
  },
  {
    "key": "Mon_Tasks",
    "color" : "#333",
    "values" : [[0,5],[1,6],[2,5],[3,7],...,[23,2]]
  }
}

I suspect the issue lies with the .x(function(d,i) { return i}) line, but I'm uncertain about limiting it correctly.

Answer №1

Consider applying a filter to the data set prior to associating it with your chosen elements. An example implementation could be:

var filteredSet = dataSet.filter(function(item) { return item.category.includes("Sun"); });
d3.select('#visualization svg')
  .data(filteredSet)
  ...

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

What is the best method to reset values in ngx-bootstrap date picker?

At the moment, it is only accepting the most recently selected values. To see a live demo, click here. ...

Use PHP to transform an array into JSON format, then access and retrieve the JSON data using either jQuery or JavaScript

I have successfully generated JSON data using PHP: $arr = []; foreach($userinfo as $record) { $arr[] = array( 'BAid' => $record->getBAid(), 'BCid' => $record->getBCid(), 'BA ...

Implementing data updates in Ruby on Rails through AJAX or jQuery

Within a text field input lies the value of a database attribute (ref). Upon focusing on the field, a border appears and disappears upon clicking out. My dilemma is that I wish for the data within the text field to be saved in the database without the nee ...

Dealing with JSON data retrieved from a Django QuerySet using AJAX

I am utilizing a Django QuerySet as a JSON response within a Django view. def loadSelectedTemplate(request): if request.is_ajax and request.method == "GET": templateID = request.GET.get("templateID", None) ...

When you press the submit button, the screen automatically scrolls down but no action is taken

I'm currently utilizing Selenium WebDriver (Java) with the Firefox driver. Upon trying to click the 'Submit' button on a particular page, it only results in scrolling down the screen slightly. The button itself does not register the click, c ...

Troubleshooting Angular 5: Interceptor Fails to Intercept Requests

I have a valid JWT token stored in local storage and an interceptor that I borrowed from a tutorial. However, the interceptor is not intercepting requests and adding headers as expected. Here's where I am making a request: https://github.com/Marred/ ...

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

Reveal hidden elements once the form has been submitted

At this moment, the info, stat and foo elements are hidden. Strangely, when I submit the form, they don't become visible. However, if I incorporate the unhide() function within the <button onclick="unhide()"></button>, it works p ...

The absence of variable declaration in a 'for...of' loop is functional in .js files but does not work in

index.js let items = [{ item: 'apple' }, { item: 'banana' }, { item: 'orange' }]; for (item of items) { console.log(item); } Execute using node $ node index.js { item: 'apple' } { item: 'banana' } { ...

How can I convert a JSON object with an array field into an object with a String field using serialization

My JSON object looks like this: { "id" : "1", "children" : ["2","3"] } In my Java object (with constructor, getters and setters excluded), I have: public class Entity { public String id; public String children; } I'm trying to deserial ...

Is there any potential security vulnerability when using ActiveRecord::Serialization.from_json() in RoR to parse uploaded JSON?

Currently in the process of setting up an export-import feature in Ruby on Rails. I have been contemplating the possibility of malicious code injection since JSON has the capability to include JavaScript. Is there a risk that someone could inject harmful ...

Ways to flatten a structured json object

Looking to flatten a nested input JSON containing product attributes and items with their own attributes. The goal is to bring all the information to the root level, but struggling with the nested arrays. Unsure if it needs to be done in multiple steps. H ...

The current error received from navigator.geolocation.getCurrentPosition is "Position acquisition error: Unknown."

I am currently exploring the geolocation API in my project. After allowing my browser - whether it's on localhost or a web host - to access my location, I noticed that my console.log is displaying: Unknown error acquiring position I'm puzzle ...

Generating HTML content using Node.js

I am completely new to the MEAN-stack and have been trying to develop an application on openshift. However, I am facing difficulties in rendering a new page. Despite my efforts to search for solutions online, I keep encountering this error that I can&apos ...

Enhanced in Azure Functions Isolated Worker (.NET 8): Additional Quotation Marks Introduced in String within ActivityTrigger

Dear Stack Overflow Community Members, I have encountered a unique challenge following the migration of an Azure Functions app from an in-process model using .NET 6 to an isolated worker model with .NET 8. The issue arises when passing string parameters t ...

Bootstrap Modal inactive

Looking for someone with expertise in Bootstrap to help me out. I have a modal loading dynamic data from a MySQL database table, but the issue is that it appears disabled and I can't close it. I'm completely stuck and don't know how to fix i ...

unable to connect to PHP using AJAX JSON format

<html> <head> <script src="http://code.jquery.com/jquery-1.9.0.js"></script> <script charset="utf&minus;8" type="text/javascript"> function connect(e) { var term= {button:e}; ...

Why are my basic style properties not appearing correctly when I use json_encode on an array?

My calendar is written in Javascript within a table with the ID "calendario," allowing me to manipulate it using calendario.rows[i].cells[i]. This calendar lets users make reservations and provides an option to close a day if there are too many reservatio ...

VueJS search filter issue: 'search' property is not defined

Currently, I am in the process of developing an application that will consume JSON data and display it with a search filter feature, among other functionalities. I have attempted to create the necessary function for this task, however, it has not been suc ...

Adding a file to a firebase storage folder using Vue js

Currently, I am utilizing Vue js 3 in combination with Firebase 9. My objective is to upload images to a specified folder, however I seem to be encountering some difficulties. Whenever I attempt to do so, the file gets renamed to 'product' and up ...