Python Plotly子图创建问题求助(附数据集与代码)
Hey there! Congrats on getting up to speed with Plotly in just 3 months—single line charts are a great start, and subplots are totally within your reach. Let's break down why your make_subplots was showing blank charts, plus clean up that repetitive code.
Why Your Subplots Were Blank
The most common culprit here is not specifying the row and col parameters when adding traces to your subplot figure. Without these, Plotly doesn't know where to place each line chart, leaving you with empty axes. Other possible issues include forgetting to call fig.show() at the end, or misreferencing your DataFrame columns.
Optimizing Repetitive Code
Instead of writing three separate add_trace blocks for each metric, we can loop through your metrics and their target subplot positions. This cuts down on redundancy and makes your code easier to maintain if you ever add new metrics later.
Full Working Example
Let's assume your dataset is a pandas DataFrame named df with columns: date (your x-axis), pn_chg, fx_chg, totw_chg. Here's the revised code:
import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd # Replace this with your actual dataset df = pd.DataFrame({ 'date': pd.date_range(start='2024-01-01', periods=30), 'pn_chg': [i*0.5 + pd.np.random.randn() for i in range(30)], 'fx_chg': [i*0.3 + pd.np.random.randn() for i in range(30)], 'totw_chg': [i*0.8 + pd.np.random.randn() for i in range(30)] }) # Create 2x2 subplot layout with titles fig = make_subplots( rows=2, cols=2, subplot_titles=("PN Change", "FX Change", "Total Change", "") # Empty title for unused 4th subplot ) # Define metrics and their target subplot positions (column name, label, row, column) metrics = [ ('pn_chg', 'PN Change', 1, 1), ('fx_chg', 'FX Change', 1, 2), ('totw_chg', 'Total Change', 2, 1) ] # Loop through metrics to add traces (no more repeated code!) for col_name, y_label, row, col in metrics: fig.add_trace( go.Scatter(x=df['date'], y=df[col_name], mode='lines', name=y_label), row=row, col=col # Critical: tell Plotly which subplot to use ) # Customize overall layout for consistency fig.update_layout( height=600, width=800, title_text="Metric Changes Over Time", showlegend=False # Hide legend since subplot titles already label each chart ) # Update axes labels for clarity fig.update_xaxes(title_text="Date", row=1, col=1) fig.update_xaxes(title_text="Date", row=1, col=2) fig.update_xaxes(title_text="Date", row=2, col=1) fig.update_yaxes(title_text="Change Value", row=1, col=1) fig.update_yaxes(title_text="Change Value", row=1, col=2) fig.update_yaxes(title_text="Change Value", row=2, col=1) # Display the chart fig.show()
Key Takeaways:
rowandcolparameters: Everyadd_tracecall needs these to map your line chart to the correct subplot—this is the fix for blank charts.- Loop-based trace addition: By storing metrics and positions in a list, we eliminate duplicate code. Adding a new metric later only requires one extra tuple in the
metricslist. - Clean layout: We added empty title for the unused 4th subplot to keep the 2x2 grid intact, and removed redundant legends since subplot titles already clarify each chart.
This should resolve your blank subplot issue and make your code much cleaner. If you hit snags with your actual dataset, feel free to share more details!
内容的提问来源于stack exchange,提问作者t3c

