2

I want to create a line chart with multiple lines sharing the same x and y axis. Fortunately, newest version of Plotly seems to allow multiple inputs as y. Example: px.line(df,x,[y1,y2]) works fine.

Unfortunately, I want to add text as datapoint annotations and this does not work in the same way.

My goal is to create a lineplot with multiple lines and each datapoint annotated with its y_value in the same color as the corresponding line.

Ty for your help!

0

1 Answer 1

4

Perhaps not the most elegant approach, but the complete snippet below will produce the following figure. Some central parts of the snippets are:

Approach:

for i, d in enumerate(fig.data):
    for j, a in enumerate(d.x):
        fig.add_annotation(x=a, y = d.y[j], text = str(d.y[j])[:5],
                          showarrow = False,
                          yshift = 10,
                          font=dict(color=d.line.color, size=12))

Plot 1:

enter image description here

If you'd like to follow other color cycles for your annotations, just include:

colors = px.colors.qualitative.Alphabet

And replace:

font=dict(color=d.line.color, size=12)

with:

font=dict(color=colors[i], size=12)

And get:

Plot 2:

enter image description here

I'd be happy to go into all the details if this is something you could use.

Complete code:

# imports
import pandas as pd
import plotly.express as px

# data
df = px.data.stocks().tail(10)
df = df.drop(['AMZN', 'AAPL'], axis = 1)

df.set_index('date', inplace = True)
colors = px.colors.qualitative.Alphabet

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

for i, d in enumerate(fig.data):
    for j, a in enumerate(d.x):
        fig.add_annotation(x=a, y = d.y[j], text = str(d.y[j])[:5],
                           showarrow = False,
                           yshift = 10,
                           font=dict(color=d.line.color, size=12)
#                            font=dict(color=colors[i], size=12)
                          )


fig.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.