Horizontal wavelength colorbar legend for line plot

Question:

I have a line plot with a bunch of signals in the form of (wavelength, intensity) derived from an optics experiment. All of them share the exact same index (wavelength in the range of visible light).

I want to add a simple, static horizontal colorbar legend at the bottom for better visual interpretation.

I’ve been googling for two whole days and cannot for the life of me get this to work. This should be a very simple and already implemented feature for such a rich plotting library like plotly but I cannot find it anywhere.

I’m using graph_objects.Scatter, in the following straightforward way:

fig = graph_objects.Figure()
fig.add_trace(
    graph_objects.Scatter(
        x=signal.wavelength,  # signal is a pd.DataFrame
        y=signal.intensity,
        mode='lines',
        line_shape='spline',
        text=signal.wavelength,
    )
)

I’ve tried both fig.update_layout() and fig.update_coloraxes() with all the combinations I could think of without any luck. Almost all the info I could find either uses px, wants to assign color to the line itself or uses mode='markers' instead of lines.

Any hint, reference to other posts, documentation or anything is appreciated.

Relevant links: colorscale, coloraxis, layout

Asked By: oropo

||

Answers:

The graph object does not support the horizontal type of color bar, so draw a scatter plot of the express and place the color bar horizontally. Add to it the line mode of the scatterplot created in the graph object. Since the data was not presented to me, I created it assuming x-axis as wavelength and y-axis as intensity, so please modify it to fit your data.

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np

N = 200
random_x = np.linspace(380, 780, N)
random_y1 = np.random.randn(N)

df = pd.DataFrame({'random_x': random_x,'random_y': random_y1})

line = go.Figure(data=go.Scatter(x=df['random_x'], y=df['random_y'], line_shape='spline')) 
fig = px.scatter(df, x='random_x', y='random_y', color='random_x', color_continuous_scale='Turbo')
fig.add_trace(go.Scatter(line.data[0], line_color='royalblue', showlegend=False))

fig.update_layout(
    coloraxis=dict(
        colorbar=dict(
            title='',
            orientation='h',
            y=-0.55)
    )
)
fig.update_xaxes(range=[380,780])

fig.show()

enter image description here

Answered By: r-beginners
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.