目标是在 x=1 的每个子图中获得垂直无限线。在这个例子中,我将在第一行第一列尝试一个 type="line" 的绘图形状
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import numpy as np
fig = make_subplots(
rows=2,
cols=2,
subplot_titles=list(map(str, range(4))),
shared_xaxes=True,
shared_yaxes=False,
)
time = np.linspace(-np.pi, np.pi, 1000)
for i in range(4):
data = np.sin((i+1) * time)
fig.add_trace(
go.Scatter(y=data,x=time, name=str(i)),
row=1 if i in [0, 1] else 2,
col=1 if i in [0, 2] else 2,
)
fig.add_shape(
go.layout.Shape(
type="line",
yref="paper",
xref="x",
x0=1,
y0=0,
x1=1,
y1=1,
line=dict(color="RoyalBlue", width=3),
),row=1,col=1)
fig.write_image("1.png",width=800, height=600, scale=1)
Run Code Online (Sandbox Code Playgroud)
所以看起来添加具有行和列的形状会覆盖 yref 和外部参照属性,返回一条线段而不是无限线。在打印前强制 yref …
我试图在 Plotly 中突出显示时间段。我似乎最好的方法是使用 Shapes,就像这样,但在现实世界中,您不想像示例 url 中那样手动添加每个形状。我认为 for 循环是最好的解决方案,但欢迎其他(计算量较小的)建议。
我的脚本如下所示:
np.random.seed(12345)
rows = 20
x = pd.Series(np.random.randn(rows),index=pd.date_range('1/1/2020', periods=rows)).cumsum()
df = pd.DataFrame({"index": x})
# add column showing what to shade
df["signal"] = df['index'] < 5
# plot index and highlight periods with Rectangle Shapes in Plotly
fig = px.line(df, x=df.index, y="index")
for row in df.iterrows():
if df['signal'] == False:
ply_shapes['shape_' + str(i)]=go.layout.Shape(type="rect",
x0=df.dato[i-1],
y0=0,
x1=df.dato[i],
y1=2000,
opacity=0.5,
layer="below"
)
lst_shapes=list(ply_shapes.values())
fig.update_layout(shapes=lst_shapes)
fig.show()
Run Code Online (Sandbox Code Playgroud)
但这返回:
ValueError: The truth value of a Series …Run Code Online (Sandbox Code Playgroud)