Demi
Demi

Reputation: 234

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?

Upvotes: 0

Views: 5313

Answers (2)

Redox
Redox

Reputation: 9967

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

Upvotes: 1

r-beginners
r-beginners

Reputation: 35115

This is my first experience with this graph, but to add it to the legend, you can use the line mode of the scatter plot. So I took the maximum x-axis value used in the first graph and set the legend name Average using the appropriate y-axis value. This example is taken from the official reference.

import plotly.express as px
import plotly.graph_objects as go

df = px.data.tips()
fig = px.ecdf(df, x=["total_bill", "tip"])
xmax = max(fig.data[0]['x'])
#print(xmax)

fig.add_trace(go.Scatter(
    x=[0,xmax],
    y=[0.6,0.6],
    mode='lines',
    line_color='red',
    name='mean',
    showlegend=True
))

fig.show()

enter image description here

Upvotes: 2

Related Questions