You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何合并Pandas绘制的DataFrame子图中的每隔一个子图?

Merging Every Other Subplot in Pandas Plotting

Got it, let's tackle this problem. Your current code generates a 7x2 grid of subplots (one for each column in your DataFrame), and you want to merge every pair of adjacent subplots—meaning each row's two subplots become a single subplot that displays both of the corresponding series. Here are two straightforward approaches to achieve this:

Approach 1: Manual Subplot Creation (Simplest)

Instead of letting pandas auto-generate subplots for every column, we'll create a grid of 7 single subplots (one per group of two columns) and plot both series from each group onto the same subplot.

import pandas as pd
import matplotlib.pyplot as plt

# Your original data preparation code
NG = [1,2,3,4,5,6,7]
dflist = []
l = [1,2,3,4,5,6]
b = [6,5,4,3,2,1]
for n in NG:
    df = pd.DataFrame(l)
    dflist.append(df)
    df2 = pd.DataFrame(b)
    dflist.append(df2)
df = pd.concat(dflist, axis = 1)

# Create a 7-row, 1-column grid of subplots
fig, axes = plt.subplots(nrows=7, ncols=1, figsize=(8, 14), sharey=True)

# Loop through each group of two columns and plot them on the same subplot
for group_idx in range(7):
    # Select the two columns for this group
    group_cols = df.iloc[:, [2*group_idx, 2*group_idx + 1]]
    # Plot both series on the current subplot
    group_cols.plot(grid=True, ax=axes[group_idx])
    # Add a title for clarity
    axes[group_idx].set_title(f'Group {group_idx + 1}')

# Adjust layout to prevent overlapping labels
plt.tight_layout()
plt.show()

Approach 2: Using GridSpec for Fine Layout Control

If you need more control over the subplot layout (like adjusting spacing or merging specific grid cells), you can use matplotlib's GridSpec to explicitly merge the two columns in each row:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

# Your original data preparation code (same as above)
NG = [1,2,3,4,5,6,7]
dflist = []
l = [1,2,3,4,5,6]
b = [6,5,4,3,2,1]
for n in NG:
    df = pd.DataFrame(l)
    dflist.append(df)
    df2 = pd.DataFrame(b)
    dflist.append(df2)
df = pd.concat(dflist, axis = 1)

# Create a figure and a 7x2 grid specification
fig = plt.figure(figsize=(8, 14))
gs = GridSpec(7, 2, figure=fig)

# Loop through each row and merge the two columns into one subplot
for row_idx in range(7):
    # Merge the two columns in the current row into a single axis
    ax = fig.add_subplot(gs[row_idx, :])
    # Select and plot the two columns for this group
    group_cols = df.iloc[:, [2*row_idx, 2*row_idx + 1]]
    group_cols.plot(grid=True, ax=ax, sharey=True)
    ax.set_title(f'Group {row_idx + 1}')

plt.tight_layout()
plt.show()

Key Idea

The core change here is moving away from subplots=True (which creates one subplot per column) to manually grouping your DataFrame columns and plotting each group on a single subplot. This gives you full control over which series share a subplot.

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

火山引擎 最新活动