【问题标题】:Plotly: Annotate marker at the last value in line chartPlotly:在折线图中的最后一个值处注释标记
【发布时间】:2021-02-13 10:57:13
【问题描述】:

我正在尝试在 plotly express python 中用一个大红点标记折线图的最后一个值,有人可以帮我吗?

我成功构建了折线图,但无法注释点。

下面是我的数据框,我希望对数据框中的最后一个值进行注释。

下面是创建的折线图,我希望我的图表与屏幕截图中的第二张图片相似

我正在使用的代码:

fig = px.line(gapdf, x='gap', y='clusterCount', text="clusterCount")
fig.show()

【问题讨论】:

    标签: python annotations plotly linechart plotly-python


    【解决方案1】:

    您可以使用plotly.graph_objects 覆盖最后一个数据点的附加跟踪:

    import pandas as pd
    import plotly.express as px
    import plotly.graph_objects as go
    
    gapdf = pd.DataFrame({
        'clusterCount': [1, 2, 3, 4, 5, 6, 7, 8],
        'gap': [-15.789, -14.489, -13.735, -13.212, -12.805, -12.475, -12.202, -11.965]
    })
    
    fig = px.line(gapdf, x='gap', y='clusterCount')
    
    fig.add_trace(go.Scatter(x=[gapdf['gap'].iloc[-1]],
                             y=[gapdf['clusterCount'].iloc[-1]],
                             text=[gapdf['clusterCount'].iloc[-1]],
                             mode='markers+text',
                             marker=dict(color='red', size=10),
                             textfont=dict(color='green', size=20),
                             textposition='top right',
                             showlegend=False))
    
    fig.update_layout(plot_bgcolor='white',
                      xaxis=dict(linecolor='gray', mirror=True),
                      yaxis=dict(linecolor='gray', mirror=True))
    
    fig.show()
    

    【讨论】:

      【解决方案2】:

      gflavia 的建议非常有效。 但是您也可以通过直接寻址图中的元素而不是像这样的数据源来设置额外的跟踪和关联文本:

      fig.add_scatter(x = [fig.data[0].x[-1]], y = [fig.data[0].y[-1]])
      

      情节 1

      完整代码:

      import pandas as pd
      import plotly.express as px
      import plotly.graph_objects as go
      
      gapdf = pd.DataFrame({
          'clusterCount': [1, 2, 3, 4, 5, 6, 7, 8],
          'gap': [-15.789, -14.489, -13.735, -13.212, -12.805, -12.475, -12.202, -11.965]
      })
      
      fig = px.line(gapdf, x='gap', y='clusterCount')
      
      fig.add_scatter(x = [fig.data[0].x[-1]], y = [fig.data[0].y[-1]],
                           mode = 'markers + text',
                           marker = {'color':'red', 'size':14},
                           showlegend = False,
                           text = [fig.data[0].y[-1]],
                           textposition='middle right')
      
      fig.show()
      

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 1970-01-01
        • 2019-08-27
        • 2020-03-18
        • 2020-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多