Hover Text and Formatting in JavaScript

How to add hover text and format hover values in D3.js-based javascript charts.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Sign up for early access now.

var data = [
  {
    x: [0, .5, 1, 1.5, 2],
    y: [1, 3, 2, 4, 2],
    mode: 'markers',
    marker: {size:16},
    text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
    type: 'scatter'
  }
];
var layout = {
  title: {
      text: 'Hover over the points to see the text'
  }
};
Plotly.newPlot('myDiv', data, layout);
Click to copy
00.511.5211.522.533.54
Hover over the points to see the text
// Round x and y hover values by setting hoverformat in layout.xaxis and/or layout.yaxis
// using D3 number formatting ( https://github.com/mbostock/d3/wiki/Formatting )

var N = 40,
    x = d3.range(N).map( d3.random.normal() ),
    y1 = d3.range(N).map( d3.random.normal() ),
    y2 = d3.range(N).map( d3.random.normal() ),
    data = [{ x:x, y:y1, type:'scatter', mode:'markers',
              marker:{color:'rgba(200, 50, 100, .7)', size:16},
              hoverinfo:"x+y"
             },
            { x:x, y:y2, type:'scatter', mode:'markers',
             marker:{color:'rgba(10, 180, 180, .8)', size:16},
             hoverinfo:"x+y"}];
    layout = {
    hovermode: 'closest',
    title: {
        text: 'Formatting X & Y Hover Values'
    },
    xaxis: {
        zeroline: false,
        hoverformat: '.2f',
        title: {
            text: 'Rounded: 2 values after the decimal point on hover'
        }
    },
    yaxis: {
        zeroline: false,
        hoverformat: '.2r',
        title: {
            text: 'Rounded: 2 significant values on hover'
        }
    }
};

Plotly.newPlot('myDiv', data, layout);
Click to copy
−2−10123−2−10123
trace 0trace 1Formatting X & Y Hover ValuesRounded: 2 values after the decimal point on hoverRounded: 2 significant values on hover
var data = [
    {
        type: 'scatter',
        mode: 'lines+markers',
        x: [1,2,3,4,5],
        y: [2.02825,1.63728,6.83839,4.8485,4.73463],
        hovertemplate: '<i>Price</i>: $%{y:.2f}' +
                        '<br><b>X</b>: %{x}<br>' +
                        '<b>%{text}</b>',
        text: ["Text A", "Text B", "Text C", "Text D", "Text E"],
        showlegend: false
    },
    {
        x: [1,2,3,4,5],
        y: [3.02825,2.63728,4.83839,3.8485,1.73463],
        hovertemplate: 'Price: %{y:$.2f}<extra></extra>',
        showlegend: false
    }
];

var layout = {
    title: {
        text: "Set hover text with hovertemplate"
    },
};

Plotly.newPlot('myDiv', data, layout);
Click to copy
11.522.533.544.55234567
Set hover text with hovertemplate