首页 > 解决方案 > Plotly:当 (n) 个点被绘制时,标记消失

问题描述

好的,所以我最初的想法是绘制一个线图,并在某个阈值 t 之后用一种颜色为线着色,在阈值之前用另一种颜色着色。它适用于 23 或更少的点,但它不再适用,使用以下方法:

import numpy as np
import plotly.graph_objects as go

X = [j for j in range(0, 100)]
Y = [j for j in range(100000, 200000, 1000)]
X = X[:23]
Y = Y[:23]
X = np.array(X)
Y = np.array(Y)
t = 4

x = X[X <= t]  # Include the threshold
y = Y[X <= t]
bx = X[X >= t]
by = Y[X >= t]

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, line=dict(width=4, color='grey'), name="useless data"))
fig.add_trace(go.Scatter(x=bx, y=by, line=dict(width=4, color='blue'), name="useful data"))
fig.update_layout(xaxis_title="x axis", yaxis_title="y axis")
fig.show()

所以这正常工作,如果你运行它,你会看到 4 包含在蓝点中。但是现在,请删除仅取 23 个值的行 ( X = X[:23], Y = Y[:23])。你会看到 4 不再是蓝点的一部分,而且点本身从图中蓝线消失了,你可以悬停查看数据,但看不到实际的点!如果有人知道为什么会发生这种情况,它是一个实际的错误还是它是正常行为并且我缺少一些东西?先感谢您!

标签: pythonpython-3.xplotplotlyplotly-python

解决方案


The reason:

This is a 'feature' of Plotly Scatter plots. When (a number) of points are plotted, the underlying Plotly logic converts the 'scatter' plot to a 'line' plot, for rendering efficiency and plot cleanliness. Thus, the markers are converted to a solid line.

The fix:

Simply add mode='lines+markers' to the trace.

Full working example:

This is your source code, with the minor fix mentioned above:

import numpy as np
import plotly.graph_objects as go

X = [j for j in range(0, 100)]
Y = [j for j in range(100000, 200000, 1000)]
#X = X[:23]
#Y = Y[:23]
X = np.array(X)
Y = np.array(Y)
t = 4

x = X[X <= t]  # Include the threshold
y = Y[X <= t]
bx = X[X >= t]
by = Y[X >= t]

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, mode='lines+markers', line=dict(width=1, color='grey'), name="useless data"))
fig.add_trace(go.Scatter(x=bx, y=by, mode='lines+markers', line=dict(width=1, color='blue'), name="useful data"))
fig.update_layout(xaxis_title="x axis", yaxis_title="y axis")
fig.show()

Output:

enter image description here


推荐阅读