Unable to view the D3.js violin plot on display

Hello, I'm just starting out with JavaScript and trying to implement this code from using my own data.

<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<script>

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 40},
    width = 1200 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// Read the data and compute summary statistics for each specie
d3.csv("violinsummary.csv", function(data) {

    // Show the X scale
    var x = d3.scaleBand()
        .range([0, width])
        .domain(["2017-09", "2017-10","2018-02","2018-03"])
        .paddingInner(1)
        .paddingOuter(.5);
    svg.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

    // Show the Y scale
    var y = d3.scaleLinear()
        .domain([80, 100])
        .range([height, 0]);
    svg.append("g").call(d3.axisLeft(y));

  // Features of density estimate
  var kde = kernelDensityEstimator(kernelEpanechnikov(.2), y.ticks(50));


  // Compute the binning for each group of the dataset
  var sumstat = d3.nest()  // nest function allows to group the calculation per level of a factor
    .key(function(d) {
      return d.DATE;})
    .rollup(function(d) {   // For each key..
      input = d.map(function(g) {
        return g.Power;});
      density = kde(input);   // And compute the binning on it.
      return(density);
    })
    .entries(data);
  console.log(input);
  console.log(density);

  // What is the biggest value that the density estimate reach?
  var maxNum = 0;
  for ( i in sumstat ){
    allBins = sumstat[i].value;
    kdeValues = allBins.map(function(a){return a[1]});
    biggest = d3.max(kdeValues);
    if (biggest > maxNum) { maxNum = biggest }
  }
  console.log(allBins);
  console.log(kdeValues);
  console.log(biggest);


  // The maximum width of a violin must be x.bandwidth = the width dedicated to a group
  var xNum = d3.scaleLinear()
    .range([0, x.bandwidth()])
    .domain([-maxNum,maxNum]);

  console.log(sumstat);

  // Add the shape to this svg!
  svg
    .selectAll("myViolin")
    .data(sumstat)
    .enter()        // So now we are working group per group
    .append("g")
      .attr("transform", function(d){ return("translate(" + x(d.key) +" ,0)") } ) // Translation on the right to be at the group position
    .append("path")
        .datum(function(d){ return(d.value)})     // So now we are working density per density
        .style("stroke", "none")
        .style("fill","#69b3a2")
        .attr("d", d3.area()
            .x0(function(d){ return(xNum(-d[1])) } )
            .x1(function(d){ return(xNum(d[1])) } )
            .y(function(d){ return(y(d[0])) } )
            .curve(d3.curveCatmullRom)    // This makes the line smoother to give the violin appearance. Try d3.curveStep to see the difference
        )

    });



// 2 functions needed for kernel density estimate
function kernelDensityEstimator(kernel, X) {
  return function(V) {
    return X.map(function(x) {
      return [x, d3.mean(V, function(v) { return kernel(x - v); })];
    });
  };
}
function kernelEpanechnikov(k) {
  return function(v) {
    return Math.abs(v /= k) <= 1 ? 0.75 * (1 - v * v) / k : 0;
  };
}


</script>

I believe there might be an issue in the part of the code where I add the shape to the SVG. All console log outputs seem to display accurate data. I have also compared the data types between the example's data and mine, they remain consistent.

Data (violinsummary.csv):

Power,DATE
89.29,2017-09
89.9,2017-09
91.69,2017-09
89.23,2017-09
91.54,2017-09
88.49,2017-09
89.15,2017-09
90.85,2017-09
89.59,2017-09
93.38,2017-10
92.41,2017-10
90.65,2017-10
91.07,2017-10
90.13,2017-10
91.73,2017-10
91.09,2017-10
93.21,2017-10
91.62,2017-10
89.58,2017-10
90.59,2017-10
92.57,2017-10
89.99,2017-10
90.59,2017-10
88.12,2017-10
91.3,2017-10
89.59,2018-02
91.9,2018-02
87.83,2018-02
90.36,2018-02
91.38,2018-02
91.56,2018-02
91.89,2018-02
90.95,2018-02
90.15,2018-02
90.24,2018-02
94.04,2018-02
85.4,2018-02
88.47,2018-02
92.3,2018-02
92.46,2018-02
92.26,2018-02
88.78,2018-02
90.13,2018-03
89.95,2018-03
92.98,2018-03
91.94,2018-03
90.29,2018-03
91.2,2018-03
94.22,2018-03
90.71,2018-03
93.03,2018-03
91.89,2018-03

Answer №1

x.paddingInner is causing the violins to be too compressed due to a large value, making them hard to see. A paddingInner of 1 results in no bandwidth for display.

By adjusting the x.paddingInner to a smaller value like 0.1, the x scale will have a wider bandwidth, expanding the range for xNum scale and making the violins more visible.

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

An error occurs when calling useSWR in a function that is neither a React function component nor a custom React Hook function

When using useSWR to fetch data from an endpoint, I encountered the following error (I only want to fetch data onclick) "useSWR is called in function `fetchUsers` that is neither a React function component nor a custom React Hook function" Error ...

Creating a touch-like scrolling experience with CSS and the mouse

Is there a way to incorporate mouse scroll functionality in my Angular app similar to the scrolling feature on touch screen devices where you swipe left or right to navigate? I'm interested in implementing a scrolling technique that allows users to cl ...

Is it possible to verify if a string in JavaScript contains both numbers and special characters?

I created this function to check if a string contains numbers and special characters, but it seems to not be working correctly let validateStr = (stringToValidate) => { var pattern = /^[a-zA-Z]*$/; if (stringToValidate&& stringToValidate.leng ...

Efficiency in Javascript coding techniques

Hey there, I'm seeking some feedback on the efficiency of my aspect ratio function. This function is designed to determine the aspect ratio and limit the size of an image. Take a look and let me know what you think! function constrainTwoNumbers(optio ...

Tips for creating a Carousel with more than three images using Bootstrap

Recently, I attempted to enhance my Carousel in Bootstrap by adding more images. Initially, I inserted the code snippet below within the ordered list with the class "carousel-indicators." <li data-target="#carouselExampleCaptions" data-slide-to=" ...

Turn off drag and drop functionality and activate selection in HTML

Recently, I encountered a strange issue where selected text became draggable and droppable onto other text, causing it to concatenate. To resolve this problem, I added the following code: ondragstart="return false" onmousedown="return false" However, thi ...

Tips for implementing event handlers on dynamically generated li elements in VueJS

Creating multiple ul elements using v-for in the following way <div v-for="item in info"> <ul> <li><a>{{item.number}}</a></li> <li><a>{{item.alphabet}}</a></li> </ul> </div&g ...

The HTML video will only be visible when the window is resized

I recently attempted to incorporate the vide.js jQuery extension into my project in order to implement a video background within a div element. Below is the code snippet for the video div: <div id="header" data-vide-bg="mp4: graphics/videos/identity.mp ...

JavaScript's search function is encountering issues when working with multidimensional arrays

I have an array containing city names and postal codes that I need to search through. I can successfully search for the city name and retrieve the result, but when I try to search for a postal code, it doesn't register. My question is: How can I modif ...

Display or conceal rendering in Rails upon clicking a button

I'm attempting to accomplish a seemingly simple task that is proving quite challenging. My goal is to conceal a render or partial in a specific view within my Rails application. Despite my efforts to find a solution, I have not come across any working ...

Using Node and Mongoose to link documents that rely on each other for reference

Is there a way to add a document after another document has been successfully inserted using node and mongoose? For example, I initiate the creation of a document with mongoose, and once it is successfully added, I want to trigger the insertion of another ...

The significance of the "? :" operator in JavaScript

These are the lines of code I am currently working with: toggleMore : function( $item, show ) { ( show ) ? $item.find('a.ca-more').show() : $item.find('a.ca-more').hide(); }, Could someone help me understand what this code does? ...

Angular 1.6 limits the ability to include multiple custom components on a single page

I'm currently working with angular 1.6 and have encountered an issue with two components, config-list and request-dates. Both components function correctly individually on a page, but when I attempt to add both components to the same page, only the s ...

What causes the AJAX JSON script to output an additional 0?

Within my WordPress website, there is an AJAX function that reaches out to a PHP function in order to retrieve a specific value from a transient record stored in the Database. Whenever I trigger this function with jQuery, I successfully receive the result ...

"Utilize Angular's $http options for requesting instead of using

When I attempt to send a $http POST request to a server API, the request method unexpectedly changes to OPTIONS. Strangely, this issue only occurs when working with localhost. To troubleshoot, I tried making the same request using Postman and it worked fla ...

Ways to retrieve the starting position of a span element and then append a value to a hidden field

Link to the Fiddle example: http://jsfiddle.net/socc95bd/1/ JQuery code snippet: var offsets = $('#ss').offset(); var left = offsets.left; $("#hfYN").val(left); alert(left); $(".switch input").on("click", function () { var offsets = $(&apo ...

Spotify app experiencing issues with Angular's ng-repeat functionality

In my code, I am facing an issue where ng-repeat is not functioning as expected. Here is the content of my App.js file: var app = angular.module('angularjs-starter', ['jsonService', 'ngRoute', 'ngResource']) app. ...

Incorporating an HTML page into a tab through Ajax with the help of a for loop, utilizing Bootstrap 3

Currently, I am developing an Address Book application where the main page displays a series of tabs with the names of the contacts from the contact.objects using a for loop in the code below. How can I utilize ajax to load the information of each contact ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...