gpt4 book ai didi

python - 如何注释 plotly 本身之外的一个点?

转载 作者:行者123 更新时间:2023-12-04 00:01:19 24 4
gpt4 key购买 nike

我有一个这样的 plotly ,想在文本“今天”的行上方添加文本。

enter image description here

我正在尝试使用注释

annots.append(dict(x='2020-03-29',y=len(df)+1,text='<b>Today<b>', showarrow=False, font=dict(color='black')))

但输出是这样的,我希望它在 plotly 之上,而不是改变 plotly 的结构!
enter image description here

最佳答案

您可以分三步进行:

  • 使用 fig.update_layout(margin=dict()) 调整边距为文本腾出空间
  • 添加行使用 fig.add_shape()
  • 使用 add_annotation(yref='paper', y=1.06) 在绘图外添加文本例如y > 1将注释放在绘图本身之上。

  • 有关详细信息,请参阅代码片段

    剧情:

    enter image description here

    完整代码:
    # imports
    from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
    from IPython.core.display import display, HTML
    import plotly.figure_factory as ff
    import plotly.graph_objs as go

    # setup
    display(HTML("<style>.container { width:50% !important; } .widget-select > select {background-color: gainsboro;}</style>"))
    init_notebook_mode(connected=True)

    #%qtconsole --style vim

    # dates
    StartA = '2009-01-01'
    StartB = '2009-03-05'
    StartC = '2009-02-20'

    FinishA='2009-02-28'
    FinishB='2009-04-15'
    FinishC='2009-05-30'

    LabelDateA='2009-01-25'
    LabelDateB='2009-03-20'
    LabelDateC='2009-04-01'

    # sample data
    df = [dict(Task="Task A", Start=StartA, Finish=FinishA),
    dict(Task="Task B", Start=StartB, Finish=FinishB),
    dict(Task="Task C", Start=StartC, Finish=FinishC)]

    # figure
    fig = ff.create_gantt(df)

    # add annotations
    annots = [dict(x=LabelDateA,y=0,text="Task label A", showarrow=False, font=dict(color='white')),
    dict(x=LabelDateB,y=1,text="Task label B", showarrow=False, font=dict(color='White')),
    dict(x=LabelDateC,y=2,text="Task label C", showarrow=False, font=dict(color='White'))]

    # plot figure
    fig['layout']['annotations'] = annots


    # Step 1 - adjust margins to make room for the text
    fig.update_layout(margin=dict(t=150))

    # Step 2 - add line
    fig.add_shape(type='line',
    x0=LabelDateB,
    y0=0,
    x1=LabelDateB,
    y1=1,
    line=dict(color='black', dash='dot'),
    xref='x',
    yref='paper'
    )

    # Step 3 - add text with xref set to x
    # and yref set to 'paper' which will let you set
    # text outside the plot itself by specifying y > 1
    fig.add_annotation(dict(font=dict(color="black",size=12),
    #x=x_loc,
    x=LabelDateB,
    y=1.06,
    showarrow=False,
    text='<b>Today</b>',
    textangle=0,
    xref="x",
    yref="paper"
    ))

    fig.update_layout(
    title_text="Academic year 2019/2020"
    )

    fig.show()

    关于python - 如何注释 plotly 本身之外的一个点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60913366/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com