【问题标题】:Plotly: how to write a text over my Sankey diagram columns?Plotly:如何在我的桑基图列上写一个文本?
【发布时间】:2021-08-05 00:25:25
【问题描述】:

我已经建立了一个Sankey diagram using plotly。我想给列命名,给每个列一个列标题,如下面的红色文本:

如何编写这些列标题?

【问题讨论】:

    标签: plotly plotly-python sankey-diagram


    【解决方案1】:

    您可以使用注释来添加文本,使用 0, 1, 2 的 x 值并将 xref 设置为 "x",并使用 1.05 的 y 值将 yref 设置为 "paper"在纸坐标中。这将确保注释位于图上方。

    import plotly.graph_objects as go
    
    fig = go.Figure(data=[go.Sankey(
        node = dict(
          pad = 15,
          thickness = 20,
          line = dict(color = "black", width = 0.5),
          label = ["A1", "A2", "B1", "B2", "C1", "C2"],
          color = "blue"
        ),
        link = dict(
          source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ...
          target = [2, 3, 3, 4, 4, 5],
          value = [8, 4, 2, 8, 4, 2]
      ))])
    
    layout={
          
         }
    
    for x_coordinate, column_name in enumerate(["column 1","column 2","column 3"]):
      fig.add_annotation(
              x=x_coordinate,
              y=1.05,
              xref="x",
              yref="paper",
              text=column_name,
              showarrow=False,
              font=dict(
                  family="Courier New, monospace",
                  size=16,
                  color="tomato"
                  ),
              align="center",
              )
    
    fig.update_layout(
      title_text="Basic Sankey Diagram", 
      xaxis={
      'showgrid': False, # thin lines in the background
      'zeroline': False, # thick line at x=0
      'visible': False,  # numbers below
      },
      yaxis={
      'showgrid': False, # thin lines in the background
      'zeroline': False, # thick line at x=0
      'visible': False,  # numbers below
      }, plot_bgcolor='rgba(0,0,0,0)', font_size=10)
    
    fig.show()
    

    【讨论】:

    • 不错!代码完美地编写了列,但它在图中生成了一个网格和轴。
    • 我解决了将这个添加到我的图中的问题:layout={ 'xaxis': { 'showgrid': False, # thin lines in the background 'zeroline': False, # thick line at x=0 'visible': False, # numbers below }, 'yaxis': { 'showgrid': False, # thin lines in the background 'zeroline': False, # thick line at x=0 'visible': False, # numbers below }, 'plot_bgcolor':'rgba(0,0,0,0)', }
    • 啊,我明白了 - 如果在注释中引用 x 坐标,则默认情况下会生成网格和轴,但修改布局是一个明智的解决方案。我很高兴我的回答很有帮助!
    • 我已将布局配置包含在您的答案中以使其更好。
    猜你喜欢
    • 2022-10-18
    • 2020-07-23
    • 2018-11-02
    • 2021-12-23
    • 2022-01-14
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多