How to get plotly.express.timeline overlapped bars to be visible

Question:

I’d like to know if anyone has a solution to overlapping timeline bars?

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
    dict(Task="Job B", Start='2009-02-25', Finish='2009-04-15', Resource="Alex"),
    dict(Task="Job C", Start='2009-02-23', Finish='2009-05-23', Resource="Max"),
    dict(Task="Job D", Start='2009-02-20', Finish='2009-05-30', Resource="Max")
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Resource")
fig.show()

enter image description here

And in the image it’s very difficult to see:

  • Where Job A ends/Job B starts
  • Job D is not visible at all

Any suggestions?

Asked By: Sergio Martins

||

Answers:

The best that I was able to figure out was using different colors for all of the "Tasks" or "Jobs", and having to opacity lower so that it was possible to see the traces/bars that were getting covered

The code looks like:

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
    dict(Task="Job B", Start='2009-02-25', Finish='2009-04-15', Resource="Alex"),
    dict(Task="Job C", Start='2009-02-23', Finish='2009-05-23', Resource="Max"),
    dict(Task="Job D", Start='2009-02-20', Finish='2009-05-30', Resource="Max")
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Task", opacity=0.5)

fig.show()

And the graph looks like:
enter image description here

Answered By: AS11

I often find that assigning different width to some of the categories helps make the whole thing easier to read. So in your case I would include a column in your df where this is specified, and then edit the figure using:

for i, d in enumerate(fig.data):
    d.width = df[df['Task']==d.name]['width']

Plot:

enter image description here

Complete code with edited data:

import plotly.express as px
import pandas as pd

resource = ['Alex', 'Max']
df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex", width = 0.5),
    dict(Task="Job B", Start='2009-02-25', Finish='2009-04-15', Resource="Alex", width = 0.2),
    dict(Task="Job C", Start='2009-02-23', Finish='2009-05-23', Resource="Max", width = 0.5),
    dict(Task="Job D", Start='2009-02-20', Finish='2009-05-30', Resource="Max", width = 0.2)
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Task")

for i, d in enumerate(fig.data):
    d.width = df[df['Task']==d.name]['width']
fig.show()
Answered By: vestland

You can update layout by this command:

fig.update_layout(barmode='group')

Your traces will be grouped as here

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.