Plotly:如何从两个数据框列中绘制两条线并从其他两列中分配悬停信息?

Jeb*_*ose 8 python timeserieschart plotly

如何从数据帧的两列绘制两条线图,并且另一列表示 x 轴,另外两列表示前两列的悬停值(工具提示)?

ves*_*and 7

使用go.Scatter您可以将任何数据框列显示y=df['A']为具有关联索引的行x=df.index,并将任何pandas数据框列指定为hoverinfo的源,使用hovertext=df['A_info']以下方法来获取:

在此输入图像描述

完整代码:

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()
Run Code Online (Sandbox Code Playgroud)


Ind*_*ema 7

这是将多条线添加到单个图中的更简单的方法。使用该add_scatter函数可以向图中添加任意多条线。

import plotly.express as px
    
fig = px.line(df, x="<col_name>", y="<line1_col>", title='<Plot_Title>')
fig.add_scatter(x=df['<col_name>'], y=df['<line2_col>'], mode='lines', hovertext=df['<hover_col>'], hoverinfo="text",)
fig.show()
Run Code Online (Sandbox Code Playgroud)