Plotly绘制股票K线图时如何将默认副图替换为RSI指标图
Fixing the Duplicate Subplot: Replace with RSI Chart
Hey there! Let's get that duplicate candlestick subplot swapped out for an RSI indicator—super straightforward once you use Plotly's subplot system properly. Here's how to adjust your code:
Modified Full Code
import pandas as pd import ta import plotly.graph_objects as go from plotly.subplots import make_subplots # Load your data and calculate RSI (same as before) df = pd.read_csv("Trial.csv") df["rsi"] = ta.momentum.rsi(df["Close"], window=14, fillna=False) dfff = df.tail(180) # Create a 2-row subplot layout with shared x-axis fig = make_subplots( rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.05, # Small gap between charts row_heights=[0.7, 0.3] # Give main OHLC chart more space ) # Add candlestick chart to the top row fig.add_trace( go.Candlestick( x=dfff['Date'], open=dfff['Open'], high=dfff['High'], low=dfff['Low'], close=dfff['Close'], name='OHLC' ), row=1, col=1 ) # Add RSI line to the bottom subplot fig.add_trace( go.Scatter( x=dfff['Date'], y=dfff['rsi'], name='RSI (14)', line=dict(color='#ff7f0e') # Orange line for visibility ), row=2, col=1 ) # Add standard RSI reference lines (30 = oversold, 70 = overbought) fig.add_hline(y=30, line_dash="dash", line_color="green", row=2, col=1) fig.add_hline(y=70, line_dash="dash", line_color="red", row=2, col=1) # Customize the overall layout fig.update_layout( autosize=False, width=4181, height=1597, title='Stock OHLC with RSI Indicator', xaxis_title='Date', yaxis_title='Price', yaxis2_title='RSI Value' ) # Optional: Hide the range slider on the x-axis if you don't need it fig.update_layout(xaxis_rangeslider_visible=False) # Save the final figure fig.write_image("fig_001.jpeg")
Key Changes Explained
make_subplotsSetup: This replaces your basicgo.Figurewith a structured 2-row layout. Sharing the x-axis ensures the date ranges sync between both charts, and the row heights keep the main OHLC chart as the focal point.- Separate Traces: We explicitly add the candlestick chart to the first row and the RSI line to the second row using the
rowparameter inadd_trace. No more duplicate plots! - RSI Reference Lines: The dashed green/red lines at 30 and 70 are standard for RSI analysis—they help quickly spot oversold/overbought conditions.
- Layout Polish: Added clear titles for each y-axis and adjusted spacing to make the chart look clean.
This will give you a proper main OHLC chart with an RSI indicator below it, exactly what you're looking for.
内容的提问来源于stack exchange,提问作者Lokkii9
相关产品推荐
相关产品推荐

