Search code examples
javascriptplotlyplotly.js

Plotly.js - Is there a way to draw vertical colorbar with minimum value on top and maximum on bottom?


I'm using plotly.js to plot scientific data.

I’m trying to reverse the colorscale orientation. Plotly draw vertical colorbar with max-value on top and min value on bottom.

Is possible to invert this feature? (min-value on top and max-value on botton)

I’ve tried the “reversescale” feature, but it inverts the colorscale too. Please help.

example

1


Solution

  • It is a bit of a hack but I did not find any other way to do it. Basically you can create a dummy plot with the properties of the colorbar you want. In this example I am using an empty scatter plot for it. Be aware that you need to manually insert the tick values for this to work.

    import plotly.graph_objects as go
    import numpy as np
     
    data = np.array([[1,2,3,4,5],
         [3,4,5,6,7],
         [7,8,9,6,4],
         [3,7,2,4,2]])
    
    # Ticks to appear in the colorbar 
    tickvals = [2, 5, 8]
    colorscale="Viridis"
    
    # Main plot 
    trace = go.Contour(z = data, colorscale=colorscale, colorbar_tickvals=tickvals,  showscale=False)
    
    # Dummy plot for colorbar
    colorbar_trace=go.Scatter(
                x=[None],
                y=[None],
                mode='markers',
                marker=dict(
                    colorscale=colorscale+'_r', 
                    cmin=np.min(data),
                    cmax=np.max(data),
                    colorbar=dict(tickvals=tickvals, ticktext=tickvals[::-1])),
                hoverinfo='none'
                )
    
    fig = go.Figure(data = [trace, colorbar_trace])
    fig.show()
    

    Example of Inverted Colorbar