简体   繁体   English

Plotly:如何为 y 轴的不同区间添加注释?

[英]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我正在尝试根据 y 值的不同反转向 y 轴添加注释

if y > 0, I want to give the annotation of Flexion如果 y > 0,我要给出Flexion的注解
if y < 0, I want to give the annotation of Extension如果 y < 0,我要给出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这将产生

像这样的图表

but I don't want the lines to seperate the Flexision and Extension但我不希望线条将FlexisionExtension分开

and this method will give detailed y values on the y axis, which is also I don't want to have这种方法会在 y 轴上给出详细的 y 值,这也是我不想拥有的

I'm wondering if there's another way to add annotation to y axis based on different interval?我想知道是否有另一种方法可以根据不同的间隔向 y 轴添加注释?

Thanks !谢谢 !

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()如果除了线条和详细的 y 轴之外,您对上面的设置感到满意,那么您可以放弃多索引方法,只需使用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)) ,使用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使用xref="paper"将注释放置在 y 轴的左侧,并且
  5. does not mess up the values of the y-axis tickmarks.不会弄乱 y 轴刻度线的值。

Plot Plot

在此处输入图像描述

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM