Search code examples
pythonplotlyvisualization

Plotly: legend is not visible


Here is CDF visualization I have:

fig_cdf = px.ecdf(df['Timespan'], color_discrete_sequence=['blue'],ecdfnorm='probability', orientation='h')
fig_cdf.add_hline(y=90, line_width=2, line_color="red", name='90%', visible=True)
fig_cdf.add_hline(y=30, line_width=2, line_color="red", name='75%', visible=True)
fig_cdf.update_layout(width=500, height=500)

enter image description here

The problem here is that i want horizontal lines' names to be visible and appear as 2nd and 3rd legends. For this, I tried to add visible=True. However, it seems not to work. What's wrong?


Solution

  • This is one way of doing it...

    • Add the two lines to the dataframe as new columns
    • Use color_discrete_sequence to identify the colors you want I am using some random dummy data, which you can replace with your data
    import plotly.express as px
    df = pd.DataFrame({'firstline': random.sample(range(1, 500), 20),'myX' : range(20)}) #My dummy data
    
    #Add the two lines to dataframe
    df['90%'] = [90] * 20
    df['75%'] = [75] * 20
    
    fig = px.line(df, 
            y = ['firstline', '90%', '75%'], x= 'myX', color_discrete_sequence=["blue", "red", "red"])
    fig.update_layout(legend_title_text='Legend Heading') #Update Legend header if you dont like 'variable'
    fig.show()
    

    Output graph enter image description here