Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a name or label to shapes in plotly?

I have created a simple plotly line graph as follows:

var trace1 = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
type: 'scatter' 
};

var layout = {
xaxis:{
title:"x-axis",
tickangle:45,
rangemode:'nonnegative',
autorange:true,
exponentformat: "none"
},
yaxis:{
title: "Time",
tickangle:45,
rangemode:'nonnegative',
range:[0,20],
autorange: false
},
shapes: [
    {
    type: 'line',
    xref: 'paper',
    x0: 0,
    y0: threshold1,
    x1: 1,
    y1: threshold1,
    line:{
        color: 'rgb(255, 0, 0)',
        width: 2,
        dash:'dot'
        },
    },
    {
    type: 'line',
    xref: 'paper',
    x0: 0,
    y0: threshold2,
    x1: 1,
    y1: threshold2,
    line:{
        color: 'rgb(0, 255, 0)',
        width: 2,
        dash:'dot'
        },
    }
]
    };


Plotly.newPlot(myDiv,[trace1],layout);

Now, I want to add a name or label to the threshold1 and threshold2 that I have created in 'shapes' under 'layout'. I searched the plotly JS documentation but did'nt get anything useful there. How can I do this. Any help would be appreciated.

like image 923
Abhi Avatar asked Sep 13 '25 06:09

Abhi


1 Answers

You could create another trace with mode: 'text'. There is certainly more than one way of doing it but this one is simple and does not need complicated data replication.

var threshold1 = 12;
var threshold2 = 16;
var offset = 0.75;

var trace1 = {
  x: [1, 2, 3, 4],
  y: [10, 15, 13, 17],
  type: 'scatter'
};

var trace2 = {
  x: [Math.min.apply(Math, trace1.x) + offset, 
      Math.max.apply(Math, trace1.x) - offset],
  y: [threshold1 - offset, threshold2 - offset],
  mode: 'text',
  text: ['lower threshold', 'upper threshold'],
  showlegend: false
}

var layout = {
  xaxis: {
    title: "x-axis",
    tickangle: 45,
    rangemode: 'nonnegative',
    autorange: true,
    exponentformat: "none"
  },
  yaxis: {
    title: "Time",
    tickangle: 45,
    rangemode: 'nonnegative',
    range: [0, 20],
    autorange: false
  },
  shapes: [{
    type: 'line',
    xref: 'paper',
    x0: 0,
    y0: threshold1,
    x1: 1,
    y1: threshold1,
    line: {
      color: 'rgb(255, 0, 0)',
      width: 2,
      dash: 'dot'
    },
  }, {
    type: 'line',
    xref: 'paper',
    x0: 0,
    y0: threshold2,
    x1: 1,
    y1: threshold2,
    line: {
      color: 'rgb(0, 255, 0)',
      width: 2,
      dash: 'dot'
    },
  }]
};


Plotly.newPlot(myDiv, [trace1, trace2], layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id='myDiv'></div>
like image 133
Maximilian Peters Avatar answered Sep 14 '25 20:09

Maximilian Peters