python - Pandas 和 Plotly : how to access data columns in the hover text that are not used to plot the point?

标签 python pandas data-visualization plotly-python

Plotly 的文档显示一个 hovertemplate可以访问文本中的 x 和 y 值,但我们如何访问其他列中的数据?

导入:

import pandas as pd  
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot

代码:

test_data = {"client1-percent":[90,100,60]
             , "client1-volume":[500000,3542,20000]
             , "client2-percent":[99,63,98]
             ,"client2-volume":[6423,6524,5737]
            }
df = pd.DataFrame(test_data)

data = [go.Scatter(
    x = df.index.values
    , y = df.loc[:,col].values
    , hovertemplate = "Percent: %{y:.1f}% | Volume: {}"
    , mode = 'lines+markers'
    , name = col.replace("-percent","")
) for col in df.columns if "-volume" not in col]

plot(data, filename='test.html')

enter image description here

所以这里的具体问题是:如何将客户量添加到这个绘图工具提示的文本中?

最佳答案

好的,我想我有你想要的。我必须将 client3-volume 的名称更改为 client2-volume 以便我可以通过列表理解中的一些逻辑来获取它。我在Scatter对象中创建了一个文本对象,通过hoverinfo将y和文本都传递到hovertemplate中。如果您有更聪明的方法从您的 df 中获取与客户百分比列关联的音量列,您可以将 text = ... 更改为任何将向其发送所需数据的内容。

test_data = {"client1-percent":[90,100,60]
             , "client1-volume":[500000,3542,20000]
             , "client2-percent":[99,63,98]
             ,"client2-volume":[6423,6524,5737]
            }

df = pd.DataFrame(test_data)

data = [go.Scatter(
    x = df.index.values
    , y = df.loc[:,col].values
    , text = df[col.replace('-percent','-volume')].values
    , hoverinfo = 'y+text'
    , hovertemplate = "Percent: %{y:.1f}% | Volume: %{text}"
    , mode = 'lines+markers'
    , name = col.replace("-percent","")
) for col in df.columns if "-volume" not in col]

plot(data, filename='test.html')

关于python - Pandas 和 Plotly : how to access data columns in the hover text that are not used to plot the point?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713856/

相关文章:

r - 使用线条和多因子连接 ggplot 箱线图

python - 仅具有高亮值的 matplotlib 条形图

python - 如何循环多个 DataFrame 并生成多个 csv?

Python循环函数根据多列的Groupby创建新列

python - 在Python中将一列spark数据帧转换为由管道字符分隔的单个字符串

python - Pandas 在交叉值中找到重复项

python - 用于科学 Web 应用程序的谷歌云平台架构

javascript - D3 : Are "parabolic" scales possible?

python - 将文本文档转换为 jsonl(json 行)格式

python - 尝试上传已散列到AWS S3存储桶的文件名