如何在同一画布中绘制DataFrame分组后的多列直方图
Got it, let's fix this so all your histograms end up on one unified figure instead of spawning separate windows for each group! Below are two practical approaches depending on how you want to organize your plots:
Approach 1: Grid Layout (One Subplot per Column + Group)
This arranges histograms in a neat grid where each row corresponds to a column (A/B/C) and each column in the grid maps to a group from column D. It's perfect for comparing individual group distributions across different columns.
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Generate your original DataFrame df = pd.DataFrame(np.random.randint(0, 3, size=(100, 4)), columns=list('ABCD')) groups = df.groupby("D") # Get group names and columns we want to plot (exclude D since it's our grouping key) group_labels = list(groups.groups.keys()) columns_to_plot = df.columns.drop("D") # Create a single figure with a grid of subplots fig, axes = plt.subplots( nrows=len(columns_to_plot), ncols=len(group_labels), figsize=(12, 8) # Adjust size based on your needs ) # Loop through columns and groups to plot each histogram in the correct subplot for row_idx, col in enumerate(columns_to_plot): for col_idx, group_name in enumerate(group_labels): # Fetch the specific group's data group_data = groups.get_group(group_name) # Plot histogram on the corresponding subplot group_data[col].hist(ax=axes[row_idx][col_idx], bins=3) # Add clear labels and title axes[row_idx][col_idx].set_title(f"{col} - Group D={group_name}") axes[row_idx][col_idx].set_xlabel(col) axes[row_idx][col_idx].set_ylabel("Count") # Adjust spacing so labels don't overlap plt.tight_layout() plt.show()
Approach 2: Overlapped Histograms (Compare Groups per Column)
If you want to directly compare distributions of the same column across different groups, this approach puts all group histograms for a single column into one subplot (using distinct colors and transparency to avoid clutter).
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Generate your original DataFrame df = pd.DataFrame(np.random.randint(0, 3, size=(100, 4)), columns=list('ABCD')) groups = df.groupby("D") columns_to_plot = df.columns.drop("D") # Assign unique colors to each group for easy distinction group_colors = ["#1f77b4", "#ff7f0e", "#2ca02c"] # Create a single figure with one subplot per column fig, axes = plt.subplots( nrows=len(columns_to_plot), ncols=1, figsize=(8, 10) ) # Handle edge case where there's only one column to plot (avoids index errors) if len(columns_to_plot) == 1: axes = [axes] # Loop through each column and plot all group histograms in the same subplot for idx, col in enumerate(columns_to_plot): ax = axes[idx] for (group_name, group_data), color in zip(groups, group_colors): # Plot histogram with transparency to see overlaps clearly group_data[col].hist( ax=ax, bins=3, alpha=0.7, label=f"Group D={group_name}", color=color ) # Add descriptive labels, title, and legend ax.set_title(f"Distribution of {col} by Group D") ax.set_xlabel(col) ax.set_ylabel("Count") ax.legend() plt.tight_layout() plt.show()
Quick Notes:
- We skip plotting column D because each group will only have one unique value for D, making its histogram irrelevant.
- Tweak
figsize,bins, andcolorsto match your data and visualization preferences. plt.tight_layout()ensures subplot labels and titles don't overlap, keeping the figure clean.
内容的提问来源于stack exchange,提问作者dearn44

