1

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?

1

1 Answer 1

2
  • 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

Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly fine for me! However, I needed to define color_discrete_map category_orders. Otherwise, it would just assign colors randomly again. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.