Utilizing d3.csv to load CSV data into an nvd3 multiBar Chart demonstration (in JSON format)

I am attempting to recreate a nvd3.js multiBar Chart using my own .csv data. While I have come across similar questions in the past, none of them have provided a solution specific to my current issue. Some suggestions involve utilizing d3.entries, d3.nest, and creating variables to achieve the correct input format. However, I am struggling to understand how these techniques work.

Related questions: d3.js csv to nvd3 (stacked area chart) format ScatterChart in NVD3 – Reading the data from csv file d3 csv data loading

These inquiries focus on replicating other types of charts that require different JSON data formats. My main struggle lies in generating the "x" and "y" values within the nest function. In the example chart, they utilize a function to create data where they define the x (number of bars) and y (input values).

I aim to replicate this graph:

Using the following csv data:

date,Equipment:Electricity:LGF,Equipment:Electricity:GF,Equipment:Electricity:1st,Equipment:Electricity:2nd
jan,6726.864146,5648.080727,2598.709507,2042.260163
feb,6405.091236,5377.910358,2474.402801,1944.570663
mar,6727.448125,5648.571054,2598.935109,2042.437457
apr,6433.12227,5401.446071,2485.231698,1953.080819
may,6993.742947,5872.160325,2701.809623,2123.28394
jun,6433.12227,5401.446071,2485.231698,1953.080819
jul,6727.448125,5648.571054,2598.935109,2042.437457
aug,6993.742947,5872.160325,2701.809623,2123.28394
sep,6166.827448,5177.8568,2382.357183,1872.234336
oct,6993.742947,5872.160325,2701.809623,2123.28394
nov,6699.417092,5625.035342,2588.106212,2033.927301
dec,6167.411428,5178.347127,2382.582785,1872.411631

The expected data should follow this JSON format (actual version contains more data):

[
  {
    "key": "Stream #0",
    "values": [
      {
        "x": 0,
        "y": 0.4428573444644372
      },
      {
        "x": 1,
        "y": 1.1148710782512004
      },
      {
        "x": 2,
        "y": 1.4665579659689634
      }
    ]
  },
  {
    "key": "Stream #1",
    "values": [
      {
        "x": 0,
        "y": 0.14053699714131654
      },
      {
        "x": 1,
        "y": 0.1493057878687978
      },
      {
        "x": 2,
        "y": 0.12193947387887433
      }
    ]
  }
]

I have experimented with various solutions from related questions, resulting in outputs like this: https://i.sstatic.net/k5dh8.png. Here, you can see my attempt on the left based on an example, and on the right is the loaded JSON file.

CODE:

Any hints or explanations would be greatly appreciated!

Answer №1

If you're unsure about the final expected outcome, this code snippet can help you get started or even fully address your inquiry. I've used basic Javascript for the data transformation to hopefully enhance its clarity.

For a live demonstration, visit http://bl.ocks.org/timelyportfolio/c7c9dbc75975df7322bd.

    <script src = "http://d3js.org/d3.v3.js"></script>
    <script src = "http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.js"></script>

    <link rel = "stylesheet" href = "http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.css">


    <div id = "chart1">
      <svg></svg>
    </div>

    <script>
        d3.csv("data.csv",function(err,data){

          //get each key of the data that is not date
          //these will be our key in the key/value pair
          //the values x and y will be month and the value
          var dataToPlot = Object.keys(data[0]).filter(function(k){return k!="date"})
            .map(function(k){
              return {"key":k,"values":data.map(function(d){
               return {
                 //let's make this a real date
                 "x":d3.time.format("%Y-%b-%d").parse("2014-" + d.date + "-01"),
                 "y":+d[k]
               }
              })}
            })

          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.time.format('%b'));

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

            d3.select('#chart1 svg')
                .datum(dataToPlot)
                .call(chart);

            nv.utils.windowResize(chart.update);

            return chart;
          });

        })


    </script>

    </html>

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 way to format a date as "2020-01-16 07:29:43.657519000 Z" using JavaScript?

Upon discovering a format 2020-01-16 07:29:43.657519000 Z in a project, I am curious about the significance of the numbers 657519000 and how to replicate this precise format using JavaScript. When attempting new Date().toISOString(), I receive 2020-05-27T2 ...

Enable autocomplete feature in a PHP form once the user starts typing their name

After searching for similar questions, I couldn't find any with the same "variables," so here's my dilemma: I have a basic form where I input a name and I want the rest of the form to be filled in automatically (ID). Retrieving data from the da ...

How to send JSON data using HTTP POST in iOS?

My attempt at this code is resulting in an unauthorized error being returned AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager setRequestSerializer:[AFJSONRequestSerializer serializer]]; [manager.requestSeriali ...

Adjust the range directly in ng-repeat from the directive

I am working with HTML code that looks like this: <div dir-paginate="x in comments | itemsPerPage: commentsPerPage"> HERE IS DIRECTIVE FROM BLEOW </div> My goal is to update the commentsPerPage scope within the directive... Below is a direct ...

Guide on inserting text input value into the href attribute of a hyperlink

Lately, I've been facing an issue that has been troubling me for the past few hours. I have a search input field where users can enter text and click send. The entered text should then be added to the href attribute and sent to the results page for qu ...

Discover various ways to encapsulate Vue.js components

I am currently in the process of developing a website that utilizes classic multiple pages powered by blade templates. However, I am looking to incorporate vuejs2 components for more dynamic functionalities. Although things are running smoothly, I am faci ...

"Receiving data from an axios call in React using useEffect leads to an error message: "Property 'numero' cannot be read as undefined"

I am encountering an issue while trying to fetch a mock API using axios. Setting up the useEffect hook to fetch the API data const FetchMockAPI = () => { const [data, setData] = useState(); useEffect(() => { ...

How to add Bootstrap and Font Awesome to your Angular project

After attempting to add Bootstrap and Font Awesome to my Angular application, I am encountering issues. I utilized the command npm install --save bootstrap font-awesome and included both libraries in the angular.json file as follows: "styles": ...

Ways to retrieve information from a JSON object

Currently, I am working on an Ionic app where I need to send an array of condiments via a POST request to an API. These condiments are represented as checkboxes on the mobile end. My goal is to capture the checked checkboxes in order to dynamically generat ...

Is there a way to transfer gulp.watch() to a pipe?

Currently, I have a basic task set up for linting changed JavaScript files: gulp.task('default', function() { // monitor JS file changes gulp.watch(base + 'javascripts/**/*.js', function() { gulp.run(&ap ...

Flow bar for micro-tasks

In my current project, I am faced with the task of organizing a series of 4 mini tasks and displaying to the end user which specific mini task they are currently on. To accomplish this, I have been utilizing image tags for each task. <img>1</img ...

Is it possible to engage with a local webpage using an application and receive real-time feedback?

I am interested in finding a way to connect my local HTML page with my C++ application. Similar to using the JavaScript console to make real-time edits to a webpage, like this: document.getElementById('divlayer').style.visibility = 'hidden& ...

JavaScript inserted into debug console by developer

Is there a method to troubleshoot code that has been added through the firefox developer console terminal? For example, I added document.onkeydown = function(event) { // code logic for checking keys pressed } If only I could determine which .js file t ...

The NPM Install process seems to be skipping certain files that were successfully installed in the past

When I first installed NPM Install in a folder, it created multiple folders and files: node_modules public src .DS_Store package.json package-lock.json webpack.config.js After that, npm start functioned perfectly. Now, as I embark on a new project for th ...

What is the best approach to convert text to uppercase or lowercase based on the length of the string in Angular version 1.5?

My goal is to apply text formatting to a string named 'name'. Once the string is entered into an HTML form and the save button is clicked, the new formatted string should be displayed below the form. The formatting rule states that if the length ...

Pause and continue scrolling through the page with the push of a button

I have a question about a simple demo. I am looking to prevent scrolling when button1 is clicked, and then resume scrolling when button2 is clicked. Can someone guide me on how to achieve this? Check out the Fiddle here HTML: <input type='button& ...

Modify the current link's <li> class

I am facing an issue with the code below which is supposed to change the class of li based on whether the browser URL matches the href attribute within that li. The current problem I am encountering is that the code changes the class for all li elements, ...

JavaScript for validating forms in PHP

Hey everyone, I'm struggling to understand why the alert box isn't showing up when I run this code. I'm new to programming and find HTML easy, but I'm currently in a PHP class where we have been tasked with creating and validating a for ...

Adding data from a CSV file into a database by executing an update insert query

My code currently inserts data from a .csv file into a database, but there is a limitation where if a row from the .csv file is already inserted in the database, the user needs to remove that row and add a new one for insertion to avoid duplicate key entry ...

Flot.js chart on Asp.net webform fails to display when returning Json data

Currently, I am utilizing ASP.NET webforms to generate flot charts. In the test.aspx.cs file, I have established a connection to the database and implemented a [Webmethod] to retrieve data in JSON format. Upon receiving the data, I attempted to display it ...