'How do I plot an area chart in p5.js?

I am trying to recreate this visualization using p5.js. I have some trouble understanding how to create the coordinates for the new points and plot them on my canvas.

The data is a series of negative-positive values that need to be plotted below and above an X-axis respectively (from left to right). This is a sample:

"character","roll_value"
"Daphne Blake",0
"Daphne Blake",-1
"Daphne Blake",-1
"Daphne Blake",-5
"Daphne Blake",-3
"Daphne Blake",2

So I know that I have to map the values between a certain negative and positive height so I've demarcated those heights as follows:

enter image description here

let maxNegativeHeight = sketch.height - 120;
let maxPositiveHeight = sketch.height/4;

For mapping the input I thought of creating a new function called mapToGraph which takes in the roll_value, the old X position, max height and min height. This would map the old values to a new incremented X position and a vertical height:

 const mapToGraph = (value, oldXPos, maxHeight, minHeight) => {
    const newXPos = oldXPos + 10;
    const newYPos = sketch.map(value, 0, maxHeight, minHeight, maxHeight);
    return [newXPos, newYPos];
  };

In my draw function, I am drawing the points as follows:

 sketch.draw = () => {
    for(let i = 0; i < data.getRowCount(); i++) {
      let character = data.getString(i, "character");
      if(character === 'Daphne Blake'){
        console.log(character);
        // Draw a horizontal line in the middle of the canvas
        sketch.stroke('#F18F01');
        sketch.line(0, sketch.height/2, sketch.width, sketch.height/2);
        // Plot the data points
        let value = data.getNum(i, "roll_value");
        let [newX, newY] = mapToGraph(value, 0, maxNegativeHeight, maxPositiveHeight);
        console.log(newX, newY);
        sketch.strokeWeight(0.5);
        sketch.point(newX, newY);
      }
    }
  };

However, this does not plot any points. My console.log shows me that I am not processing the numbers correctly, since all of them look like this:

10 -3
cardThree.js:46 Daphne Blake
cardThree.js:55 10 -4
cardThree.js:46 Daphne Blake
cardThree.js:55 10 -4
cardThree.js:46 Daphne Blake

What am I doing wrong? How can I fix this and plot the points like the visualization I linked above?

Here is the full code of what I've tried (live link to editor sketch).

This is the full data



Solution 1:[1]

In your code newX is always 10 since you always pass 0 as the second argument to mapToGraph. Additionally the vertical displacement is always very small and often negative. Since you are using newY directly rather than relative to the middle of the screen many of the points are off screen.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul Wheeler