Search code examples
pythonlinewidthstockplotly-express

Plotly Express set the width of a specific line on graph of multiple lines


I'm trying to make the 'Close' line wider than the others using plotly.express. I tried various options with a conditional statement, or adding a trace but nothing seems to work.

fig.for_each_trace(
lambda trace: trace.update(line=dict(color="Black", width=3)) if trace.name == "Close" else ()

This is the code:

import plotly.express as px
ticker = 'TSLA'
colours = ['steelblue', 'tan', 'black', 'red', 'green']
fig = px.line(df.tail(150), x=df.tail(150).index, y=['middle_band', 'SMA_200', 
'upper_band', 'lower_band','Close'], title=f'{ticker}', 
color_discrete_sequence=colours, width=800, height=600)
fig.update_traces(textfont_size=12, showlegend=True)
fig.update_layout(legend=dict(
yanchor="top",
y=0.9,
xanchor="left",
x=0.02
))
fig.update_xaxes(title_text='Price evolution over time',  title_font = {"size": 16},)
fig.update_yaxes(title_text='Price', tickprefix="$")
fig.show()

which produces this: TESLA price evolution over time

As always, any help is welcome.


Solution

  • You can add this line just before fig.show() to increase the width of the 5th line - fig['data'][4]['line']['width']=5, changing the 4 to any number between 0-4 will increase the width / thickness by 5 (or any number you need). I have used random numbers and plotted your code. Same is below.

    import plotly.express as px
    df = pd.DataFrame(np.random.randint(0,1000,size=(5, 5)), columns=list('ABCDE'))
    ticker = 'TSLA'
    colours = ['steelblue', 'tan', 'black', 'red', 'green']
    fig = px.line(df.tail(5), x=df.tail(5).index, y=['A', 'B', 
    'C', 'D','E'], title=f'{ticker}', 
    color_discrete_sequence=colours, width=800, height=600)
    fig.update_traces(textfont_size=12, showlegend=True)
    fig.update_layout(legend=dict(
    yanchor="top",
    y=0.9,
    xanchor="left",
    x=0.02
    ))
    fig.update_xaxes(title_text='Price evolution over time',  title_font = {"size": 16},)
    fig.update_yaxes(title_text='Price', tickprefix="$")
    #fig.update_traces(line=dict(color="Black", width=0.5))
    fig['data'][4]['line']['width']=5
    fig.show()
    

    Plot

    enter image description here