在 Plotly 趋势线中处理 np.nan

Handling np.nan in Plotly trendline

我正在尝试在 Plotly 中重新创建这个 Seaborn 情节:seaborn plot。

我的数据框有 np.nan 个值,而在 Plotly 中,趋势线变得古怪:plotly plot。 例如,红色散点图显示了后来出现在电视节目中的角色的情绪(因此,对于前几集,数据框中的值为 np.nan)。如果您只看红色趋势线,您会发现它与红色散点图不一致。

如果我取出 np.nan 值,那么问题就会消失,但这不是我想要做的,因为我希望情绪与 x 轴上的每一集保持一致。

我该如何解决这个问题?这是我的代码:

 import plotly.express as px
 fig = px.scatter(df, x='episode', y='sentiment', color='character', trendline="lowess")
 fig.show()

编辑:

我在 Plotly 论坛上得到了一个解决方案:

# Correct position of x points
for scatter, trendline in zip(fig.data[::2], fig.data[1::2]):
    trendline['x'] = scatter['x'][np.logical_not(np.isnan(scatter['y']))]
fig.show()

这应该会在 plotly.py 的下一版本中修复。

解决方法:

import plotly.express as px
fig = px.scatter(newdf, x='episode', y='sentiment', color='character', trendline="lowess")

# Correct position of x points
for scatter, trendline in zip(fig.data[::2], fig.data[1::2]):
    trendline['x'] = scatter['x'][np.logical_not(np.isnan(scatter['y']))]
fig.show()

这应该会在 plotly.py 的下一版本中修复。

您可以将此添加到 'fig' 元素:

fig.update_traces(connectgaps=True)

对我有用。