pythonplotlyheatmapplotly-pythonlogarithm

Logarithmic heatmap in Plotly


I am using heatmap from Plotly. I want to use a logarithmic scale for the color but cannot find how to do so. Here is a MWE:

import plotly.graph_objects as go
import numpy as np

z = [[1e-4,1e-3,1e-2],
    [1e-1, 1, 1e1],
    [1e2, 1e3, 1e4]]

go.Figure(
    data = go.Heatmap(
        z = z,
    )
).show()

go.Figure(
    data = go.Heatmap(
        z = np.log(z),
    )
).show()

In the MWE I manually calculate the logarithm of the data. I want the color map to be shown as in the second figure but without having to manually transform the data, and also displaying the real z values in the color scale, not the logarithm.


Solution

  • I got tired of manually doing this every time so I wrote a simple function to automate this, which can be found here and is called imshow_logscale. It is fully compatible with plotly.express.imshow, it displays the real value (i.e. not the log) in the hover box as well as in the color scale, and it is really a logarithmic. Below a working example.

    import plotly_utils # https://github.com/SengerM/plotly_utils
    import numpy
    
    z1 = numpy.random.randint(1,100000,(33,33))
    z2 = numpy.random.randint(1,500,(33,33))
    
    for title,img in {'spanning many orders of magnitude':z1,'spanning few orders of magnitude':z2}.items():
        fig = plotly_utils.imshow_logscale(img, title=title)
        fig.show()
    

    enter image description here

    enter image description here

    Edit

    I recently added the option to draw contours: A heatmap with logarithmic scale made with Plotly