Search code examples
pythonplotlyplotly-dashplotly-python

Define Color for specific data in plotly python


I implemented a Timeline to display my data. To create the Timeline I used:

fig = px.timeline(df
                  , x_start="Start"
                  , x_end="End"
                  , y="Name"
                  , hover_name="Task"
                  , opacity=0.8
                  , template='plotly_white'
                  , height=len(df)*35
                  , width=1150
                  , color="Type"
                  , category_orders=dict(
                    Name=df["Name"].drop_duplicates().tolist()
                    )
                  )

You can see that the colors are based on "Type". In my dataframe I have two types of Data: Releases and Epics. The colors look like follows:

enter image description here

The problem here is that colors are generated randomly. However, I would like to define the colors like this:

colors = {'Release':'rgb(255,239,0)', 'Epic':'rgb(148, 76, 228)'}
fig.update(color=colors)

Is there a way to do this?


Solution

    • have simulated some data to fit your code
    • have commented height and width so it fits on my screen
    • it's a simple case of using color_discrete_map
    import pandas as pd
    import numpy as np
    import plotly.express as px
    
    n = 8
    df = pd.DataFrame(
        {
            "Start": pd.date_range("1-jan-2021", freq="1M", periods=n),
            "End": pd.date_range("1-mar-2021", freq="1M", periods=n),
            "Name": [str(i) for i in range(n)],
            "Task": np.random.choice(list("ABCDE"), n),
            "Type": np.random.choice(["Epic", "Release"], n),
        }
    )
    
    fig = px.timeline(
        df,
        x_start="Start",
        x_end="End",
        y="Name",
        hover_name="Task",
        opacity=0.8,
        template="plotly_white",
        # height=len(df) * 35,
        # width=1150,
        color="Type",
        category_orders=dict(Name=df["Name"].drop_duplicates().tolist()),
        color_discrete_map={"Release": "rgb(255,239,0)", "Epic": "rgb(148, 76, 228)"},
    )
    
    fig
    

    enter image description here