Hi,
I want to add an annotation on a 2D scatter plot, but I would like this annotation to follow the slope of the curve.
Calculating the slope of the curve on the point and using it in the textangle argument of the annotation doesn’t work as attended.
It works if x and y are almost on the same scale, but if there is a too big difference, the angle isn’t right.
You’ll find below a sample code showing this.
If anyone have an idea , it would be very much appreciated.
Regards,
import plotly.graph_objects as go
import numpy as np
# Sample Data
x = np.linspace(2e-3, 4e-3, 100)
x = x*1.0
y = 100.0 + 50000.0*x
y = y*1.0
text = [f"Point {i}" for i in range(len(x))]
fig = go.Figure()
trace = go.Scatter(x=x, y=y, mode='lines', text=text)
fig.add_trace(trace)
mid_index = len(x) // 2
dy_dx = np.gradient(y, x)[mid_index]
angle = np.degrees(np.arctan(dy_dx))
print(f'angle : {angle}')
fig.add_annotation(
x=x[mid_index],
y=y[mid_index],
text=text[mid_index],
showarrow=False,
bgcolor=fig.layout.template.layout.paper_bgcolor,
borderpad=2,
textangle=-angle,
visible=True,
)
fig.show()