goose
goose

Reputation: 2642

How to add data labels to plotly line graph?

I've got a simple plotly line graph:

import plotly.express as px
fig = px.line(data, x="x-axis", y="variable")
fig.show()

plotly line graph

I want to add data labels displaying each y-axis value to each point, but I can't work out how to do it using the plotly api. Is it possible? Can anyone point out how?

Upvotes: 1

Views: 9738

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31146

  • have simulated dataframe for your figure
  • two steps
    1. define text parameter so trace / figure is built appropriately by Plotly Express
    2. updated texttemplate so that formatting of y-axis is used
import plotly.express as px
import pandas as pd
import numpy as np

data = pd.DataFrame(
    {
        "x-axis": np.arange(0, 12),
        "variable": (np.cos(np.linspace(np.pi / 2, np.pi, 12)) + 1) / 25,
    }
)

fig = px.line(data, x="x-axis", y="variable", text="variable")
fig.update_traces(texttemplate="%{y}")
fig.update_layout(yaxis_tickformat=".2%")

enter image description here

Upvotes: 4

Related Questions