Plotly Playground

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/plotly.js/3.1.1/plotly.min.js"></script>

  <div id="plot" style="height: 300px"></div>

JavaScript

// Load data
console.log('lajson');
document.addEventListener('readystatechange', function(event) {
console.log(document.readyState);
const data = [
  {
    "x": 0,
    "y": 722
  },
  {
    "x": 1,
    "y": 706
  },
  {
    "x": 2,
    "y": 521
  },
  {
    "x": 3,
    "y": 951
  },
  {
    "x": 4,
    "y": 492
  },
  {
    "x": 5,
    "y": 56
  },
  {
    "x": 6,
    "y": 794
  },
  {
    "x": 7,
    "y": 557
  },
  {
    "x": 8,
    "y": 290
  },
  {
    "x": 9,
    "y": 563
  },
  {
    "x": 10,
    "y": 226
  },];

const xValues = data.map((item) => item.x);
// scatter-chart2.ts sorts yValues descending before pairing with xValues.
const yValues = data.map((item) => item.y).sort((a, b) => b - a);

// Calculate Y range
let yMin = Number.MAX_VALUE;
let yMax = Number.MIN_VALUE;
for (const y of yValues) {
  if (y < yMin) yMin = y;
  if (y > yMax) yMax = y;
}
const yRange = yMax - yMin;
const third = yRange / 3;

const yellowLineY = yMin + third;
const redLineY = yMin + 2 * third;

// Calculate X range for padding
let xMin = Number.MAX_VALUE;
let xMax = Number.MIN_VALUE;
for (const x of xValues) {
  if (x < xMin) xMin = x;
  if (x > xMax) xMax = x;
}
const xDiff = xMax - xMin;
const xPadding = xDiff * 0.05;

// Define line start and end for traces (covering the allowed range)
const lineXStart = xMin - xPadding;
const lineXEnd = xMax + xPadding;

// Define Shapes (Bands)
// Shapes in Plotly: https://plotly.com/javascript/shapes/
// We want background bands. layer: 'below'
const shapes = [
  // Green Band
  {
    type: 'rect',
    xref: 'paper',
    yref: 'y',
    x0: 0,
    x1: 1,
    y0: yMin - yRange * 0.05,
    y1: yMin + third,
    fillcolor: 'rgba(0, 255, 0, 0.3)',
    line: { width: 0 },
    layer: 'below'
  },
  // Yellow Band
  {
    type: 'rect',
    xref: 'paper',
    yref: 'y',
    x0: 0,
    x1: 1,
    y0: yMin + third,
    y1: yMin + 2 * third,
 ...