Search code examples
javascriptplotlystacked-area-chart

Fill / Shade a chart above a specific Y value in PlotlyJS


I would like to fill until a specific Y value in PlotlyJS. This is as far as I got from the PlotlyJS docs: Fiddle

{
  "x": [
    "2016-01-31T00:03:57.000Z",
    "2016-02-12T04:35:26.000Z"
  ],
  "y": [
    100,
    100
  ],
  "fill": "tonexty",
  "fillcolor": "#8adcb3"
}

In the documentation, there seems to be two options:

  1. tonexty - Fills as below. The problem is 'tonexty' is a bit limiting - The use case is 'filling until the line', so shading ONLY above 110. Example:

enter image description here

  1. tozeroy - Fills till zero:

enter image description here

Also, do you need to introduce a new trace in order to create a fill?

This means that if I have a chart as follows (with only one trace but a threshold line as a shape): I need to introduce another trace just to create a fill. Maybe there's something I missed in the docs, or this is the wrong approach altogether. enter image description here

So, how do you fill an area in a trace above a specific Y value in PlotlyJS?


Solution

  • A solution is to use multiple traces.
    Split all your traces between ones which are above 0 and ones which are not.
    When you are done you can fill them (or not) with the 'tozeroy' value.

    The following jsfiddle shows a working example.

    The code is as following :

    HTML:

    <div id="myDiv" style="width:600px;height:250px;"></div>
    

    JS:

    var data = [
      {
        x: ['A', 'B', 'C', 'D'],
        y: [1, 3, 6, 0],
        fill: 'tozeroy',
        fillcolor: '#8adcb3'
      },
      {
        x: ['D', 'F', 'G', 'I'],
        y: [0, -3, -2, 0],
        fill: 'toself'
      },
       {
        x: ['I', 'J', 'K'],
        y: [0, 5, 7],
        fill: 'tozeroy',
        fillcolor: '#0adcb3'
      }
    ];
    
    Plotly.newPlot('myDiv', data);
    

    The result looks as following :
    Result plot