pythonplotlylinegraph

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?


Solution

  • 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