Search code examples
pythonpandaschartsplotly

Plotly two facet row plots combined


I'm kinda newbie at plotly and i just cant find solution for my problem. How can i combine 2 plotly express plots (in my case timeline and scatter marks only), while both using facet rows with same rule of separation? Hope somebody did it before and knows solution. Using plotly and pandas.

I thought about me using wrong code structure, but i just want to see someone's idea of this, then adaptate mine script to it

import plotly.express as px
import pandas as pd
df=pd.DataFrame([
    dict(team='Wolfs',start='2004-05-23',end='2006-05-24',country='Russia'),
    dict(team='Lions',start='2007-07-05',end='2009-07-06',country='USA'),
    dict(team='Crows',start='2001-08-9',end='2003-08-11',country='USA'),
    dict(team='Elephants',start='2010-02-14',end='2012-02-15',country='China')
    ])  #team, country, date of start of team playing, end of team. Timeline chart
dm=pd.DataFrame([
    dict(date='23.05.2004',team='Wolfs',country='Russia'),
    dict(team='Lions',date='04.07.2007',country='USA'),
    dict(team='Crows',date='09.08.2001',country='USA'),
    dict(team='Elephants',date='14.02.2010',country='China')
    ])  #team, country, time of event and an name of event (for example - losing without scoring a point)
fig = px.timeline(df,x_start='start',x_end='end',y='team',facet_row='country')
fig2 = px.scatter(dm, x='date', y='team', facet_row='country')
fig.add_trace(fig2.data[0],row='all',col='all')
fig.show()

Solution

  • The reason the two graphs could not be merged successfully was that the date column of the second data frame was not treated as a time series. Also, the graph being added, fig2.data[0], specifies only Russia. fig2 consists of three scatter plots, so three additions are needed. The only adjustment regarding the graphs is the addition of color='country' so that the markers on the scatterplots are color coded. The faceted labels overlap, so we are increasing the spacing and the overall graph.

    dm['date'] = pd.to_datetime(dm['date'], format='%d.%m.%Y')
    
    fig = px.timeline(df,x_start='start',x_end='end',y='team',facet_row='country',facet_row_spacing=0.1)
    fig2 = px.scatter(dm, x='date', y='team', color='country',facet_row='country')
    
    fig.add_trace(fig2.data[0],row=3,col=1)
    fig.add_trace(fig2.data[1],row=2,col=1)
    fig.add_trace(fig2.data[2],row=1,col=1)
    
    fig.update_layout(height=400)
    fig.show()
    

    enter image description here