如何绘制DataFrame中10个样本的变量变化?21个变量样本变化可视化需求
Hey there! Let's figure out how to visualize those variable trends for your 10 samples and 21 variables. I'll break down practical, easy-to-follow approaches using Python's go-to plotting tools—matplotlib, seaborn, and even interactive Plotly if you want to dig into the data more closely.
First, let's assume your DataFrame is structured with samples as rows (either as the index or a dedicated column) and 21 variables as columns. Here's a quick mock-up of what that might look like:
import pandas as pd import numpy as np # Simulate your dataset (replace this with your actual data) np.random.seed(42) df = pd.DataFrame( np.random.randn(10, 21), index=[f"Sample_{i+1}" for i in range(10)], columns=[f"Var_{j+1}" for j in range(21)] )
If you want a high-level view of how all variables change across samples, a single line plot works. We'll add markers and move the legend outside to avoid clutter:
import matplotlib.pyplot as plt plt.figure(figsize=(12, 6)) # Loop through each variable column and plot its trend for var in df.columns: plt.plot(df.index, df[var], marker='o', linewidth=1.5, label=var) plt.title('Trend of All 21 Variables Across 10 Samples') plt.xlabel('Sample ID') plt.ylabel('Variable Value') # Place legend outside the plot area plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0) plt.tight_layout() # Adjust layout to fit the legend plt.show()
21 variables on one plot can get messy. Splitting them into a grid of subplots lets you examine each variable's trend in detail. We'll use a 7x3 grid (since 7*3=21):
fig, axes = plt.subplots(nrows=7, ncols=3, figsize=(15, 20)) axes = axes.flatten() # Convert 2D axes array to 1D for easy looping for idx, var in enumerate(df.columns): axes[idx].plot(df.index, df[var], marker='s', color='teal', linewidth=1.2) axes[idx].set_title(f'{var} Trend', fontsize=10) axes[idx].set_xlabel('Sample', fontsize=8) axes[idx].tick_params(axis='x', rotation=45) # Rotate sample labels to prevent overlap plt.tight_layout(pad=2.0) # Add padding between subplots plt.show()
Seaborn makes it easy to create polished, statistical plots. First, we'll convert our wide-format DataFrame to long (tidy) format, which Seaborn prefers:
import seaborn as sns # Reshape data to long format df_long = df.reset_index().melt( id_vars='index', var_name='Variable', value_name='Value' ) df_long.rename(columns={'index': 'Sample'}, inplace=True) plt.figure(figsize=(12, 6)) sns.lineplot( data=df_long, x='Sample', y='Value', hue='Variable', marker='o', linewidth=1.2 ) plt.title('Variable Trends Across Samples (Seaborn Style)') plt.xlabel('Sample ID') plt.ylabel('Variable Value') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() plt.show()
If you want to hover over points to see exact values or toggle variables on/off, Plotly is perfect:
import plotly.express as px fig = px.line( df, x=df.index, y=df.columns, markers=True, title='Interactive Variable Trends Across Samples' ) fig.update_layout( xaxis_title='Sample ID', yaxis_title='Variable Value', legend_title='Variables', width=1000, height=600 ) fig.show()
Customizing to Your "Specified Style"
If you have a specific look in mind (e.g., custom colors, line styles, or themes), you can tweak these code snippets:
- Use
plt.style.use('ggplot')orplt.style.use('seaborn-v0_8-darkgrid')to apply pre-built themes - Adjust
color,linestyle, andmarkerparameters in the plot calls - Add grid lines with
plt.grid(True)or customize axis labels/title fonts
内容的提问来源于stack exchange,提问作者Warzone

