猿问

Plotly:如何给y轴的不同区间添加注解?

我正在尝试根据 y 值的不同 inverval 向 y 轴添加注释


如果 y > 0,我想给出注释Flexion

如果 y < 0,我想给出注释Extension


我尝试使用 multicategory 来指定注释


我的代码如下所示


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()

这将产生

但我不希望线条将FlexisionExtension

并且此方法将在 y 轴上给出详细的 y 值,这也是我不想拥有的

我想知道是否有另一种方法可以根据不同的间隔向 y 轴添加注释?

谢谢 !


守候你守候我
浏览 169回答 1
1回答

守着一只汪

如果除了线条和详细的 y 轴之外,您对上面的设置感到满意,那么您可以放弃多索引方法,只需在适当的位置使用注释fig.add_annotation()下图是用下面的代码片段生成的:使用 , 为左侧的注释留出空间fig.update_layout(margin=dict(l=150)),将区间名称和数据存储在字典中,并且计算每个指定区间的中间值,以及将注释放置在 y 轴的左侧,使用xref="paper", 和不会弄乱 y 轴刻度线的值。阴谋完整代码:import plotly.graph_objects as goimport numpy as np&nbsp;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],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'Extension':[0, -10]}# plotly setupfig = go.Figure( data= go.Scatter(x=x,y=y) )# make room for annotationsfig.update_layout(margin=dict(l=150))for k in intervals.keys():&nbsp; &nbsp; fig.add_annotation(dict(font=dict(color="green",size=14),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #x=x_loc,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x=-0.16,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; y=(intervals[k][0]+intervals[k][1])/2,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; showarrow=False,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text="<i>"+k+"</i>",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; textangle=0,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xref="paper",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yref="y"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;))fig.show()
随时随地看视频慕课网APP

相关分类

Python
我要回答