【问题标题】:Add text for different part of line chart plot in plotly python在plotly python中为折线图的不同部分添加文本
【发布时间】:2021-10-02 23:11:21
【问题描述】:

我使用 plotly (python) 绘制了一个图形,如下所示。

现在我的目标是以相同颜色显示所有点,但为该图中的每个彩色部分添加不同的文本。例如,对于蓝色部分,我想添加文本 AAA 和红色部分 BBB。如何在情节中做到这一点?

【问题讨论】:

    标签: charts plotly plotly-python


    【解决方案1】:
    • 我有模拟数据,其特征将生成与您展示的图表相似的图表
    • 有三种添加标签的方法
      1. 图例中的痕迹标签
      2. 作为带有mode="text" 的附加散点图
      3. 作为图中的注释

    所有这三个都在下面演示。它确实假设您具有 pandas

    的工作知识
    import plotly.express as px
    import plotly.graph_objects as go
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({"AAA":np.concatenate([np.random.uniform(1,5,20), np.full(20,np.nan)]), 
                  "BBB":np.concatenate([np.full(20,np.nan), np.random.uniform(1,5,20), ])})
    
    # create two traces, where traces are in legend to label AAA & BBB
    fig = px.scatter(df, x=df.index, y=["AAA","BBB"]).update_traces(mode="lines+markers")
    
    # additionally create text trace, that are last AAA & BBB
    lastAAA = df.loc[~df["AAA"].isna()].iloc[-1]
    lastBBB = df.loc[~df["BBB"].isna()].iloc[-1]
    fig.add_trace(go.Scatter(x=[lastAAA.name], y=[lastAAA["AAA"]], text="AAA", mode="text", showlegend=False))
    fig.add_trace(go.Scatter(x=[lastBBB.name], y=[lastBBB["BBB"]], text="BBB", mode="text", showlegend=False))
    
    # additionally add annotations
    fig.add_annotation(x=lastAAA.name, y=lastAAA["AAA"], text="AAA")
    fig.add_annotation(x=lastBBB.name, y=lastBBB["BBB"], text="BBB")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2015-11-13
      • 2019-08-27
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多