whtitefall
whtitefall

Reputation: 671

Plotly: How to add annotations to different intervals of the y-axis?

I'm trying to add annoation to y axis based on different inverval of y value

if y > 0, I want to give the annotation of Flexion
if y < 0, I want to give the annotation of Extension

I tried to use multicategory to specify the annotation

my code is show below

import plotly.graph_objects as go
import numpy as np 


x = np.arange(-10,10,1)
y = np.arange(-10,10,1)

y_annotation = [ 'Flexion' if data > 0 else 'Extension' for data in y ]

fig = go.Figure( data= go.Scatter(x=x,y=[y_annotation,y]) )

fig.show()

This will produce

a graph like this

but I don't want the lines to seperate the Flexision and Extension

and this method will give detailed y values on the y axis, which is also I don't want to have

I'm wondering if there's another way to add annotation to y axis based on different interval?

Thanks !

Upvotes: 4

Views: 2170

Answers (1)

vestland
vestland

Reputation: 61094

If you're happy with the setup above besides the lines and detailed y-axis, then you can drop the multi index approach and just set up annotations at the appropriate positions using fig.add_annotation()

The following figure is produced with the snippet below that:

  1. makes room for your annotations on the left side using fig.update_layout(margin=dict(l=150)),
  2. stores interval names and data in a dict, and
  3. calculates the middle values of each specified interval, and
  4. places the annotations to the left of the y-axis using xref="paper", and
  5. does not mess up the values of the y-axis tickmarks.

Plot

enter image description here

Complete code:

import plotly.graph_objects as go
import numpy as np 


x = np.arange(-10,10,1)
y = np.arange(-10,10,1)

y_annotation = [ 'Flexion' if data > 0 else 'Extension' for data in y ]

intervals = {'Flexion':[0,10],
             'Extension':[0, -10]}


# plotly setup
fig = go.Figure( data= go.Scatter(x=x,y=y) )

# make room for annotations
fig.update_layout(margin=dict(l=150))

for k in intervals.keys():
    fig.add_annotation(dict(font=dict(color="green",size=14),
                            #x=x_loc,
                            x=-0.16,
                            y=(intervals[k][0]+intervals[k][1])/2,
                            showarrow=False,
                            text="<i>"+k+"</i>",
                            textangle=0,
                            xref="paper",
                            yref="y"
                           ))


fig.show()

Upvotes: 4

Related Questions