好的!以下是用Python实现科研绘图的入门指南,包含核心库介绍、常用图表类型及代码示例:


一、核心工具库

  1. Matplotlib

    • 基础绘图库,支持PDF/SVG矢量图输出
    • 关键模块:pyplot(快速绘图)、axes(精细控制)
    • 科研适配:
      import matplotlib.pyplot as plt
      plt.rcParams.update({
          'font.family': 'serif',       # 学术期刊常用衬线字体
          'mathtext.fontset': 'stix'    # 数学公式字体
      })
      

  2. Seaborn

    • 基于Matplotlib的统计图表库
    • 优势:一键生成箱线图、分布图等统计可视化
    import seaborn as sns
    sns.set_theme(context='paper', style='ticks')  # 学术论文风格
    

  3. SciencePlots(扩展包)

    • 预置学术出版级样式
    pip install SciencePlots
    

    plt.style.use(['science', 'ieee'])  # IEEE期刊样式
    


二、典型科研图表实现

1. 带误差棒的折线图
import numpy as np

x = np.linspace(0, 10, 5)
y = np.sin(x)
y_err = 0.1 * np.random.rand(5)

plt.errorbar(x, y, yerr=y_err, capsize=4, marker='o', linestyle='--')
plt.xlabel('时间 (s)')
plt.ylabel('电压 (mV)')
plt.savefig('plot.pdf', dpi=300, bbox_inches='tight')  # 300dpi矢量图

2. 多子图复杂布局
fig, axs = plt.subplots(2, 2, figsize=(10, 8))

# 子图1:散点图
axs[0,0].scatter(x, y, s=10, alpha=0.7)

# 子图2:带数学公式标注
x = np.linspace(-5, 5, 100)
axs[0,1].plot(x, np.exp(-x**2))
axs[0,1].text(0, 0.8, r'$f(x) = e^{-x^2}$', fontsize=12)

# 子图3:热力图
data = np.random.rand(10,10)
axs[1,0].imshow(data, cmap='viridis')

# 子图4:3D图
ax = fig.add_subplot(2, 2, 4, projection='3d')
X, Y = np.meshgrid(x, x)
ax.plot_surface(X, Y, np.sin(X+Y))


三、出版级优化技巧

  1. 矢量图导出

    plt.savefig('figure.svg', format='svg')  # 避免分辨率损失
    

  2. LaTeX公式集成

    plt.title(r'$\frac{\partial T}{\partial t} = \alpha\nabla^2 T$')
    

  3. 颜色映射规范

    • 使用cividisviridis(色盲友好)
    plt.imshow(data, cmap='viridis')
    


四、完整工作流示例

# 数据预处理
import pandas as pd
data = pd.read_csv('experiment_data.csv')

# 绘图配置
plt.style.use('science')
fig, ax = plt.subplots(figsize=(6,4))

# 核心绘图
sns.lineplot(data=data, x='Wavelength', y='Intensity', hue='Sample', ax=ax)

# 学术标注
ax.annotate('Peak at 532nm', xy=(532, 0.9), xytext=(550, 0.7),
            arrowprops=dict(arrowstyle="->", color='black'))

# 输出
plt.savefig('spectrum.tif', dpi=300, format='tiff')


提示:建议结合Jupyter Notebook实时调试,通过%matplotlib inline即时预览绘图效果。对于复杂图表,可使用GridSpec实现非均匀子图布局。

Logo

小龙虾开发者社区是 CSDN 旗下专注 OpenClaw 生态的官方阵地,聚焦技能开发、插件实践与部署教程,为开发者提供可直接落地的方案、工具与交流平台,助力高效构建与落地 AI 应用

更多推荐