Skip to content

Instantly share code, notes, and snippets.

@eliasdabbas
Last active November 6, 2024 12:25
Show Gist options
  • Save eliasdabbas/f05642752c859dda2c7e8c4b92bcf8f4 to your computer and use it in GitHub Desktop.
Save eliasdabbas/f05642752c859dda2c7e8c4b92bcf8f4 to your computer and use it in GitHub Desktop.
Direct labeling with plotly.express
import plotly.express as px
fig = px.line(
stocks,
x='date',
template='plotly_white',
y=stocks.columns[1:],
color_discrete_sequence=cat_scale,
labels={'y': 'stock price'},
height=600,)
# This for-loop creates the labels
for i, stock in enumerate(stocks.columns[1:]):
fig.add_scatter(
x=[stocks['date'].iloc[-1]],
y=[stocks[stock].iloc[-1]],
name=stock,
mode='text+markers',
text=stock,
textposition='middle right',
marker= {'color': fig.data[i].line.color, 'size': 12},
textfont={'color': fig.data[i].line.color, 'weight': 'bold'})
fig.layout.showlegend = False
fig.layout.title = '<b>AFTER</b>'
fig.layout.title.subtitle.text = 'Direct labeling (no legend) - easier to visually relate colors to lines'
fig
@eliasdabbas
Copy link
Author

Screenshot 2024-11-06 at 3 21 03 PM Screenshot 2024-11-06 at 3 22 01 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment