Matplotlib绘制植物生长曲线:从数据到可视化分析的完整指南

引言
植物生长曲线是植物生理学和农业科学研究中的重要工具,它展示了植物在不同生长阶段的高度、生物量或其他指标随时间的变化规律。通过绘制生长曲线,研究人员可以直观地观察植物的生长趋势,识别关键生长阶段,并评估不同环境条件或处理对植物生长的影响。
Matplotlib是Python中最流行的数据可视化库之一,它提供了强大而灵活的工具来创建高质量的科学图表。本指南将详细介绍如何使用Matplotlib从原始数据创建专业的植物生长曲线,包括数据准备、基础绘图、高级定制和统计分析等完整流程。
1. 环境准备和数据结构
1.1 安装必要的库
首先,确保安装了必要的Python库:
# 安装命令(在终端中执行)
pip install matplotlib numpy pandas scipy
1.2 数据结构设计
植物生长数据通常采用表格形式,包含以下关键列:
时间/天数
:X轴,表示实验天数
株高/生物量
:Y轴,表示测量值
处理组
:不同实验条件(如不同肥料、光照、水分等)
重复
:每个处理组的重复样本数
import pandas as pd
import numpy as np
import matplotlib.pyplot as Matplotlib绘制植物生长曲线:从数据到可视化分析的完整指南

# 示例数据结构
data = {
‘Day’: [0, 3, 7, 10, 14, 17, 21, 24, 28, 31, 35],
‘Height_Control’: [2.1, 2.3, 2.8, 3.5, 4.2, 5.1, 6.2, 7.4, 8.8, 10.2, 11.5],
‘Height_Treatment1’: [2.1, 2.4, 3.1, 4.0, 5.2, 6.5, 8.1, 9.8, 11.7, 13.6, 15.5],
‘Height_Treatment2′: [2.1, 2.5, 3.3, 4.5, 6.0, 7.8, 9.9, 12.3, 14.9, 17.6, 20.3]
}

df = pd.DataFrame(data)
print(df)
2. 基础生长曲线绘制
2.1 创建第一个生长曲线
让我们从最简单的单组生长曲线开始:
import matplotlib.pyplot as plt
import numpy as np

# 准备数据
days = np.array([0, 3, 7, 10, 14, 17, 21, 24, 28, 31, 35])
height_control = np.array([2.1, 2.3, 2.8, 3.5, 4.2, 5.1, 6.2, 7.4, 8.8, 10.2, 11.5])

# 创建图形和轴对象
fig, ax = plt.subplots(figsize=(10, 6))

# 绘制基础曲线
ax.plot(days, height_control,
color=’blue’,
linewidth=2,
marker=’o’,
markersize=6,
label=’Control Group’)

# 设置标题和标签
ax.set_title(‘Plant Growth Curve – Control Group’, fontsize=14, fontweight=’bold’)
ax.set_xlabel(‘Days After Planting’, fontsize=12)
ax.set_ylabel(‘Plant Height (cm)’, fontsize=12)

# 添加网格和图例
ax.grid(True, alpha=0.3)
ax.legend()

# 显示图形
plt.tight_layout()
plt.show()
2.2 多组生长曲线对比
在实际研究中,我们通常需要比较不同处理组的生长情况:
# 多组数据对比
height_treatment1 = np.array([2.1, 2.4, 3.1, 4.0, 5.2, 6.5, 8.1, 9.8, 11.7, 13.6, 15.5])
height_treatment2 = np.array([2.1, 2.5, 3.3, 4.5, 6.0, 7.8, 9.9, 12.3, 14.9, 17.6, 20.3])

fig, ax = plt.subplots(figsize=(12, 7))

# 绘制多条曲线
ax.plot(days, height_control, ‘o-‘, color=’blue’, linewidth=2, label=’Control’, alpha=0.8)
ax.plot(days, height_treatment1, ‘s-‘, color=’green’, linewidth=2, label=’Treatment 1′, alpha=0.8)
ax.plot(days, height_treatment2, ‘^-‘, color=’red’, linewidth=2, label=’Treatment 2′, alpha=0.8)

# 美化图表
ax.set_title(‘Comparative Plant Growth Curves’, fontsize=16, fontweight=’bold’, pad=20)
ax.set_xlabel(‘Days After Planting’, fontsize=12)
ax.set_ylabel(‘Plant Height (cm)’, fontsize=12)
ax.grid(True, alpha=0.3, linestyle=’–‘)
ax.legend(loc=’upper left’, fontsize=10)

# 设置坐标轴范围
ax.set_xlim(0, 35)
ax.set_ylim(0, 22)

plt.tight_layout()
plt.show()
3. 数据处理与误差分析
3.1 处理重复样本数据
在实际实验中,每个时间点通常有多个重复样本。我们需要计算平均值和标准误差:
# 模拟重复样本数据(每个时间点3个重复)
np.random.seed(42)
days = np.array([0, 3, 7, 10, 14, 17, 21, 24, 28, 31, 35])

# 生成带噪声的重复数据
control_repeats = []
treatment1_repeats = []
treatment2_repeats = []

for i, day in enumerate(days):
# Control组:基础值 + 随机噪声
base_control = 2.0 + 0.3 * day * 0.3 # 增长趋势
control_repeats.append([base_control + np.random.normal(0, 0.2) for _ in range(3)])

# Treatment1组
base_t1 = 2.0 + 0.35 * day * 0.35
treatment1_repeats.append([base_t1 + np.random.normal(0, 0.2) for _ in range(3)])

# Treatment2组
base_t2 = 2.0 + 0.42 * day * 0.42
treatment2_repeats.append([base_t2 + np.random.normal(0, 0.2) for _ in range(3)])

# 转换为numpy数组
control_repeats = np.array(control_repeats)
treatment1_repeats = np.array(treatment1_repeats)
treatment2_repeats = np.array(treatment2_repeats)

# 计算平均值和标准误差
control_mean = np.mean(control_repeats, axis=1)
control_std = np.std(control_repeats, axis=1)

treatment1_mean = np.mean(treatment1_repeats, axis=1)
treatment1_std = np.std(treatment1_repeats, axis=1)

treatment2_mean = np.mean(treatment2_repeats, axis=1)
treatment2_std = np.std(treatment2_repeats, axis=1)

print(“Control组平均值:”, control_mean)
print(“Control组标准差:”, control_std)
3.2 绘制带误差带的生长曲线
fig, ax = plt.subplots(figsize=(12, 7))

# 绘制带误差带的曲线
# Control组
ax.plot(days, control_mean, ‘o-‘, color=’blue’, linewidth=2, label=’Control’, zorder=3)
ax.fill_between(days,
control_mean – control_std,
control_mean + control_std,
color=’blue’, alpha=0.2, label=’±SD (Control)’)

# Treatment1组
ax.plot(days, treatment1_mean, ‘s-‘, color=’green’, linewidth=2, label=’Treatment 1′, zorder=3)
ax.fill_between(days,
treatment1_mean – treatment1_std,
treatment1_mean + treatment1_std,
color=’green’, alpha=0.2, label=’±SD (Treatment 1)’)

# Treatment2组
ax.plot(days, treatment2_mean, ‘^-‘, color=’red’, linewidth=2, label=’Treatment 2′, zorder=3)
ax.fill_between(days,
treatment2_mean – treatment2_std,
treatment2_mean + treatment2_std,
color=’red’, alpha=0.2, label=’±SD (Treatment 2)’)

# 美化图表
ax.set_title(‘Plant Growth Curves with Error Bands’, fontsize=16, fontweight=’bold’, pad=20)
ax.set_xlabel(‘Days After Planting’, fontsize=12)
ax.set_ylabel(‘Plant Height (cm)’, fontsize=12)
ax.grid(True, alpha=0.3, linestyle=’–‘)
ax.legend(loc=’upper left’, fontsize=9, ncol=2)

plt.tight_layout()
plt.show()
4. 高级可视化技巧
4.1 添加趋势线和拟合曲线
植物生长通常遵循S形曲线(Logistic生长模型)。我们可以使用scipy进行曲线拟合:
from scipy.optimize import curve_fit

# Logistic生长模型
def logistic_growth(t, K, r, t0, L):
“””
Logistic生长模型: L + K / (1 + exp(-r*(t-t0)))
K: 最大生长量
r: 生长速率
t0: 拐点时间
L: 初始值
“””
return L + K / (1 + np.exp(-r * (t – t0)))

# 拟合Control组数据
popt_control, pcov_control = curve_fit(logistic_growth, days, control_mean,
p0=[10, 0.2, 15, 2], maxfev=5000)

# 生成平滑曲线用于绘图
days_smooth = np.linspace(0, 35, 100)
control_fit = logistic_growth(days_smooth, *popt_control)

# 拟合Treatment1组数据
popt_t1, pcov_t1 = curve_fit(logistic_growth, days, treatment1_mean,
p0=[12, 0.25, 15, 2], maxfev=5000)
treatment1_fit = logistic_growth(days_smooth, *popt_t1)

# 拟合Treatment2组数据
popt_t2, pcov_t2 = curve_fit(logistic_growth, days, treatment2_mean,
p0=[15, 0.3, 15, 2], maxfev=5000)
treatment2_fit = logistic_growth(days_smooth, *popt_t2)

# 绘制拟合曲线
fig, ax = plt.subplots(figsize=(12, 7))

# 原始数据点
ax.plot(days, control_mean, ‘o’, color=’blue’, markersize=6, label=’Control (data)’)
ax.plot(days, treatment1_mean, ‘s’, color=’green’, markersize=6, label=’Treatment 1 (data)’)
ax.plot(days, treatment2_mean, ‘^’, color=’red’, markersize=6, label=’Treatment 2 (data)’)

# 拟合曲线
ax.plot(days_smooth, control_fit, ‘-‘, color=’blue’, linewidth=2, label=’Control (fit)’)
ax.plot(days_smooth, treatment1_fit, ‘-‘, color=’green’, linewidth=2, label=’Treatment 1 (fit)’)
ax.plot(days_smooth, treatment2_fit, ‘-‘, color=’red’, linewidth=2, label=’Treatment 2 (fit)’)

# 添加拟合参数文本框
textstr = ‘\n’.join([
f’Control: K={popt_control[0]:.1f}, r={popt_control[1]:.3f}’,
f’T1: K={popt_t1[0]:.1f}, r={popt_t1[1]:.3f}’,
f’T2: K={popt_t2[0]:.1f}, r={popt_t2[1]:.3f}’
])
props = dict(boxstyle=’round’, facecolor=’wheat’, alpha=0.5)
ax.text(0.02, 0.98, textstr, transform=ax.transAxes, fontsize=9,
verticalalignment=’top’, bbox=props)

ax.set_title(‘Plant Growth with Logistic Model Fitting’, fontsize=16, fontweight=’bold’)
ax.set_xlabel(‘Days After Planting’, fontsize=12)
ax.set_ylabel(‘Plant Height (cm)’, fontsize=12)
ax.grid(True, alpha=0.3)
ax.legend(loc=’upper left’, fontsize=9)

plt.tight_layout()
plt.show()
4.2 子图布局:原始数据、拟合曲线、增长率
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle(‘Comprehensive Growth Analysis’, fontsize=18, fontweight=’bold’)

# 1. 原始数据与误差带
ax1 = axes[0, 0]
ax1.plot(days, control_mean, ‘o-‘, color=’blue’, label=’Control’)
ax1.fill_between(days, control_mean-control_std, control_mean+control_std, alpha=0.2, color=’blue’)
ax1.plot(days, treatment1_mean, ‘s-‘, color=’green’, label=’Treatment 1′)
ax1.fill_between(days, treatment1_mean-treatment1_std, treatment1_mean+treatment1_std, alpha=0.2, color=’green’)
ax1.set_title(‘Raw Data with Error Bands’)
ax1.set_xlabel(‘Days’)
ax1.set_ylabel(‘Height (cm)’)
ax1.grid(True, alpha=0.3)
ax1.legend()

# 2. Logistic拟合曲线
ax2 = axes[0, 1]
ax2.plot(days_smooth, control_fit, ‘-‘, color=’blue’, label=’Control’)
ax2.plot(days_smooth, treatment1_fit, ‘-‘, color=’green’, label=’Treatment 1′)
ax2.plot(days_smooth, treatment2_fit, ‘-‘, color=’red’, label=’Treatment 2′)
ax2.set_title(‘Logistic Model Fits’)
ax2.set_xlabel(‘Days’)
ax2.set_ylabel(‘Height (cm)’)
ax2.grid(True, alpha=0.3)
ax2.legend()

# 3. 增长速率(导数)
ax3 = axes[1, 0]
# 计算拟合曲线的导数(增长率)
def logistic_derivative(t, K, r, t0, L):
return K * r * np.exp(-r*(t-t0)) / (1 + np.exp(-r*(t-t0)))**2

control_rate = logistic_derivative(days_smooth, *popt_control)
treatment1_rate = logistic_derivative(days_smooth, *popt_t1)
treatment2_rate = logistic_derivative(days_smooth, *popt_t2)

ax3.plot(days_smooth, control_rate, ‘-‘, color=’blue’, label=’Control’)
ax3.plot(days_smooth, treatment1_rate, ‘-‘, color=’green’, label=’Treatment 1′)
ax3.plot(days_smooth, treatment2_rate, ‘-‘, color=’red’, label=’Treatment 2′)
ax3.set_title(‘Growth Rate (Derivative)’)
ax3.set_xlabel(‘Days’)
ax3.set_ylabel(‘Rate (cm/day)’)
ax3.grid(True, alpha=0.3)
ax3.legend()

# 4. 累积生物量(积分)
ax4 = axes[1, 1]
# 计算拟合曲线的积分(累积生长量)
from scipy.integrate import cumulative_trapezoid

control_integral = cumulative_trapezoid(control_fit, days_smooth, initial=0)
treatment1_integral = cumulative_trapezoid(treatment1_fit, days_smooth, initial=0)
treatment2_integral = cumulative_trapezoid(treatment2_fit, days_smooth, initial=0)

ax4.plot(days_smooth, control_integral, ‘-‘, color=’blue’, label=’Control’)
ax4.plot(days_smooth, treatment1_integral, ‘-‘, color=’green’, label=’Treatment 1′)
ax4.plot(days_smooth, treatment2_integral, ‘-‘, color=’red’, label=’Treatment 2′)
ax4.set_title(‘Cumulative Growth (Integral)’)
ax4.set_xlabel(‘Days’)
ax4.set_ylabel(‘Cumulative Height (cm·day)’)
ax4.grid(True, alpha=0.3)
ax4.legend()

plt.tight_layout()
plt.show()
5. 统计分析与显著性检验
5.1 计算生长参数
# 计算关键生长参数
def calculate_growth_parameters(days, heights):
“””
计算植物生长关键参数
“””
# 最终高度
final_height = heights[-1]

# 总生长量
total_growth = heights[-1] – heights[0]

# 平均日增长
avg_daily_growth = total_growth / days[-1]

# 最大日增长(相邻两天差值的最大值)
daily_increments = np.diff(heights)
max_daily_growth = np.max(daily_increments)

# 达到50%最终高度的时间
half_final = heights[0] + total_growth * 0.5
idx_half = np.where(heights >= half_final)[0][0]
days_to_half = days[idx_half]

return {
‘Final Height’: final_height,
‘Total Growth’: total_growth,
‘Avg Daily Growth’: avg_daily_growth,
‘Max Daily Growth’: max_daily_growth,
‘Days to 50% Height’: days_to_half
}

# 计算各组参数
params_control = calculate_growth_parameters(days, control_mean)
params_t1 = calculate_growth_parameters(days, treatment1_mean)
params_t2 = calculate_growth_parameters(days, treatment2_mean)

# 创建参数对比表格
import pandas as pd
params_df = pd.DataFrame({
‘Control’: params_control,
‘Treatment 1’: params_t1,
‘Treatment 2’: params_t2
})

print(“生长参数对比:”)
print(params_df.round(2))
5.2 显著性检验(t检验)
from scipy import stats

# 进行最终高度的t检验
# 假设我们有最终时间点的重复样本数据
final_day = 35
control_final = control_repeats[-1] # Control组最终高度的3个重复
t1_final = treatment1_repeats[-1] # Treatment1组最终高度的3个重复
t2_final = treatment2_repeats[-1] # Treatment2组最终高度的3个重复

# Control vs Treatment1
t_stat1, p_val1 = stats.ttest_ind(control_final, t1_final)
print(f”Control vs Treatment1: t={t_stat1:.3f}, p={p_val1:.4f}”)

# Control vs Treatment2
t_stat2, p_val2 = stats.ttest_ind(control_final, t2_final)
print(f”Control vs Treatment2: t={t_stat2:.3f}, p={p_val2:.4f}”)

# Treatment1 vs Treatment2
t_stat3, p_val3 = stats.ttest_ind(t1_final, t2_final)
print(f”Treatment1 vs Treatment2: t={t_stat3:.3f}, p={p_val3:.4f}”)

# 可视化显著性
fig, ax = plt.subplots(figsize=(8, 6))

# 箱线图显示最终高度分布
data_to_plot = [control_final, t1_final, t2_final]
bp = ax.boxplot(data_to_plot, labels=[‘Control’, ‘Treatment 1’, ‘Treatment 2′])

# 添加显著性标记
def add_significance(ax, data1, data2, x1, x2, y, p_value, text):
# 绘制显著性标记
ax.plot([x1, x1, x2, x2], [y, y+0.5, y+0.5, y], lw=1.5, c=’black’)
# 添加p值文本
significance = “***” if p_value < 0.001 else "**" if p_value < 0.01 else "*" if p_value < 0.05 else "ns" ax.text((x1+x2)*0.5, y+0.6, f"{significance}\n(p={p_value:.4f})", ha='center', fontsize=10) # 设置y轴范围 max_val = max(np.max(control_final), np.max(t1_final), np.max(t2_final)) ax.set_ylim(0, max_val * 1.3) # 添加显著性标记 add_significance(ax, control_final, t1_final, 1, 2, max_val*1.1, p_val1, "Control vs T1") add_significance(ax, control_final, t2_final, 1, 3, max_val*1.15, p_val2, "Control vs T2") add_significance(ax, t1_final, t2_final, 2, 3, max_val*1.2, p_val3, "T1 vs T2") ax.set_ylabel('Final Height (cm)', fontsize=12) ax.set_title('Final Height Distribution with Significance', fontsize=14, fontweight='bold') ax.grid(True, alpha=0.3, axis='y') plt.tight_layout() plt.show() 6. 专业出版级图表定制 6.1 出版级图表设置 # 设置matplotlib参数以适应出版要求 plt.rcParams.update({ 'font.family': 'sans-serif', 'font.sans-serif': ['Arial', 'DejaVu Sans'], 'font.size': 10, 'axes.linewidth': 0.8, 'axes.labelsize': 10, 'axes.titlesize': 12, 'xtick.major.size': 3, 'xtick.minor.size': 1.5, 'ytick.major.size': 3, 'ytick.minor.size': 1.5, 'legend.fontsize': 9, 'legend.frameon': False, 'figure.dpi': 300, 'savefig.dpi': 300 }) # 创建出版级图表 fig, ax = plt.subplots(figsize=(3.5, 2.8), dpi=300) # 单栏宽度约8.7cm # 使用更专业的颜色方案(ColorBrewer) colors = ['#377eb8', '#4daf4a', '#e41a1c'] # 蓝、绿、红 # 绘制数据 ax.plot(days, control_mean, 'o-', color=colors[0], linewidth=1.5, markersize=4, markerfacecolor='white', markeredgewidth=1.5, label='Control') ax.plot(days, treatment1_mean, 's-', color=colors[1], linewidth=1.5, markersize=4, markerfacecolor='white', markeredgewidth=1.5, label='Treatment 1') ax.plot(days, treatment2_mean, '^-', color=colors[2], linewidth=1.5, markersize=4, markerfacecolor='white', markeredgewidth=1.5, label='Treatment 2') # 添加误差带(更细的透明度) ax.fill_between(days, control_mean-control_std, control_mean+control_std, color=colors[0], alpha=0.15, linewidth=0) ax.fill_between(days, treatment1_mean-treatment1_std, treatment1_mean+treatment1_std, color=colors[1], alpha=0.15, linewidth=0) ax.fill_between(days, treatment2_mean-treatment2_std, treatment2_mean+treatment2_std, color=colors[2], alpha=0.15, linewidth=0) # 设置标签和标题 ax.set_xlabel('Days after planting', fontsize=10) ax.set_ylabel('Plant height (cm)', fontsize=10) ax.set_title('Growth curves of different treatments', fontsize=11, pad=8) # 设置坐标轴 ax.set_xlim(0, 35) ax.set_ylim(0, 22) # 设置刻度 ax.set_xticks(np.arange(0, 36, 5)) ax.set_yticks(np.arange(0, 23, 5)) # 网格线(更细) ax.grid(True, alpha=0.2, linewidth=0.5, linestyle='--') # 图例(更紧凑) ax.legend(loc='upper left', fontsize=8, frameon=False, handlelength=2.5, columnspacing=1.0) # 移除顶部和右侧边框 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # 添加显著性标记(如果需要) # ax.text(20, 20, '*** p<0.001', fontsize=9, ha='center') plt.tight_layout() plt.savefig('plant_growth_curve.png', bbox_inches='tight', dpi=300) plt.show() 6.2 批量导出多种格式 def export_growth_chart(fig, filename_base, dpi=300): """ 批量导出图表为多种格式 """ formats = ['png', 'pdf', 'svg', 'eps'] for fmt in formats: filename = f"{filename_base}.{fmt}" fig.savefig(filename, format=fmt, bbox_inches='tight', dpi=dpi) print(f"导出: {filename}") # 使用示例 # export_growth_chart(fig, "plant_growth_analysis") 7. 完整工作流程示例 7.1 从原始数据到最终图表的完整脚本 """ 植物生长曲线分析完整工作流程 """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy import stats import seaborn as sns # 1. 数据准备 def generate_sample_data(): """生成模拟实验数据""" np.random.seed(42) days = np.array([0, 3, 7, 10, 14, 17, 21, 24, 28, 31, 35]) # 生成带重复的数据 data = {'Day': days} groups = ['Control', 'Treatment1', 'Treatment2'] base_heights = [2.0, 2.0, 2.0] growth_rates = [0.3, 0.35, 0.42] for group, base, rate in zip(groups, base_heights, growth_rates): for rep in range(1, 4): # Logistic生长 + 随机噪声 true_height = base + 10 / (1 + np.exp(-rate * (days - 15))) noise = np.random.normal(0, 0.3, len(days)) data[f'{group}_Rep{rep}'] = true_height + noise return pd.DataFrame(data) # 2. 数据处理 def process_data(df): """处理原始数据,计算统计量""" groups = ['Control', 'Treatment1', 'Treatment2'] results = {} for group in groups: # 提取重复数据 rep_cols = [col for col in df.columns if group in col] rep_data = df[rep_cols].values # 计算统计量 mean = np.mean(rep_data, axis=1) std = np.std(rep_data, axis=1) sem = stats.sem(rep_data, axis=1) # 标准误差 results[group] = { 'mean': mean, 'std': std, 'sem': sem, 'data': rep_data } return results # 3. 拟合模型 def fit_logistic_model(days, mean_values): """拟合Logistic生长模型""" def logistic(t, K, r, t0, L): return L + K / (1 + np.exp(-r * (t - t0))) try: popt, pcov = curve_fit(logistic, days, mean_values, p0=[10, 0.2, 15, 2], maxfev=5000) return popt, pcov, logistic except: return None, None, None # 4. 统计分析 def perform_statistical_analysis(results, final_day_idx=-1): """执行统计分析""" groups = list(results.keys()) final_heights = [results[g]['data'][final_day_idx] for g in groups] # 方差分析 f_stat, p_value = stats.f_oneway(*final_heights) # 两两比较 comparisons = [] for i in range(len(groups)): for j in range(i+1, len(groups)): t_stat, p_val = stats.ttest_ind(final_heights[i], final_heights[j]) comparisons.append({ 'group1': groups[i], 'group2': groups[j], 't_stat': t_stat, 'p_value': p_val, 'significant': p_val < 0.05 }) return { 'anova': {'f_stat': f_stat, 'p_value': p_value}, 'pairwise': comparisons } # 5. 可视化 def create_comprehensive_plot(df, results, stats_results): """创建综合分析图表""" days = df['Day'].values # 设置样式 plt.style.use('seaborn-v0_8-whitegrid') fig = plt.figure(figsize=(15, 10)) # 创建子图网格 gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3) # 1. 主生长曲线(带误差带) ax1 = fig.add_subplot(gs[0, :2]) colors = ['#377eb8', '#4daf4a', '#e41a1c'] group_names = ['Control', 'Treatment1', 'Treatment2'] display_names = ['Control', 'Treatment 1', 'Treatment 2'] for i, (group, color, name) in enumerate(zip(group_names, colors, display_names)): mean = results[group]['mean'] std = results[group]['std'] ax1.plot(days, mean, 'o-', color=color, linewidth=2, markersize=5, markerfacecolor='white', markeredgewidth=1.5, label=name) ax1.fill_between(days, mean-std, mean+std, color=color, alpha=0.15) ax1.set_xlabel('Days after planting') ax1.set_ylabel('Plant height (cm)') ax1.set_title('Growth Curves with Standard Deviation') ax1.legend(loc='upper left') ax1.grid(True, alpha=0.3) # 2. 最终高度对比(箱线图) ax2 = fig.add_subplot(gs[0, 2]) final_heights = [results[g]['data'][-1] for g in group_names] bp = ax2.boxplot(final_heights, labels=display_names, patch_artist=True) # 设置颜色 for patch, color in zip(bp['boxes'], colors): patch.set_facecolor(color) patch.set_alpha(0.3) ax2.set_ylabel('Final height (cm)') ax2.set_title('Final Height Distribution') ax2.grid(True, alpha=0.3, axis='y') # 3. Logistic拟合 ax3 = fig.add_subplot(gs[1, :2]) days_smooth = np.linspace(0, 35, 100) for i, (group, color, name) in enumerate(zip(group_names, colors, display_names)): mean = results[group]['mean'] popt, pcov, logistic = fit_logistic_model(days, mean) if popt is not None: fit_curve = logistic(days_smooth, *popt) ax3.plot(days_smooth, fit_curve, '-', color=color, linewidth=2, label=name) ax3.plot(days, mean, 'o', color=color, markersize=4, alpha=0.7) # 显示参数 param_text = f"{name}: K={popt[0]:.1f}, r={popt[1]:.3f}" ax3.text(0.02, 0.95-i*0.06, param_text, transform=ax3.transAxes, fontsize=8, color=color) ax3.set_xlabel('Days after planting') ax3.set_ylabel('Plant height (cm)') ax3.set_title('Logistic Model Fitting') ax3.grid(True, alpha=0.3) # 4. 增长速率 ax4 = fig.add_subplot(gs[1, 2]) for i, (group, color, name) in enumerate(zip(group_names, colors, display_names)): mean = results[group]['mean'] popt, pcov, logistic = fit_logistic_model(days, mean) if popt is not None: # 计算导数 def derivative(t, K, r, t0, L): return K * r * np.exp(-r*(t-t0)) / (1 + np.exp(-r*(t-t0)))**2 rate = derivative(days_smooth, *popt) ax4.plot(days_smooth, rate, '-', color=color, linewidth=2, label=name) ax4.set_xlabel('Days') ax4.set_ylabel('Rate (cm/day)') ax4.set_title('Growth Rate') ax4.grid(True, alpha=0.3) # 5. 统计结果热图 ax5 = fig.add_subplot(gs[2, :]) # 创建p值矩阵 p_matrix = np.ones((3, 3)) for comp in stats_results['pairwise']: i = group_names.index(comp['group1']) j = group_names.index(comp['group2']) p_matrix[i, j] = comp['p_value'] p_matrix[j, i] = comp['p_value'] # 绘制热图 im = ax5.imshow(p_matrix, cmap='RdYlGn_r', vmin=0, vmax=0.05) # 设置刻度标签 ax5.set_xticks(range(3)) ax5.set_yticks(range(3)) ax5.set_xticklabels(display_names) ax5.set_yticklabels(display_names) # 添加p值文本 for i in range(3): for j in range(3): if i != j: text = ax5.text(j, i, f'{p_matrix[i, j]:.3f}', ha="center", va="center", color="black", fontsize=9) ax5.set_title('Pairwise Comparison P-values (ANOVA F={:.2f}, p={:.4f})'.format( stats_results['anova']['f_stat'], stats_results['anova']['p_value'])) # 添加颜色条 cbar = plt.colorbar(im, ax=ax5, shrink=0.8) cbar.set_label('p-value', rotation=270, labelpad=15) # 整体标题 fig.suptitle('Comprehensive Plant Growth Analysis', fontsize=16, fontweight='bold', y=0.995) return fig # 6. 主执行函数 def main(): """主执行流程""" print("=" * 60) print("植物生长曲线分析系统") print("=" * 60) # 1. 生成数据 print("\n[1/5] 生成模拟数据...") df = generate_sample_data() print(f"数据形状: {df.shape}") print(df.head()) # 2. 处理数据 print("\n[2/5] 处理数据...") results = process_data(df) print("处理完成!") # 3. 统计分析 print("\n[3/5] 执行统计分析...") stats_results = perform_statistical_analysis(results) print(f"ANOVA结果: F={stats_results['anova']['f_stat']:.3f}, p={stats_results['anova']['p_value']:.4f}") # 4. 创建图表 print("\n[4/5] 生成图表...") fig = create_comprehensive_plot(df, results, stats_results) # 5. 保存结果 print("\n[5/5] 保存结果...") plt.savefig('comprehensive_growth_analysis.png', dpi=300, bbox_inches='tight') print("图表已保存为: comprehensive_growth_analysis.png") # 显示统计摘要 print("\n" + "=" * 60) print("统计摘要") print("=" * 60) for group in ['Control', 'Treatment1', 'Treatment2']: mean_final = results[group]['mean'][-1] std_final = results[group]['std'][-1] print(f"{group}: {mean_final:.2f} ± {std_final:.2f} cm") print("\n两两比较结果:") for comp in stats_results['pairwise']: sig = "***" if comp['p_value'] < 0.001 else "**" if comp['p_value'] < 0.01 else "*" if comp['p_value'] < 0.05 else "ns" print(f" {comp['group1']} vs {comp['group2']}: p={comp['p_value']:.4f} {sig}") plt.show() if __name__ == "__main__": main() 8. 常见问题与解决方案 8.1 数据质量问题 问题1:数据缺失 # 处理缺失值 df_filled = df.fillna(method='ffill') # 向前填充 # 或使用插值 df_interpolated = df.interpolate(method='linear') 问题2:异常值检测 # 使用IQR方法检测异常值 def detect_outliers_iqr(data, factor=1.5): Q1 = np.percentile(data, 25) Q3 = np.percentile(data, 75) IQR = Q3 - Q1 lower_bound = Q1 - factor * IQR upper_bound = Q3 + factor * IQR return np.where((data < lower_bound) | (data > upper_bound))

# 应用示例
outliers = detect_outliers_iqr(control_repeats[-1])
print(f”检测到的异常值索引: {outliers}”)
8.2 绘图问题
问题3:中文显示乱码
# 设置中文字体
plt.rcParams[‘font.sans-serif’] = [‘SimHei’, ‘Arial Unicode MS’, ‘DejaVu Sans’]
plt.rcParams[‘axes.unicode_minus’] = False # 解决负号显示问题
问题4:图形元素重叠
# 调整透明度和标记大小
plt.plot(x, y, alpha=0.7, markersize=3)
# 或使用seaborn的抖动功能
import seaborn as sns
sns.stripplot(x=’group’, y=’value’, data=df, jitter=True)
8.3 统计分析问题
问题5:数据不满足正态分布
# 使用非参数检验
from scipy.stats import mannwhitneyu, kruskal

# Kruskal-Wallis检验(非参数ANOVA)
h_stat, p_val = kruskal(*final_heights)

# Mann-Whitney U检验(非参数t检验)
u_stat, p_val = mannwhitneyu(control_final, t1_final)
9. 总结与最佳实践
9.1 关键要点总结
数据准备
:确保数据格式规范,包含时间序列和重复样本
误差分析
:始终计算并显示标准差或标准误差
模型拟合
:使用Logistic模型可以更好地描述植物生长规律
统计检验
:进行适当的统计检验以验证结果的显著性
可视化质量
:使用出版级设置确保图表质量
9.2 性能优化建议
# 对于大数据集,使用向量化操作
# 避免循环,使用numpy数组操作

# 不推荐
results = []
for i in range(len(data)):
results.append(calculate_something(data[i]))

# 推荐
results = np.vectorize(calculate_something)(data)

# 使用内存映射处理超大文件
import numpy as np
data = np.memmap(‘large_data.dat’, dtype=’float32′, mode=’r’, shape=(1000000, 100))
9.3 代码复用建议
将常用功能封装成函数或类:
class PlantGrowthAnalyzer:
def __init__(self, data_file):
self.data = pd.read_csv(data_file)
self.results = None

def process(self):
# 处理数据
pass

def plot(self):
# 绘图
pass

def analyze(self):
# 统计分析
pass

def save_report(self, output_dir):
# 保存报告
pass

# 使用
analyzer = PlantGrowthAnalyzer(‘experiment_data.csv’)
analyzer.process()
analyzer.plot()
analyzer.analyze()
analyzer.save_report(‘results/’)
通过本指南,您应该能够使用Matplotlib创建专业、准确、美观的植物生长曲线,并进行深入的数据分析。记住,好的可视化不仅仅是美观的图表,更重要的是能够清晰地传达科学发现和数据背后的故事。
# Matplotlib绘制植物生长曲线:从数据到可视化分析的完整指南
引言
植物生长曲线是植物生理学和农业科学研究中的重要工具,它展示了植物在不同生长阶段的高度、生物量或其他指标随时间的变化规律。通过绘制生长曲线,研究人员可以直观地观察植物的生长趋势,识别关键生长阶段,并评估不同环境条件或处理对植物生长的影响。
Matplotlib是Python中最流行的数据可视化库之一,它提供了强大而灵活的工具来创建高质量的科学图表。本指南将详细介绍如何使用Matplotlib从原始数据创建专业的植物生长曲线,包括数据准备、基础绘图、高级定制和统计分析等完整流程。
1. 环境准备和数据结构
1.1 安装必要的库
首先,确保安装了必要的Python库:
# 安装命令(在终端中执行)
pip install matplotlib numpy pandas scipy
1.2 数据结构设计
植物生长数据通常采用表格形式,包含以下关键列:
时间/天数
:X轴,表示实验天数
株高/生物量
:Y轴,表示测量值
处理组
:不同实验条件(如不同肥料、光照、水分等)
重复
:每个处理组的重复样本数
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 示例数据结构
data = {
‘Day’: [0, 3, 7, 10, 14, 17, 21, 24, 28, 31, 35],
‘Height_Control’: [2.1, 2.3, 2.8, 3.5, 4.2, 5.1, 6.2, 7.4, 8.8, 10.2, 11.5],
‘Height_Treatment1’: [2.1, 2.4, 3.1, 4.0, 5.2, 6.5, 8.1, 9.8, 11.7, 13.6, 15.5],
‘Height_Treatment2′: [2.1, 2.5, 3.3, 4.5, 6.0, 7.8, 9.9, 12.3, 14.9, 17.6, 20.3]
}

df = pd.DataFrame(data)
print(df)
2. 基础生长曲线绘制
2.1 创建第一个生长曲线
让我们从最简单的单组生长曲线开始:
import matplotlib.pyplot as plt
import numpy as np

# 准备数据
days = np.array([0, 3, 7, 10, 14, 17, 21, 24, 28, 31, 35])
height_control = np.array([2.1, 2.3, 2.8, 3.5, 4.2, 5.1, 6.2, 7.4, 8.8, 10.2, 11.5])

# 创建图形和轴对象
fig, ax = plt.subplots(figsize=(10, 6))

# 绘制基础曲线
ax.plot(days, height_control,
color=’blue’,
linewidth=2,
marker=’o’,
markersize=6,
label=’Control Group’)

# 设置标题和标签
ax.set_title(‘Plant Growth Curve – Control Group’, fontsize=14, fontweight=’bold’)
ax.set_xlabel(‘Days After Planting’, fontsize=12)
ax.set_ylabel(‘Plant Height (cm)’, fontsize=12)

# 添加网格和图例
ax.grid(True, alpha=0.3)
ax.legend()

# 显示图形
plt.tight_layout()
plt.show()
2.2 多组生长曲线对比
在实际研究中,我们通常需要比较不同处理组的生长情况:
# 多组数据对比
height_treatment1 = np.array([2.1, 2.4, 3.1, 4.0, 5.2, 6.5, 8.1, 9.8, 11.7, 13.6, 15.5])
height_treatment2 = np.array([2.1, 2.5, 3.3, 4.5, 6.0, 7.8, 9.9, 12.3, 14.9, 17.6, 20.3])

fig, ax = plt.subplots(figsize=(12, 7))

# 绘制多条曲线
ax.plot(days, height_control, ‘o-‘, color=’blue’, linewidth=2, label=’Control’, alpha=0.8)
ax.plot(days, height_treatment1, ‘s-‘, color=’green’, linewidth=2, label=’Treatment 1′, alpha=0.8)
ax.plot(days, height_treatment2, ‘^-‘, color=’red’, linewidth=2, label=’Treatment 2′, alpha=0.8)

# 美化图表
ax.set_title(‘Comparative Plant Growth Curves’, fontsize=16, fontweight=’bold’, pad=20)
ax.set_xlabel(‘Days After Planting’, fontsize=12)
ax.set_ylabel(‘Plant Height (cm)’, fontsize=12)
ax.grid(True, alpha=0.3, linestyle=’–‘)
ax.legend(loc=’upper left’, fontsize=10)

# 设置坐标轴范围
ax.set_xlim(0, 35)
ax.set_ylim(0, 22)

plt.tight_layout()
plt.show()
3. 数据处理与误差分析
3.1 处理重复样本数据
在实际实验中,每个时间点通常有多个重复样本。我们需要计算平均值和标准误差:
# 模拟重复样本数据(每个时间点3个重复)
np.random.seed(42)
days = np.array([0, 3, 7, 10, 14, 17, 21, 24, 28, 31, 35])

# 生成带噪声的重复数据
control_repeats = []
treatment1_repeats = []
treatment2_repeats = []

for i, day in enumerate(days):
# Control组:基础值 + 随机噪声
base_control = 2.0 + 0.3 * day * 0.3 # 增长趋势
control_repeats.append([base_control + np.random.normal(0, 0.2) for _ in range(3)])

# Treatment1组
base_t1 = 2.0 + 0.35 * day * 0.35
treatment1_repeats.append([base_t1 + np.random.normal(0, 0.2) for _ in range(3)])

# Treatment2组
base_t2 = 2.0 + 0.42 * day * 0.42
treatment2_repeats.append([base_t2 + np.random.normal(0, 0.2) for _ in range(3)])

# 转换为numpy数组
control_repeats = np.array(control_repeats)
treatment1_repeats = np.array(treatment1_repeats)
treatment2_repeats = np.array(treatment2_repeats)

# 计算平均值和标准误差
control_mean = np.mean(control_repeats, axis=1)
control_std = np.std(control_repeats, axis=1)

treatment1_mean = np.mean(treatment1_repeats, axis=1)
treatment1_std = np.std(treatment1_repeats, axis=1)

treatment2_mean = np.mean(treatment2_repeats, axis=1)
treatment2_std = np.std(treatment2_repeats, axis=1)

print(“Control组平均值:”, control_mean)
print(“Control组标准差:”, control_std)
3.2 绘制带误差带的生长曲线
fig, ax = plt.subplots(figsize=(12, 7))

# 绘制带误差带的曲线
# Control组
ax.plot(days, control_mean, ‘o-‘, color=’blue’, linewidth=2, label=’Control’, zorder=3)
ax.fill_between(days,
control_mean – control_std,
control_mean + control_std,
color=’blue’, alpha=0.2, label=’±SD (Control)’)

# Treatment1组
ax.plot(days, treatment1_mean, ‘s-‘, color=’green’, linewidth=2, label=’Treatment 1′, zorder=3)
ax.fill_between(days,
treatment1_mean – treatment1_std,
treatment1_mean + treatment1_std,
color=’green’, alpha=0.2, label=’±SD (Treatment 1)’)

# Treatment2组
ax.plot(days, treatment2_mean, ‘^-‘, color=’red’, linewidth=2, label=’Treatment 2′, zorder=3)
ax.fill_between(days,
treatment2_mean – treatment2_std,
treatment2_mean + treatment2_std,
color=’red’, alpha=0.2, label=’±SD (Treatment 2)’)

# 美化图表
ax.set_title(‘Plant Growth Curves with Error Bands’, fontsize=16, fontweight=’bold’, pad=20)
ax.set_xlabel(‘Days After Planting’, fontsize=12)
ax.set_ylabel(‘Plant Height (cm)’, fontsize=12)
ax.grid(True, alpha=0.3, linestyle=’–‘)
ax.legend(loc=’upper left’, fontsize=9, ncol=2)

plt.tight_layout()
plt.show()
4. 高级可视化技巧
4.1 添加趋势线和拟合曲线
植物生长通常遵循S形曲线(Logistic生长模型)。我们可以使用scipy进行曲线拟合:
from scipy.optimize import curve_fit

# Logistic生长模型
def logistic_growth(t, K, r, t0, L):
“””
Logistic生长模型: L + K / (1 + exp(-r*(t-t0)))
K: 最大生长量
r: 生长速率
t0: 拐点时间
L: 初始值
“””
return L + K / (1 + np.exp(-r * (t – t0)))

# 拟合Control组数据
popt_control, pcov_control = curve_fit(logistic_growth, days, control_mean,
p0=[10, 0.2, 15, 2], maxfev=5000)

# 生成平滑曲线用于绘图
days_smooth = np.linspace(0, 35, 100)
control_fit = logistic_growth(days_smooth, *popt_control)

# 拟合Treatment1组数据
popt_t1, pcov_t1 = curve_fit(logistic_growth, days, treatment1_mean,
p0=[12, 0.25, 15, 2], maxfev=5000)
treatment1_fit = logistic_growth(days_smooth, *popt_t1)

# 拟合Treatment2组数据
popt_t2, pcov_t2 = curve_fit(logistic_growth, days, treatment2_mean,
p0=[15, 0.3, 15, 2], maxfev=5000)
treatment2_fit = logistic_growth(days_smooth, *popt_t2)

# 绘制拟合曲线
fig, ax = plt.subplots(figsize=(12, 7))

# 原始数据点
ax.plot(days, control_mean, ‘o’, color=’blue’, markersize=6, label=’Control (data)’)
ax.plot(days, treatment1_mean, ‘s’, color=’green’, markersize=6, label=’Treatment 1 (data)’)
ax.plot(days, treatment2_mean, ‘^’, color=’red’, markersize=6, label=’Treatment 2 (data)’)

# 拟合曲线
ax.plot(days_smooth, control_fit, ‘-‘, color=’blue’, linewidth=2, label=’Control (fit)’)
ax.plot(days_smooth, treatment1_fit, ‘-‘, color=’green’, linewidth=2, label=’Treatment 1 (fit)’)
ax.plot(days_smooth, treatment2_fit, ‘-‘, color=’red’, linewidth=2, label=’Treatment 2 (fit)’)

# 添加拟合参数文本框
textstr = ‘\n’.join([
f’Control: K={popt_control[0]:.1f}, r={popt_control[1]:.3f}’,
f’T1: K={popt_t1[0]:.1f}, r={popt_t1[1]:.3f}’,
f’T2: K={popt_t2[0]:.1f}, r={popt_t2[1]:.3f}’
])
props = dict(boxstyle=’round’, facecolor=’wheat’, alpha=0.5)
ax.text(0.02, 0.98, textstr, transform=ax.transAxes, fontsize=9,
verticalalignment=’top’, bbox=props)

ax.set_title(‘Plant Growth with Logistic Model Fitting’, fontsize=16, fontweight=’bold’)
ax.set_xlabel(‘Days After Planting’, fontsize=12)
ax.set_ylabel(‘Plant Height (cm)’, fontsize=12)
ax.grid(True, alpha=0.3)
ax.legend(loc=’upper left’, fontsize=9)

plt.tight_layout()
plt.show()
4.2 子图布局:原始数据、拟合曲线、增长率
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle(‘Comprehensive Growth Analysis’, fontsize=18, fontweight=’bold’)

# 1. 原始数据与误差带
ax1 = axes[0, 0]
ax1.plot(days, control_mean, ‘o-‘, color=’blue’, label=’Control’)
ax1.fill_between(days, control_mean-control_std, control_mean+control_std, alpha=0.2, color=’blue’)
ax1.plot(days, treatment1_mean, ‘s-‘, color=’green’, label=’Treatment 1′)
ax1.fill_between(days, treatment1_mean-treatment1_std, treatment1_mean+treatment1_std, alpha=0.2, color=’green’)
ax1.set_title(‘Raw Data with Error Bands’)
ax1.set_xlabel(‘Days’)
ax1.set_ylabel(‘Height (cm)’)
ax1.grid(True, alpha=0.3)
ax1.legend()

# 2. Logistic拟合曲线
ax2 = axes[0, 1]
ax2.plot(days_smooth, control_fit, ‘-‘, color=’blue’, label=’Control’)
ax2.plot(days_smooth, treatment1_fit, ‘-‘, color=’green’, label=’Treatment 1′)
ax2.plot(days_smooth, treatment2_fit, ‘-‘, color=’red’, label=’Treatment 2′)
ax2.set_title(‘Logistic Model Fits’)
ax2.set_xlabel(‘Days’)
ax2.set_ylabel(‘Height (cm)’)
ax2.grid(True, alpha=0.3)
ax2.legend()

# 3. 增长速率(导数)
ax3 = axes[1, 0]
# 计算拟合曲线的导数(增长率)
def logistic_derivative(t, K, r, t0, L):
return K * r * np.exp(-r*(t-t0)) / (1 + np.exp(-r*(t-t0)))**2

control_rate = logistic_derivative(days_smooth, *popt_control)
treatment1_rate = logistic_derivative(days_smooth, *popt_t1)
treatment2_rate = logistic_derivative(days_smooth, *popt_t2)

ax3.plot(days_smooth, control_rate, ‘-‘, color=’blue’, label=’Control’)
ax3.plot(days_smooth, treatment1_rate, ‘-‘, color=’green’, label=’Treatment 1′)
ax3.plot(days_smooth, treatment2_rate, ‘-‘, color=’red’, label=’Treatment 2′)
ax3.set_title(‘Growth Rate (Derivative)’)
ax3.set_xlabel(‘Days’)
ax3.set_ylabel(‘Rate (cm/day)’)
ax3.grid(True, alpha=0.3)
ax3.legend()

# 4. 累积生物量(积分)
ax4 = axes[1, 1]
# 计算拟合曲线的积分(累积生长量)
from scipy.integrate import cumulative_trapezoid

control_integral = cumulative_trapezoid(control_fit, days_smooth, initial=0)
treatment1_integral = cumulative_trapezoid(treatment1_fit, days_smooth, initial=0)
treatment2_integral = cumulative_trapezoid(treatment2_fit, days_smooth, initial=0)

ax4.plot(days_smooth, control_integral, ‘-‘, color=’blue’, label=’Control’)
ax4.plot(days_smooth, treatment1_integral, ‘-‘, color=’green’, label=’Treatment 1′)
ax4.plot(days_smooth, treatment2_integral, ‘-‘, color=’red’, label=’Treatment 2′)
ax4.set_title(‘Cumulative Growth (Integral)’)
ax4.set_xlabel(‘Days’)
ax4.set_ylabel(‘Cumulative Height (cm·day)’)
ax4.grid(True, alpha=0.3)
ax4.legend()

plt.tight_layout()
plt.show()
5. 统计分析与显著性检验
5.1 计算生长参数
# 计算关键生长参数
def calculate_growth_parameters(days, heights):
“””
计算植物生长关键参数
“””
# 最终高度
final_height = heights[-1]

# 总生长量
total_growth = heights[-1] – heights[0]

# 平均日增长
avg_daily_growth = total_growth / days[-1]

# 最大日增长(相邻两天差值的最大值)
daily_increments = np.diff(heights)
max_daily_growth = np.max(daily_increments)

# 达到50%最终高度的时间
half_final = heights[0] + total_growth * 0.5
idx_half = np.where(heights >= half_final)[0][0]
days_to_half = days[idx_half]

return {
‘Final Height’: final_height,
‘Total Growth’: total_growth,
‘Avg Daily Growth’: avg_daily_growth,
‘Max Daily Growth’: max_daily_growth,
‘Days to 50% Height’: days_to_half
}

# 计算各组参数
params_control = calculate_growth_parameters(days, control_mean)
params_t1 = calculate_growth_parameters(days, treatment1_mean)
params_t2 = calculate_growth_parameters(days, treatment2_mean)

# 创建参数对比表格
import pandas as pd
params_df = pd.DataFrame({
‘Control’: params_control,
‘Treatment 1’: params_t1,
‘Treatment 2’: params_t2
})

print(“生长参数对比:”)
print(params_df.round(2))
5.2 显著性检验(t检验)
from scipy import stats

# 进行最终高度的t检验
# 假设我们有最终时间点的重复样本数据
final_day = 35
control_final = control_repeats[-1] # Control组最终高度的3个重复
t1_final = treatment1_repeats[-1] # Treatment1组最终高度的3个重复
t2_final = treatment2_repeats[-1] # Treatment2组最终高度的3个重复

# Control vs Treatment1
t_stat1, p_val1 = stats.ttest_ind(control_final, t1_final)
print(f”Control vs Treatment1: t={t_stat1:.3f}, p={p_val1:.4f}”)

# Control vs Treatment2
t_stat2, p_val2 = stats.ttest_ind(control_final, t2_final)
print(f”Control vs Treatment2: t={t_stat2:.3f}, p={p_val2:.4f}”)

# Treatment1 vs Treatment2
t_stat3, p_val3 = stats.ttest_ind(t1_final, t2_final)
print(f”Treatment1 vs Treatment2: t={t_stat3:.3f}, p={p_val3:.4f}”)

# 可视化显著性
fig, ax = plt.subplots(figsize=(8, 6))

# 箱线图显示最终高度分布
data_to_plot = [control_final, t1_final, t2_final]
bp = ax.boxplot(data_to_plot, labels=[‘Control’, ‘Treatment 1’, ‘Treatment 2′])

# 添加显著性标记
def add_significance(ax, data1, data2, x1, x2, y, p_value, text):
# 绘制显著性标记
ax.plot([x1, x1, x2, x2], [y, y+0.5, y+0.5, y], lw=1.5, c=’black’)
# 添加p值文本
significance = “***” if p_value < 0.001 else "**" if p_value < 0.01 else "*" if p_value < 0.05 else "ns" ax.text((x1+x2)*0.5, y+0.6, f"{significance}\n(p={p_value:.4f})", ha='center', fontsize=10) # 设置y轴范围 max_val = max(np.max(control_final), np.max(t1_final), np.max(t2_final)) ax.set_ylim(0, max_val * 1.3) # 添加显著性标记 add_significance(ax, control_final, t1_final, 1, 2, max_val*1.1, p_val1, "Control vs T1") add_significance(ax, control_final, t2_final, 1, 3, max_val*1.15, p_val2, "Control vs T2") add_significance(ax, t1_final, t2_final, 2, 3, max_val*1.2, p_val3, "T1 vs T2") ax.set_ylabel('Final Height (cm)', fontsize=12) ax.set_title('Final Height Distribution with Significance', fontsize=14, fontweight='bold') ax.grid(True, alpha=0.3, axis='y') plt.tight_layout() plt.show() 6. 专业出版级图表定制 6.1 出版级图表设置 # 设置matplotlib参数以适应出版要求 plt.rcParams.update({ 'font.family': 'sans-serif', 'font.sans-serif': ['Arial', 'DejaVu Sans'], 'font.size': 10, 'axes.linewidth': 0.8, 'axes.labelsize': 10, 'axes.titlesize': 12, 'xtick.major.size': 3, 'xtick.minor.size': 1.5, 'ytick.major.size': 3, 'ytick.minor.size': 1.5, 'legend.fontsize': 9, 'legend.frameon': False, 'figure.dpi': 300, 'savefig.dpi': 300 }) # 创建出版级图表 fig, ax = plt.subplots(figsize=(3.5, 2.8), dpi=300) # 单栏宽度约8.7cm # 使用更专业的颜色方案(ColorBrewer) colors = ['#377eb8', '#4daf4a', '#e41a1c'] # 蓝、绿、红 # 绘制数据 ax.plot(days, control_mean, 'o-', color=colors[0], linewidth=1.5, markersize=4, markerfacecolor='white', markeredgewidth=1.5, label='Control') ax.plot(days, treatment1_mean, 's-', color=colors[1], linewidth=1.5, markersize=4, markerfacecolor='white', markeredgewidth=1.5, label='Treatment 1') ax.plot(days, treatment2_mean, '^-', color=colors[2], linewidth=1.5, markersize=4, markerfacecolor='white', markeredgewidth=1.5, label='Treatment 2') # 添加误差带(更细的透明度) ax.fill_between(days, control_mean-control_std, control_mean+control_std, color=colors[0], alpha=0.15, linewidth=0) ax.fill_between(days, treatment1_mean-treatment1_std, treatment1_mean+treatment1_std, color=colors[1], alpha=0.15, linewidth=0) ax.fill_between(days, treatment2_mean-treatment2_std, treatment2_mean+treatment2_std, color=colors[2], alpha=0.15, linewidth=0) # 设置标签和标题 ax.set_xlabel('Days after planting', fontsize=10) ax.set_ylabel('Plant height (cm)', fontsize=10) ax.set_title('Growth curves of different treatments', fontsize=11, pad=8) # 设置坐标轴 ax.set_xlim(0, 35) ax.set_ylim(0, 22) # 设置刻度 ax.set_xticks(np.arange(0, 36, 5)) ax.set_yticks(np.arange(0, 23, 5)) # 网格线(更细) ax.grid(True, alpha=0.2, linewidth=0.5, linestyle='--') # 图例(更紧凑) ax.legend(loc='upper left', fontsize=8, frameon=False, handlelength=2.5, columnspacing=1.0) # 移除顶部和右侧边框 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # 添加显著性标记(如果需要) # ax.text(20, 20, '*** p<0.001', fontsize=9, ha='center') plt.tight_layout() plt.savefig('plant_growth_curve.png', bbox_inches='tight', dpi=300) plt.show() 6.2 批量导出多种格式 def export_growth_chart(fig, filename_base, dpi=300): """ 批量导出图表为多种格式 """ formats = ['png', 'pdf', 'svg', 'eps'] for fmt in formats: filename = f"{filename_base}.{fmt}" fig.savefig(filename, format=fmt, bbox_inches='tight', dpi=dpi) print(f"导出: {filename}") # 使用示例 # export_growth_chart(fig, "plant_growth_analysis") 7. 完整工作流程示例 7.1 从原始数据到最终图表的完整脚本 """ 植物生长曲线分析完整工作流程 """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy import stats import seaborn as sns # 1. 数据准备 def generate_sample_data(): """生成模拟实验数据""" np.random.seed(42) days = np.array([0, 3, 7, 10, 14, 17, 21, 24, 28, 31, 35]) # 生成带重复的数据 data = {'Day': days} groups = ['Control', 'Treatment1', 'Treatment2'] base_heights = [2.0, 2.0, 2.0] growth_rates = [0.3, 0.35, 0.42] for group, base, rate in zip(groups, base_heights, growth_rates): for rep in range(1, 4): # Logistic生长 + 随机噪声 true_height = base + 10 / (1 + np.exp(-rate * (days - 15))) noise = np.random.normal(0, 0.3, len(days)) data[f'{group}_Rep{rep}'] = true_height + noise return pd.DataFrame(data) # 2. 数据处理 def process_data(df): """处理原始数据,计算统计量""" groups = ['Control', 'Treatment1', 'Treatment2'] results = {} for group in groups: # 提取重复数据 rep_cols = [col for col in df.columns if group in col] rep_data = df[rep_cols].values # 计算统计量 mean = np.mean(rep_data, axis=1) std = np.std(rep_data, axis=1) sem = stats.sem(rep_data, axis=1) # 标准误差 results[group] = { 'mean': mean, 'std': std, 'sem': sem, 'data': rep_data } return results # 3. 拟合模型 def fit_logistic_model(days, mean_values): """拟合Logistic生长模型""" def logistic(t, K, r, t0, L): return L + K / (1 + np.exp(-r * (t - t0))) try: popt, pcov = curve_fit(logistic, days, mean_values, p0=[10, 0.2, 15, 2], maxfev=5000) return popt, pcov, logistic except: return None, None, None # 4. 统计分析 def perform_statistical_analysis(results, final_day_idx=-1): """执行统计分析""" groups = list(results.keys()) final_heights = [results[g]['data'][final_day_idx] for g in groups] # 方差分析 f_stat, p_value = stats.f_oneway(*final_heights) # 两两比较 comparisons = [] for i in range(len(groups)): for j in range(i+1, len(groups)): t_stat, p_val = stats.ttest_ind(final_heights[i], final_heights[j]) comparisons.append({ 'group1': groups[i], 'group2': groups[j], 't_stat': t_stat, 'p_value': p_val, 'significant': p_val < 0.05 }) return { 'anova': {'f_stat': f_stat, 'p_value': p_value}, 'pairwise': comparisons } # 5. 可视化 def create_comprehensive_plot(df, results, stats_results): """创建综合分析图表""" days = df['Day'].values # 设置样式 plt.style.use('seaborn-v0_8-whitegrid') fig = plt.figure(figsize=(15, 10)) # 创建子图网格 gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3) # 1. 主生长曲线(带误差带) ax1 = fig.add_subplot(gs[0, :2]) colors = ['#377eb8', '#4daf4a', '#e41a1c'] group_names = ['Control', 'Treatment1', 'Treatment2'] display_names = ['Control', 'Treatment 1', 'Treatment 2'] for i, (group, color, name) in enumerate(zip(group_names, colors, display_names)): mean = results[group]['mean'] std = results[group]['std'] ax1.plot(days, mean, 'o-', color=color, linewidth=2, markersize=5, markerfacecolor='white', markeredgewidth=1.5, label=name) ax1.fill_between(days, mean-std, mean+std, color=color, alpha=0.15) ax1.set_xlabel('Days after planting') ax1.set_ylabel('Plant height (cm)') ax1.set_title('Growth Curves with Standard Deviation') ax1.legend(loc='upper left') ax1.grid(True, alpha=0.3) # 2. 最终高度对比(箱线图) ax2 = fig.add_subplot(gs[0, 2]) final_heights = [results[g]['data'][-1] for g in group_names] bp = ax2.boxplot(final_heights, labels=display_names, patch_artist=True) # 设置颜色 for patch, color in zip(bp['boxes'], colors): patch.set_facecolor(color) patch.set_alpha(0.3) ax2.set_ylabel('Final height (cm)') ax2.set_title('Final Height Distribution') ax2.grid(True, alpha=0.3, axis='y') # 3. Logistic拟合 ax3 = fig.add_subplot(gs[1, :2]) days_smooth = np.linspace(0, 35, 100) for i, (group, color, name) in enumerate(zip(group_names, colors, display_names)): mean = results[group]['mean'] popt, pcov, logistic = fit_logistic_model(days, mean) if popt is not None: fit_curve = logistic(days_smooth, *popt) ax3.plot(days_smooth, fit_curve, '-', color=color, linewidth=2, label=name) ax3.plot(days, mean, 'o', color=color, markersize=4, alpha=0.7) # 显示参数 param_text = f"{name}: K={popt[0]:.1f}, r={popt[1]:.3f}" ax3.text(0.02, 0.95-i*0.06, param_text, transform=ax3.transAxes, fontsize=8, color=color) ax3.set_xlabel('Days after planting') ax3.set_ylabel('Plant height (cm)') ax3.set_title('Logistic Model Fitting') ax3.grid(True, alpha=0.3) # 4. 增长速率 ax4 = fig.add_subplot(gs[1, 2]) for i, (group, color, name) in enumerate(zip(group_names, colors, display_names)): mean = results[group]['mean'] popt, pcov, logistic = fit_logistic_model(days, mean) if popt is not None: # 计算导数 def derivative(t, K, r, t0, L): return K * r * np.exp(-r*(t-t0)) / (1 + np.exp(-r*(t-t0)))**2 rate = derivative(days_smooth, *popt) ax4.plot(days_smooth, rate, '-', color=color, linewidth=2, label=name) ax4.set_xlabel('Days') ax4.set_ylabel('Rate (cm/day)') ax4.set_title('Growth Rate') ax4.grid(True, alpha=0.3) # 5. 统计结果热图 ax5 = fig.add_subplot(gs[2, :]) # 创建p值矩阵 p_matrix = np.ones((3, 3)) for comp in stats_results['pairwise']: i = group_names.index(comp['group1']) j = group_names.index(comp['group2']) p_matrix[i, j] = comp['p_value'] p_matrix[j, i] = comp['p_value'] # 绘制热图 im = ax5.imshow(p_matrix, cmap='RdYlGn_r', vmin=0, vmax=0.05) # 设置刻度标签 ax5.set_xticks(range(3)) ax5.set_yticks(range(3)) ax5.set_xticklabels(display_names) ax5.set_yticklabels(display_names) # 添加p值文本 for i in range(3): for j in range(3): if i != j: text = ax5.text(j, i, f'{p_matrix[i, j]:.3f}', ha="center", va="center", color="black", fontsize=9) ax5.set_title('Pairwise Comparison P-values (ANOVA F={:.2f}, p={:.4f})'.format( stats_results['anova']['f_stat'], stats_results['anova']['p_value'])) # 添加颜色条 cbar = plt.colorbar(im, ax=ax5, shrink=0.8) cbar.set_label('p-value', rotation=270, labelpad=15) # 整体标题 fig.suptitle('Comprehensive Plant Growth Analysis', fontsize=16, fontweight='bold', y=0.995) return fig # 6. 主执行函数 def main(): """主执行流程""" print("=" * 60) print("植物生长曲线分析系统") print("=" * 60) # 1. 生成数据 print("\n[1/5] 生成模拟数据...") df = generate_sample_data() print(f"数据形状: {df.shape}") print(df.head()) # 2. 处理数据 print("\n[2/5] 处理数据...") results = process_data(df) print("处理完成!") # 3. 统计分析 print("\n[3/5] 执行统计分析...") stats_results = perform_statistical_analysis(results) print(f"ANOVA结果: F={stats_results['anova']['f_stat']:.3f}, p={stats_results['anova']['p_value']:.4f}") # 4. 创建图表 print("\n[4/5] 生成图表...") fig = create_comprehensive_plot(df, results, stats_results) # 5. 保存结果 print("\n[5/5] 保存结果...") plt.savefig('comprehensive_growth_analysis.png', dpi=300, bbox_inches='tight') print("图表已保存为: comprehensive_growth_analysis.png") # 显示统计摘要 print("\n" + "=" * 60) print("统计摘要") print("=" * 60) for group in ['Control', 'Treatment1', 'Treatment2']: mean_final = results[group]['mean'][-1] std_final = results[group]['std'][-1] print(f"{group}: {mean_final:.2f} ± {std_final:.2f} cm") print("\n两两比较结果:") for comp in stats_results['pairwise']: sig = "***" if comp['p_value'] < 0.001 else "**" if comp['p_value'] < 0.01 else "*" if comp['p_value'] < 0.05 else "ns" print(f" {comp['group1']} vs {comp['group2']}: p={comp['p_value']:.4f} {sig}") plt.show() if __name__ == "__main__": main() 8. 常见问题与解决方案 8.1 数据质量问题 问题1:数据缺失 # 处理缺失值 df_filled = df.fillna(method='ffill') # 向前填充 # 或使用插值 df_interpolated = df.interpolate(method='linear') 问题2:异常值检测 # 使用IQR方法检测异常值 def detect_outliers_iqr(data, factor=1.5): Q1 = np.percentile(data, 25) Q3 = np.percentile(data, 75) IQR = Q3 - Q1 lower_bound = Q1 - factor * IQR upper_bound = Q3 + factor * IQR return np.where((data < lower_bound) | (data > upper_bound))

# 应用示例
outliers = detect_outliers_iqr(control_repeats[-1])
print(f”检测到的异常值索引: {outliers}”)
8.2 绘图问题
问题3:中文显示乱码
# 设置中文字体
plt.rcParams[‘font.sans-serif’] = [‘SimHei’, ‘Arial Unicode MS’, ‘DejaVu Sans’]
plt.rcParams[‘axes.unicode_minus’] = False # 解决负号显示问题
问题4:图形元素重叠
# 调整透明度和标记大小
plt.plot(x, y, alpha=0.7, markersize=3)
# 或使用seaborn的抖动功能
import seaborn as sns
sns.stripplot(x=’group’, y=’value’, data=df, jitter=True)
8.3 统计分析问题
问题5:数据不满足正态分布
# 使用非参数检验
from scipy.stats import mannwhitneyu, kruskal

# Kruskal-Wallis检验(非参数ANOVA)
h_stat, p_val = kruskal(*final_heights)

# Mann-Whitney U检验(非参数t检验)
u_stat, p_val = mannwhitneyu(control_final, t1_final)
9. 总结与最佳实践
9.1 关键要点总结
数据准备
:确保数据格式规范,包含时间序列和重复样本
误差分析
:始终计算并显示标准差或标准误差
模型拟合
:使用Logistic模型可以更好地描述植物生长规律
统计检验
:进行适当的统计检验以验证结果的显著性
可视化质量
:使用出版级设置确保图表质量
9.2 性能优化建议
# 对于大数据集,使用向量化操作
# 避免循环,使用numpy数组操作

# 不推荐
results = []
for i in range(len(data)):
results.append(calculate_something(data[i]))

# 推荐
results = np.vectorize(calculate_something)(data)

# 使用内存映射处理超大文件
import numpy as np
data = np.memmap(‘large_data.dat’, dtype=’float32′, mode=’r’, shape=(1000000, 100))
9.3 代码复用建议
将常用功能封装成函数或类:
class PlantGrowthAnalyzer:
def __init__(self, data_file):
self.data = pd.read_csv(data_file)
self.results = None

def process(self):
# 处理数据
pass

def plot(self):
# 绘图
pass

def analyze(self):
# 统计分析
pass

def save_report(self, output_dir):
# 保存报告
pass

# 使用
analyzer = PlantGrowthAnalyzer(‘experiment_data.csv’)
analyzer.process()
analyzer.plot()
analyzer.analyze()
analyzer.save_report(‘results/’)
通过本指南,您应该能够使用Matplotlib创建专业、准确、美观的植物生长曲线,并进行深入的数据分析。记住,好的可视化不仅仅是美观的图表,更重要的是能够清晰地传达科学发现和数据背后的故事。