【问题标题】:Add multiple text labels from DataFrame columns in Plotly在 Plotly 中从 DataFrame 列添加多个文本标签
【发布时间】:2019-01-25 15:20:51
【问题描述】:

目标是使用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')

【问题讨论】:

  • 根据文档,文本需要为(string or array of strings),所以我猜你被困在这里。优化列表理解似乎是唯一的选择。
  • @MaximilianPeters 感谢您提供这些信息。我刚刚阅读了documentation,发现了一些有趣的东西......正如你提到的,它可以是array of strings;然而,df['Mean Age]series 或者更确切地说是ndarraynumpy.int32,尽管它是array of int32,但它仍然有效。无论如何,我想我可以做类似list(map(str, zip(df['Mean Age'], df['Number Column']))) 的事情,这应该比列表理解更快。
  • 在很多情况下,任何可迭代对象都可以与 Plotly 一起使用,而不是数组。为了从 Python 获取信息到 Plotly 的 JS 库,无论如何,一切都将被序列化为 JSON。

标签: python python-3.x pandas plotly


【解决方案1】:

您还可以按照以下方式进行操作:

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)
)

【讨论】:

    猜你喜欢
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多