Sunday 20 August 2023

Select/pin a single pixel on a Plotly heatmap

On a Plotly heatmap, sometimes it's useful to have 2 select modes:

  • rectangle selection (already available in the modbar)

  • selection/pinning of a single pixel: I'm trying to do it by recycling the existing "drawcircle" button which I don't need. When clicked, the pixel should be highlighted, or have a coloured disc on top of it (or a red "pin", like Google Maps UI)

Problem: when drawcircle tool is selected in the modbar, the plotly_click event is not fired (so we can't get the coordinates), and plotly_selected doesn't give the initial mouseclick position. (I don't want to make a real circle shape, I only want to use the first click). See also Event Handlers in JavaScript

const z = Array.from({
  length: 50
}, () => Array.from({
  length: 50
}, () => Math.floor(Math.random() * 255)));
const plot = document.querySelector("#plot");
const data = [{
  type: 'heatmap',
  z: z
}];
const layout = {
  'yaxis': {
    'scaleanchor': 'x'
  }
};
const config = {
  modeBarButtons: [
    ["zoom2d"],
    ["zoomIn2d"],
    ["zoomOut2d"],
    ["autoScale2d"],
    ["select2d"],
    ["drawcircle"]
  ],
  displaylogo: false,
  displayModeBar: true
};
Plotly.newPlot('plot', data, layout, config);

plot.on("plotly_selected", (data) => {
  console.log(data);
});
plot.on('plotly_click', (data) => {
  console.log(data);
});
<script src="https://cdn.plot.ly/plotly-2.16.2.min.js"></script>
<div id="plot"></div>

How to have a "select/pin a pixel/point" modebar tool on a Plotly heatmap?

Note: the Python doc is more complete than the JS version here: Add/remove modebar buttons



from Select/pin a single pixel on a Plotly heatmap

No comments:

Post a Comment