You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在单个Figure中绘制22个Series:每图2个共11个子图

Solution: Plot 2 Series per Subplot (11 Total Subplots)

Got it, let's sort this out! The core issue is that pandas' plot(subplots=True) creates one subplot per column in your DataFrame—so 22 columns mean 22 subplots. To get two series per subplot (totaling 11 subplots in one figure), we need to manually create our subplot layout and plot pairs of series on each axis.

Step-by-Step Implementation

First, let's adjust your code to generate 22 series, then group them into pairs for each subplot:

import pandas as pd
import matplotlib.pyplot as plt

# Generate 22 sample series (replace with your actual data)
NG = list(range(22))  # 22 series total
serieslist = []
for n in NG:
    # Example data: replace this with your real series data
    sample_data = [n + val for val in range(6)]
    series = pd.DataFrame(sample_data)
    serieslist.append(series)

# Combine all 22 series into a single DataFrame (22 columns)
df = pd.concat(serieslist, axis=1)

# Create a 6x2 subplot grid (fits 11 subplots, leaves one empty spot)
fig, axes = plt.subplots(nrows=6, ncols=2, sharey=True, figsize=(10, 15))
axes = axes.flatten()  # Convert 2D axes array to 1D for easy iteration

# Plot two series per subplot
for i in range(0, 22, 2):
    subplot_idx = i // 2  # Calculate which subplot to use (0 to 10)
    current_ax = axes[subplot_idx]
    
    # Plot first series in the pair
    df.iloc[:, i].plot(ax=current_ax, label=f"Series {i+1}", linewidth=2)
    # Plot second series in the pair
    df.iloc[:, i+1].plot(ax=current_ax, label=f"Series {i+2}", linewidth=2)
    
    # Add labels and formatting
    current_ax.legend()  # Differentiate the two series
    current_ax.grid(True)  # Keep the grid from your original code
    current_ax.set_title(f"Subplot {subplot_idx+1}")

# Hide the unused 12th subplot (since 6*2=12, we only need 11)
axes[-1].set_visible(False)

# Auto-adjust spacing to prevent overlap
plt.tight_layout()
plt.show()

Key Changes Explained

  • Manual Subplot Creation: We use plt.subplots() to define our 6x2 grid upfront, instead of relying on pandas' automatic subplot generation. This gives full control over which series go where.
  • Flatten Axes Array: Converting the 2D axes array to 1D makes it easy to iterate through each subplot in order.
  • Pairwise Plotting: The loop uses a step size of 2 to grab two series at a time, plotting both on the same subplot. We add a legend to distinguish the two series in each subplot.
  • Cleanup: We hide the extra 12th subplot (since 6*2=12 but we only need 11) and use tight_layout() to fix any overlapping labels.

Customization Tips

  • If you prefer a different layout (like 4x3 instead of 6x2), just adjust nrows and ncols in plt.subplots()—make sure the total grid size is at least 11.
  • Modify figsize to adjust the overall figure size for better readability.
  • Replace the sample data generation with your actual series data—just keep the structure of a list of DataFrames (or Series) that get concatenated into a 22-column DataFrame.

内容的提问来源于stack exchange,提问作者Artur Müller Romanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:19:42