在 Plotly 中绘制数据框中的特定单元格

Plot specific cells from a dataframe in Ploty

我有一个 XY 坐标数据框,我将其绘制为散点图中的标记。我想 add_trace 特定 XY 对之间的线,而不是每对之间的线。例如,我想要索引 0 和索引 3 之间的一条线,以及索引 1 和索引 2 之间的另一条线。这意味着仅使用线图是行不通的,因为我不想显示所有连接。是否可以使用 iloc 的版本来做到这一点,或者我是否需要在 'Wide-format' 中制作我的 DataFrame 并将每个 XY 对作为单独的列对? 我已经通读了这个,但我不确定它对我的情况有帮助。

import pandas as pd
import plotly.graph_objects as go

# sample data
d={'MeanE': {0: 22.448461538460553, 1: 34.78435897435799, 2: 25.94307692307667, 3: 51.688974358974164},
   'MeanN': {0: 110.71128205129256, 1: 107.71666666666428, 2: 140.6384615384711, 3: 134.58615384616363}}

# pandas dataframe
df=pd.DataFrame(d)

# set up plotly figure
fig = go.Figure()

fig.add_trace(go.Scatter(x=df['MeanE'],y=df['MeanN'],mode='markers')) 
       
fig.show()

更新: 将下面接受的答案添加到我已有的答案中,我现在得到以下完成的情节。

  • 采用更新数据框行的方法,这些行是您定义的坐标对
  • 然后将轨迹添加到图中以完成要求,作为列表理解
import pandas as pd
import plotly.graph_objects as go

# sample data
d={'MeanE': {0: 22.448461538460553, 1: 34.78435897435799, 2: 25.94307692307667, 3: 51.688974358974164},
   'MeanN': {0: 110.71128205129256, 1: 107.71666666666428, 2: 140.6384615384711, 3: 134.58615384616363}}

# pandas dataframe
df=pd.DataFrame(d)

# set up plotly figure
fig = go.Figure()

fig.add_trace(go.Scatter(x=df['MeanE'],y=df['MeanN'],mode='markers')) 

# mark of pairs that will be lines
df.loc[[0, 3], "group"] = 1
df.loc[[1, 2], "group"] = 2
# add the lines to the figure
fig.add_traces(
    [
        go.Scatter(
            x=df.loc[df["group"].eq(g), "MeanE"],
            y=df.loc[df["group"].eq(g), "MeanN"],
            mode="lines",
        )
        for g in df["group"].unique()
    ]
)

fig.show()

评论中增强要求的替代解决方案

# mark of pairs that will be lines
lines = [[0, 3], [1, 2], [0,2],[1,3]]
# add the lines to the figure
fig.add_traces(
    [
        go.Scatter(
            x=df.loc[pair, "MeanE"],
            y=df.loc[pair, "MeanN"],
            mode="lines",
        )
        for pair in lines
    ]
)