Search code examples
pythonplotlyline

Is there a simple way to give atributes (e.g. color, hover names ) to a time serie with plotly line function


In the following example, with the plotly.express line function, is there a siple way to color the lines according to the row "Continent" ? And to have the countries names as hover names?

Thank you for your answers.

import numpy as np
import plotly.express as px

a=['Afghanistan','Albania','Algeria','Andorra','Angola','Antigua','Argentina','Armenia']
b=np.random.random((100,8))
c=['Asia','Europe','Africa','Europe','Africa','America','America','Asia']

df=pd.DataFrame(columns=a, data=b)
df.loc['Continent'] = c

fig = px.line(df, x=df.index, y=df.columns)
fig.show()

Solution

  • The data in the question is in wide format and needs to be changed to long format. So create an empty data frame and merge the continent name, country name, and value data frames vertically. Then set the color setting in px.line to the continent name. The country name will also be displayed in the hover of this result.

    import numpy as np
    import pandas as pd
    import plotly.express as px
    
    a=['Afghanistan','Albania','Algeria','Andorra','Angola','Antigua','Argentina','Armenia']
    b=np.random.random((100,8))
    c=['Asia','Europe','Africa','Europe','Africa','America','America','Asia']
    
    df=pd.DataFrame(columns=a, data=b)
    df.loc['Continent'] = c
    
    dff = pd.DataFrame()
    for c in df.columns:
        data = pd.DataFrame({'continent':df.loc['Continent':,c][0], 'country':[c]*(len(df)-1), 'value': df.loc[0:(len(df)-2),c]})
        dff = pd.concat([dff, data], axis=0)
    
    fig = px.line(dff, x=dff.index,
                  y='value',
                  color='continent',
                  line_group='country',
                  color_discrete_sequence=px.colors.qualitative.G10)
    fig.show()
    

    enter image description here