简体   繁体   中英

Horizontal wavelength colorbar legend for line plot

I have 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

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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM