79680316

Date: 2025-06-26 10:34:10
Score: 0.5
Natty:
Report link

I had a quick go at this as well. This option is also based on the example on the homepage

The key difference is that the ticks values are evenly spaced on the color bar

additional tick values are added to the top and bottom of the colorbar so that the min and max range are included

import plotly.graph_objects as go
import numpy as np

z = np.array([
    [10, 100.625, 1200.5, 150.625, 2000],
    [5000.625, 60.25, 8.125, 300000, 150.625],
    [2000.5, 300.125, 50., 8.125, 12.5],
    [10.625, 1.25, 3.125, 6000.25, 100.625],
    [0.05, 0.625, 2.5, 50000.625, 10]
])

user_min_tick = 0  # optional user defined minimum tick value
if user_min_tick < np.min(z) or user_min_tick <= 0:
    user_min_tick = np.min(z)  # ensure user_min_tick is not less than the minimum 

zmax = np.max(z)

# mask values below user_min_tick to user_min_tick
z_clipped = np.where(z < user_min_tick, user_min_tick, z)
z_log = np.log10(z_clipped)

log_min = int(np.ceil(np.log10(user_min_tick)))
log_max = int(np.floor(np.log10(zmax)))
tickvals_log = np.arange(log_min, log_max + 1)
tickvals_linear = 10.0 ** tickvals_log

# might want to comment out this section if you don't want colorbar top and tail values adding to the tickvalues
if not np.isclose(zmin_log, tickvals_log[0]):
    tickvals_log = np.insert(tickvals_log, 0, zmin_log)
    tickvals_linear = np.insert(tickvals_linear, 0, user_min_tick)
if not np.isclose(zmax_log, tickvals_log[-1]):
    tickvals_log = np.append(tickvals_log, zmax_log)
    tickvals_linear = np.append(tickvals_linear, zmax)

# format all tick labels the same way
ticktext = [f"{v:,.2e}" for v in tickvals_linear]

fig = go.Figure(go.Heatmap(
    z=z_log,
    zmin=np.log10(user_min_tick),
    zmax=np.log10(zmax),
    colorscale='Viridis',
    colorbar=dict(
        tickmode='array',
        tickvals=tickvals_log,
        ticktext=ticktext,
        title=dict(
            text='Value (log scale)',
            side='right'
        )
    )
))

fig.show()
Reasons:
  • Blacklisted phrase (1): to comment
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Jon