Skip to content
Advertisement

How to set heatmap aspect ratio

I have a single-channel image where each integer pixel value maps to a string. For example 5 -> ‘person’. I’m trying to create an interactive image where hovering over a pixel will display it’s corresponding string.

I figured using plotly heatmaps might be the way to do this. The issues I’m having are:

  • It’s really slow. If I make my numpy array even (100,100) size it takes minutes to load. I’m thinking it might be because my code is not efficient?
  • I can’t figure out how to maintain aspect ratio. So if my image is a size (100,100) numpy array, I’d like the plot to also be (100,100) pixels.
  • using blank values for z_text seems like a bad workaround, but setting annotation_text=None doesn’t seem to work.

Can anyone help me out here? Here’s what I’ve got:

JavaScript

And here’s what it currently looks like:

enter image description here

Also if a plotly heatmap is not the best way to go about this I’d love to hear any alternatives!

Note: I’m currently displaying inside jupyterlab.

Advertisement

Answer

I’m not sure if I’ve gotten every detail correct here, but the code in the snippet below will produce the following plot in a Jupyter Notebook. The line that handles the aspect ratio is:

JavaScript

You can also use:

JavaScript

Plot 1:

enter image description here

Plot 2:

Just make sure to include:

JavaScript

Or else you’ll end up with this:

enter image description here

Code 1 – My edits to your sample:

JavaScript

Code 2 – The whole thing for an easy copy&paste:

JavaScript

Speed:

Even this small figure takes some time to plot, but so far I do not have any suggestions on how to speed things up.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement