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')
所以这里的具体问题是:如何将客户量添加到这个绘图工具提示的文本中?
最佳答案
好的,我想我有你想要的。我必须将 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/