如何从数据帧的两列绘制两条线图,并且另一列表示 x 轴,另外两列表示前两列的悬停值(工具提示)?
最佳答案
使用go.Scatter
,您可以将任何数据帧列y=df['A']
显示为具有关联索引x=df.index的行
,并使用 hovertext=df['A_info']
将任何 pandas 数据框列指定为悬停信息的源来获取:
完整代码:
import pandas as pd
import plotly.graph_objects as go
# sample data
d={'A':[3,3,2,1,5],
'B':[4,4,1,4,7],
'A_info':['nothing', '', '', 'bad', 'good'],
'B_info':['', '', 'bad', 'better', 'best']}
# pandas dataframe
df=pd.DataFrame(d, index=[10,11,12,13,14])
# set up plotly figure
fig = go.Figure()
# add line / trace 1 to figure
fig.add_trace(go.Scatter(
x=df.index,
y=df['A'],
hovertext=df['A_info'],
hoverinfo="text",
marker=dict(
color="blue"
),
showlegend=False
))
# add line / trace 2 to figure
fig.add_trace(go.Scatter(
x=df.index,
y=df['B'],
hovertext=df['B_info'],
hoverinfo="text",
marker=dict(
color="green"
),
showlegend=False
))
fig.show()
关于python - Plotly:如何从两个数据框列中绘制两条线并从其他两列中分配悬停信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60372991/