Skip to content
Advertisement

Plotly, mixed px.timeline chart with go.Figure to generate one visual and html file

I hope to create a visual (subplots) with a px.timeline chart and go.Table, basically put the two figures on the same page and generate a html file. Here is the sample data & unfinished code:

from plotly.subplots import make_subplots
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go


df = pd.DataFrame({'Task': ['a1', 'a2', 'a3', 'a4', 'a5', 'a6'],
                   'Source': ['abc', 'completed', 'cancelled', 'deg', 'pki', 'API'],
                   'Start': ['2021-01-01', '2021-02-12', '2021-03-15', '2021-08-09', '2021-09-20', '2021-12-15'],
                   'Finish': ['2021-03-12', '2021-04-25', '2021-05-20', '2021-10-01', '2021-12-30', '2022-03-01']})

fig1 = px.timeline(df, x_start='Start', x_end='Finish')
 
fig2 = go.Figure(data=[go.Table(
    header=dict(
        values=['Task', 'Source', 'Start', 'Finish'],
        line_color='white', fill_color='white'
    ),
    cells=dict(
        values=[df['Task'], df['Source'], df['Start'], df['Finish']],
        align='center'
    )
)])

Unfortunately right now I only can generate the two charts separately, could you help put the two on the same subplot please?

many thanks

Advertisement

Answer

Create a subplot using only the timeline data; the second sets the table graph. Finally, change the first x-axis to a date type.

from plotly.subplots import make_subplots
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go


df = pd.DataFrame({'Task': ['a1', 'a2', 'a3', 'a4', 'a5', 'a6'],
                   'Source': ['abc', 'completed', 'cancelled', 'deg', 'pki', 'API'],
                   'Start': ['2021-01-01', '2021-02-12', '2021-03-15', '2021-08-09', '2021-09-20', '2021-12-15'],
                   'Finish': ['2021-03-12', '2021-04-25', '2021-05-20', '2021-10-01', '2021-12-30', '2022-03-01']})

fig = make_subplots(rows=2, cols=1,
                   specs=[[{'type': 'bar'}],
                          [{'type': 'table'}]],
                    subplot_titles=('Time lines', 'Table'),
                    row_heights=[0.55, 0.45],
                    vertical_spacing=0.1)

fig1 = px.timeline(df, x_start='Start', x_end='Finish', y='Task')

fig.add_trace(go.Bar(fig1.data[0]), row=1,col=1)
 
fig.add_trace(go.Table(
    header=dict(
        values=['Task', 'Source', 'Start', 'Finish'],
        line_color='white', fill_color='white'
    ),
    cells=dict(
        values=[df['Task'], df['Source'], df['Start'], df['Finish']],
        align='center'
    )
), row=2, col=1)

fig.update_layout(autosize=True,
                  height=600
                 )
fig.update_xaxes(type='date')

enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement