Selecting the quartile value for every individual data point

I am currently graphing the sentiment values of tweets over a span of 10 years. The CSV file contains three columns as outlined below.

Successfully, I managed to plot each value by date. However, upon attempting to create an area graph, I encountered an issue where each date had multiple values.

This complication arises from each data point being derived from a single tweet, resulting in one x point having multiple y values.

In order to address this dilemma, I attempted to choose the quartile value of each date or select the largest or smallest y value for clarity. An example is provided below.

https://i.sstatic.net/xxLQi.png

For instance, January 8 exhibits multiple y values (textblob).

My objective is to generate an area graph while selecting either the largest value or the 2nd quartile value of each point.

How can I effectively pick the points?

The intention is to utilize the points in the following code as x/y coordinates for line or area graphs.

  function* vlinedrawing(data){
         for(let i;i<data.length;i++){
            if( i%500==0) yield svg.node();
            let px = margin+xscale(data[i].date)
            let py = height-margin-yscale(data[i].vader)
            paths.append('path')
            .attr('x',px)
            .attr('y',py)   
     }     
            yield svg.node()  
         }

The complete code can be found at the following link.

https://jsfiddle.net/soonk/uh5djax4/2/

Thank you in advance. ( The reason why it is a generator is that I'm going to visualize the graph in animated way)

Answer №1

To determine the 2nd quartile, you have a couple of options. One way is to utilize d3.quantile as follows:

d3.quantile(dataArray, 0.5);

Alternatively, since the 2nd quartile is essentially the median, you can simply use:

d3.median(dataArray);

Using d3.quantile provides more flexibility, allowing you to adjust the specified quartile by changing the p value.

If we consider your data without parsing dates (making it suitable for unique values using a Set), here's a potential solution:

const aggregatedData = [...new Set(data.map(function(d) {
    return d.date
}))].map(function(d) {
    return {
      date: parser(d),
      textblob: d3.quantile(data.filter(function(e) {
        return e.date === d
      }).map(function(e) {
        return e.textblob
      }), 0.5)
    }
});

This code serves as a guide and may not be optimized due to nested loops. You are encouraged to enhance its performance.

For demonstration purposes, please find below the script:

var parser = d3.timeParse("%m/%d/%y");

d3.csv('https://raw.githubusercontent.com/jotnajoa/Javascript/master/tweetdata.csv', row).then(function(data) {

  const aggregatedData = [...new Set(data.map(function(d) {
    return d.date
  }))].map(function(d) {
    return {
      date: parser(d),
      textblob: d3.quantile(data.filter(function(e) {
        return e.date === d
      }).map(function(e) {
        return e.textblob
      }), 0.5)
    }
  });

  console.log(aggregatedData)

});

function row(d) {
  d.vader = +d.vader;
  d.textblob = +d.textblob;
  return d;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

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

Please use Shift + Enter feature only when using desktop devices

In my React chat application, I have implemented a textarea for message input to allow multiline support. This works smoothly on mobile devices as pressing Enter creates a new line and a send button is available to submit the message. However, I want a di ...

Send the form via ajax

I am in the process of creating a unique application for my university, which is essentially a social network. One key feature I need to implement is the ability for users to add comments, which involves inserting a row into a specific database. To achieve ...

The issue with IE-9 is that it is mistakenly picking up the placeholder value as

My HTML code looks like this: <input id="SLOCriteriaOtherText" name="SLOCriteriaOtherText" style="width: 100%;" type="text" data-role="autocomplete" placeholder="Enter name for 'other' metric..." class="k-input" autocomplete="off" role="textb ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...

The sticky navigation and scroll to top features both function perfectly on their own, but when used simultaneously, they do not work

I'm facing an issue with two scripts on my website - when they are separate, they work perfectly fine but together, they don't seem to function properly. What could I be missing here? Script 1: window.onscroll = function() {myFunction()}; var n ...

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

Discover the method for inserting a title attribute value into a span element

Utilizing AngularJS to retrieve and display data within a span element. I am now aiming to utilize this value as the title for another span element. The current code being used is shown below: <span style="display: inline-block; width: 160px">{{acti ...

Sorting data in a Footable table by an unfinished line

My data table contains various lines like: 97.5%, 10/30, 41 RPM, 3.6 seconds, $4750, $100 When I set the type data-type = "number" in the rows, everything is stripped except for the numbers. However, I need the output to remain complete as shown in the ex ...

Why is it that despite passing all the unit tests successfully, the function fails when used in its actual context with the same parameters?

I have created a basic API to encrypt text using the Caesar cipher in Javascript with Express.js. While running tests with Jest, it seems that all the tests are passing successfully (and a console.log of the output confirms that the resulting string matche ...

Accessing index.html via file:// from Vue-cli template

Whenever I execute the npm run build command using this Vue-cli template, it displays this message: Hint: The built files are designed to be served over an HTTP server. Attempting to open index.html via file:// will not function correctly. Therefore, the ...

I'm attempting to integrate the map function into my React Redux application, but after implementing useDispatch, I'm encountering an error message in the console

I am currently troubleshooting an app I'm working on, but I keep encountering errors in the console. Included below is a picture of the error as well as the code snippet triggering the issue. Can anyone provide insight into what might be causing this ...

When a user clicks on a specific element's id, the image will rotate accordingly

When the elements in ul are clicked, the image rotates. The default position of the image is already rotated by a certain number of degrees, and on each click, it rotates to the desired value. This was achieved using the following code: $("#objRotates"). ...

What exactly is the purpose of measuring "First Load JS" in the @next/bundle-analyzer tool?

The analysis generated by the NextJS bundle analyzer appears as follows: Page Size First Load JS ┌ λ / 12 ...

Trouble with Bootstrap Collapse feature not collapsing on its own

I recently added a Bootstrap collapse feature to my payment view in Laravel. The Bootstrap section collapses when clicked, but I would like it to be collapsed by default. I understand that I need to include: aria-expanded="false" However, it still doesn& ...

Can you provide a way to directly calculate the total length of all arrays within an array of objects?

How can I find the total length of arrays in an array of objects based on a specific property? var myArray = [{ "a" : 1, "b" : another Array }, { "c" : 2, "b" : another Array } ..... ] Is there a more efficient way to achieve this instea ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

Learn how to showcase the current date by utilizing JavaScript arrays and the getDate method!

I have been struggling to format the date as follows: "Today is Sunday, the 31st day of March in the year 2019." I am working with JavaScript in an HTML5 document. Below is the code I have so far, and I would appreciate any help. I prefer not to rely on ...

Highlighting menu elements when landing on a page and making another menu element bold upon clicking in WordPress

I've been searching extensively for a solution to this issue. I'm trying to make the menu item DE appear bold when entering the site, and if I click on EN, I want DE to return to normal (thin) font while EN becomes bold. You can find the site he ...