![](/img/trans.png)
[英]How to add a hline or vline to a plotly express legend in Python
[英]update figure add hline with sliders Plotly Python
大家好,我需要幫助,我有一段代碼將水平線列表添加到 python 中的 Plotly 圖。我想將代碼更改為我們將使用 slider 將水平線添加到圖中並重新布局。 當 slider 向右移動時,更多的水平線將添加到圖中,而當 slider 向左移動時,水平線將從圖中移除。 以下是到目前為止我的代碼
for v in range(len(sortadlist)):
fig.add_hline(y=sortadlist[v][0], line_color='brown', line_width=1.5, row=1, col=1)
fig.add_shape(type="rect",
y0=round(sortadlist[v][0],2)-.3, y1=round(sortadlist[v][0],2)+.3, x0=-1, x1=len(df),
fillcolor="darkcyan",
opacity=0.15)
上面的所有代碼都是循環遍歷數字列表並使用 fig.add_hline 將水平線添加到圖中。 我需要幫助創建一個 slider,它將水平線添加到圖中
這是該圖當前的樣子我想要一個 slider 來幫助向圖中添加更多水平線並將它們也刪除
由於沒有完整的代碼,樣本數據是通過獲取公司的股票價格來處理的。 首先,水平線和形狀沒有顯示/隱藏屬性,因此它們與滑塊不兼容。 所以我創建了一個代碼,根據散點圖的折線圖中的適當價目表繪制一條線。 折線圖隱藏后,第一個折線圖可見。 圖表的結構是一個有 6 條線的燭台,燭台始終顯示。 循環過程用於創建要顯示或隱藏的行列表。
import yfinance as yf
import plotly.graph_objects as go
import numpy as np
df = yf.download("AAPL", start="2022-01-01", end="2023-01-01", progress=False)
df.reset_index(inplace=True)
pricelist = np.arange(130,190,10)
fig = go.Figure()
fig.add_trace(go.Candlestick(x=df['Date'],
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
name='AAPL'
)
)
fig.add_hrect(y0=df['Close'].median()-10,
y1=df['Close'].median()+10,
annotation_text="Median+-10",
annotation_position="top right",
fillcolor="darkcyan",
opacity=0.25,
line_width=0)
for p in pricelist:
fig.add_trace(go.Scatter(x=df['Date'],
y=[p]*len(df['Date']),
line_color='blue',
name=str(p),
showlegend=False,
visible=False,
)
)
fig.data[1].visible = True
steps = []
for i in np.arange(1,len(fig.data)):
step = dict(
method="update",
args=[{"visible": [False] * len(fig.data)},
{"title": "Price lines: " + str(pricelist[i-1])}],
label=str(pricelist[i-1])
)
step["args"][0]["visible"][0] = True
step["args"][0]["visible"][i] = True
steps.append(step)
sliders = [dict(
active=10,
currentvalue={"prefix": "Price: "},
pad={"t": 50},
steps=steps
)]
fig.update_layout(
sliders=sliders
)
fig.update_layout(height=600, xaxis_rangeslider_visible=False)
fig.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.