Have a Question?

If you have any question you can ask below or enter what you are looking for!

python – Imshow Plotly colour toggling using legend

To create an interactive plot in Python using Plotly with a color toggling feature using a legend, you can use the plotly.graph_objects module along with some callbacks from the dash library. Here’s a simple example:

import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y1': [10, 6, 11, 8, 9],
    'y2': [8, 5, 7, 10, 6],
    'y3': [5, 4, 3, 2, 7]

# Create a Dash web application
app = dash.Dash(__name__)

# Layout of the app
app.layout = html.Div([
    html.Label('Toggle Series:'),
            {'label': 'y1', 'value': 'y1'},
            {'label': 'y2', 'value': 'y2'},
            {'label': 'y3', 'value': 'y3'}
        value=['y1', 'y2', 'y3']

# Callback to update the plot based on toggled series
    Output('scatter-plot', 'figure'),
    [Input('toggle-series', 'value')]
def update_plot(selected_series):
    # Filter the dataframe based on selected series
    filtered_df = df[['x'] + selected_series]

    # Create scatter plot using Plotly Express
    fig = px.scatter(filtered_df, x='x', y=selected_series, title='Scatter Plot')

    # Update legend
    fig.update_traces(showlegend=True, legendgroup='group')

    return fig

# Run the app
if __name__ == '__main__':

This example uses the dash library to create a simple web application with a scatter plot. The dcc.Checklist component is used for selecting the series to display, and the callback function (update_plot) updates the scatter plot based on the selected series. The legend is updated accordingly to display only the selected series. The legendgroup attribute ensures that the legends are grouped together.

Leave a Reply

Your email address will not be published. Required fields are marked *