代码之家  ›  专栏  ›  技术社区  ›  It_is_Chris

从Plotly中的DataFrame列添加多个文本标签

  •  2
  • It_is_Chris  · 技术社区  · 7 年前

    目标是使用 plotly 其中文本参数包含多个列。

    这是我的数据框架:

    import pandas as pd
    import numpy as np
    import plotly as py
    import plotly.graph_objs as go
    
    np.random.seed(1)
    df = pd.DataFrame({'Mean Age': np.random.randint(40,60,10),
                       'Percent': np.random.randint(20,80,10),
                       'Number Column': np.random.randint(100,500,10)},
                      index=list('ABCDEFGHIJ'))
    
    df.index.name = 'Text Column'
    df = df.sort_values('Mean Age')
    

    下面是我如何用一列中的文本绘制数据以在悬停时显示的示例:

    # trace for Percent
    trace0 = go.Scatter(
        x = df.index,
        y = df['Percent'],
        name = 'Percent',
        text = df['Mean Age'], # text to show on hover from df column
        mode = 'lines+markers',
        line = dict(
            color = ('rgb(0,0,255)'), # blue
            width = 4)
    )
    
    layout = dict(title = 'Test Plot',
                 xaxis = dict(title = 'Text Column'),
                 yaxis = dict(title = 'Percent'),
                  )
    
    data = [trace0]
    fig = dict(data=data, layout=layout)
    
    py.offline.plot(fig, filename = 'Test_Plot.html')
    

    我正在寻找一个类似于以下内容的输出,但比使用列表理解更有效:

    # column values to list
    num = list(df['Number Column'])
    age = list(df['Mean Age'])
    
    
    # trace for Percent
    trace0 = go.Scatter(
        x = df.index,
        y = df['Percent'],
        name = 'Percent',
        # list comprehension to get the data to show
        text = [f'Number Column: {x}; Mean Age: {y}' for x,y in list(zip(num, age))],
        mode = 'lines+markers',
        line = dict(
            color = ('rgb(0,0,255)'), # blue
            width = 4)
    )
    
    layout = dict(title = 'Test Plot',
                 xaxis = dict(title = 'Text Column'),
                 yaxis = dict(title = 'Percent'),
                  )
    
    data = [trace0]
    fig = dict(data=data, layout=layout)
    
    py.offline.plot(fig, filename = 'Test_Plot_Output.html')
    
    0 回复  |  直到 7 年前
        1
  •  3
  •   Caleb Courtney    5 年前

    你也可以做以下几点:

    trace0 = go.Scatter(
        x = df.index,
        y = df['Percent'],
        name = 'Percent',
        # string concatenation in pandas
        # also the <br> puts the data on a new line in the hover text
        text = "Number Column: " + df["Number Column"].astype(str) + "<br>Mean Age: " + df["Mean Age"].astype(str),
        mode = 'lines+markers',
        line = dict(
            color = ('rgb(0,0,255)'),  # blue
            width = 4)
    )